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"),
700 { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","amsa","jar" },
702 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" },
707 chooser.setFileView(new JalviewFileView());
708 chooser.setDialogTitle("Save Alignment to file");
709 chooser.setToolTipText("Save");
711 int value = chooser.showSaveDialog(this);
713 if (value == JalviewFileChooser.APPROVE_OPTION)
715 currentFileFormat = chooser.getSelectedFormat();
716 if (currentFileFormat == null)
718 JOptionPane.showInternalMessageDialog(Desktop.desktop,
719 "You must select a file format before saving!",
720 "File format not specified",
721 JOptionPane.WARNING_MESSAGE);
722 value = chooser.showSaveDialog(this);
726 fileName = chooser.getSelectedFile().getPath();
728 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
731 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
732 if (currentFileFormat.indexOf(" ")>-1)
734 currentFileFormat = currentFileFormat.substring(0, currentFileFormat.indexOf(" "));
736 saveAlignment(fileName, currentFileFormat);
740 public boolean saveAlignment(String file, String format)
742 boolean success = true;
744 if (format.equalsIgnoreCase("Jalview"))
746 String shortName = title;
748 if (shortName.indexOf(java.io.File.separatorChar) > -1)
750 shortName = shortName.substring(shortName.lastIndexOf(
751 java.io.File.separatorChar) + 1);
754 success = new Jalview2XML().SaveAlignment(this, file, shortName);
756 statusBar.setText("Successfully saved to file: "
758 +format +" format.");
764 String[] omitHidden = null;
766 if (viewport.hasHiddenColumns)
768 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
769 "The Alignment contains hidden columns."
770 + "\nDo you want to save only the visible alignment?",
771 "Save / Omit Hidden Columns",
772 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
774 if (reply == JOptionPane.YES_OPTION)
776 omitHidden = viewport.getViewAsString(false);
779 FormatAdapter f = new FormatAdapter();
781 String output = f.formatSequences(
783 (Alignment) viewport.alignment, // class cast exceptions will occur in the distant future
784 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
794 java.io.PrintWriter out = new java.io.PrintWriter(
795 new java.io.FileWriter(file));
800 statusBar.setText("Successfully saved to file: "
802 + format + " format.");
807 ex.printStackTrace();
814 JOptionPane.showInternalMessageDialog(
815 this, "Couldn't save file: " + fileName,
817 JOptionPane.WARNING_MESSAGE);
826 * @param e DOCUMENT ME!
828 protected void outputText_actionPerformed(ActionEvent e)
830 String [] omitHidden = null;
832 if(viewport.hasHiddenColumns)
834 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
835 "The Alignment contains hidden columns."
836 +"\nDo you want to output only the visible alignment?",
837 "Save / Omit Hidden Columns",
838 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
840 if(reply==JOptionPane.YES_OPTION)
842 omitHidden = viewport.getViewAsString(false);
846 CutAndPasteTransfer cap = new CutAndPasteTransfer();
847 cap.setForInput(null);
848 Desktop.addInternalFrame(cap,
849 "Alignment output - " + e.getActionCommand(), 600,
853 cap.setText(new FormatAdapter().formatSequences(
854 e.getActionCommand(),
856 omitHidden, viewport.colSel));
862 * @param e DOCUMENT ME!
864 protected void htmlMenuItem_actionPerformed(ActionEvent e)
866 new HTMLOutput(alignPanel,
867 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
868 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
871 public void createImageMap(File file, String image)
873 alignPanel.makePNGImageMap(file, image);
879 * @param e DOCUMENT ME!
881 public void createPNG(File f)
883 alignPanel.makePNG(f);
889 * @param e DOCUMENT ME!
891 public void createEPS(File f)
893 alignPanel.makeEPS(f);
897 public void pageSetup_actionPerformed(ActionEvent e)
899 PrinterJob printJob = PrinterJob.getPrinterJob();
900 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
906 * @param e DOCUMENT ME!
908 public void printMenuItem_actionPerformed(ActionEvent e)
910 //Putting in a thread avoids Swing painting problems
911 PrintThread thread = new PrintThread(alignPanel);
915 public void exportFeatures_actionPerformed(ActionEvent e)
917 new AnnotationExporter().exportFeatures(alignPanel);
921 public void exportAnnotations_actionPerformed(ActionEvent e)
923 new AnnotationExporter().exportAnnotations(
925 viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
926 viewport.alignment.getGroups(),
927 ((Alignment)viewport.alignment).alignmentProperties
932 public void associatedData_actionPerformed(ActionEvent e)
934 // Pick the tree file
935 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
938 chooser.setFileView(new JalviewFileView());
939 chooser.setDialogTitle("Load Jalview Annotations or Features File");
940 chooser.setToolTipText("Load Jalview Annotations / Features file");
942 int value = chooser.showOpenDialog(null);
944 if (value == JalviewFileChooser.APPROVE_OPTION)
946 String choice = chooser.getSelectedFile().getPath();
947 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
948 loadJalviewDataFile(choice);
957 * @param e DOCUMENT ME!
959 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
961 if(alignPanels!=null && alignPanels.size()<2)
968 if(alignPanels!=null)
972 for (int i = 0; i < alignPanels.size(); i++)
974 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
975 jalview.structure.StructureSelectionManager.getStructureSelectionManager()
976 .removeStructureViewerListener(ap.seqPanel, null);
977 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
978 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
979 PaintRefresher.RemoveComponent(ap);
980 ap.av.alignment = null;
985 int index = tabbedPane.getSelectedIndex();
987 alignPanels.removeElement(alignPanel);
988 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
989 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
990 PaintRefresher.RemoveComponent(alignPanel);
991 viewport.alignment = null;
995 tabbedPane.removeTabAt(index);
996 tabbedPane.validate();
998 if(index==tabbedPane.getTabCount())
1003 this.tabSelectionChanged(index);
1009 this.setClosed(true);
1012 catch (Exception ex)
1014 ex.printStackTrace();
1022 void updateEditMenuBar()
1025 if (viewport.historyList.size() > 0)
1027 undoMenuItem.setEnabled(true);
1028 CommandI command = (CommandI) viewport.historyList.peek();
1029 undoMenuItem.setText("Undo " + command.getDescription());
1033 undoMenuItem.setEnabled(false);
1034 undoMenuItem.setText("Undo");
1037 if (viewport.redoList.size() > 0)
1039 redoMenuItem.setEnabled(true);
1041 CommandI command = (CommandI) viewport.redoList.peek();
1042 redoMenuItem.setText("Redo " + command.getDescription());
1046 redoMenuItem.setEnabled(false);
1047 redoMenuItem.setText("Redo");
1052 public void addHistoryItem(CommandI command)
1054 if(command.getSize()>0)
1056 viewport.historyList.push(command);
1057 viewport.redoList.clear();
1058 updateEditMenuBar();
1059 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1065 * @return alignment objects for all views
1067 AlignmentI[] getViewAlignments()
1069 if (alignPanels!=null)
1071 Enumeration e = alignPanels.elements();
1072 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1073 for (int i=0; e.hasMoreElements(); i++)
1075 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1081 return new AlignmentI[] { viewport.alignment };
1088 * @param e DOCUMENT ME!
1090 protected void undoMenuItem_actionPerformed(ActionEvent e)
1092 if (viewport.historyList.empty())
1094 CommandI command = (CommandI)viewport.historyList.pop();
1095 viewport.redoList.push(command);
1096 command.undoCommand(getViewAlignments());
1098 AlignViewport originalSource = getOriginatingSource(command);
1099 updateEditMenuBar();
1101 if(originalSource!=null)
1103 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1104 originalSource.firePropertyChange("alignment",
1106 originalSource.alignment.getSequences());
1113 * @param e DOCUMENT ME!
1115 protected void redoMenuItem_actionPerformed(ActionEvent e)
1117 if(viewport.redoList.size()<1)
1122 CommandI command = (CommandI) viewport.redoList.pop();
1123 viewport.historyList.push(command);
1124 command.doCommand(getViewAlignments());
1126 AlignViewport originalSource = getOriginatingSource(command);
1127 updateEditMenuBar();
1129 if(originalSource!=null)
1131 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1132 originalSource.firePropertyChange("alignment",
1134 originalSource.alignment.getSequences());
1138 AlignViewport getOriginatingSource(CommandI command)
1140 AlignViewport originalSource = null;
1141 //For sequence removal and addition, we need to fire
1142 //the property change event FROM the viewport where the
1143 //original alignment was altered
1145 if (command instanceof EditCommand)
1147 EditCommand editCommand = (EditCommand) command;
1148 al = editCommand.getAlignment();
1149 Vector comps = (Vector) PaintRefresher.components
1150 .get(viewport.getSequenceSetId());
1152 for (int i = 0; i < comps.size(); i++)
1154 if (comps.elementAt(i) instanceof AlignmentPanel)
1156 if (al == ( (AlignmentPanel) comps.elementAt(i)).av.alignment)
1158 originalSource = ( (AlignmentPanel) comps.elementAt(i)).av;
1165 if (originalSource == null)
1167 //The original view is closed, we must validate
1168 //the current view against the closed view first
1171 PaintRefresher.validateSequences(al, viewport.alignment);
1174 originalSource = viewport;
1177 return originalSource;
1183 * @param up DOCUMENT ME!
1185 public void moveSelectedSequences(boolean up)
1187 SequenceGroup sg = viewport.getSelectionGroup();
1196 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1198 SequenceI seq = viewport.alignment.getSequenceAt(i);
1200 if (!sg.getSequences(null).contains(seq))
1205 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1207 if (sg.getSequences(null).contains(temp))
1212 viewport.alignment.getSequences().setElementAt(temp, i);
1213 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1218 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1220 SequenceI seq = viewport.alignment.getSequenceAt(i);
1222 if (!sg.getSequences(null).contains(seq))
1227 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1229 if (sg.getSequences(null).contains(temp))
1234 viewport.alignment.getSequences().setElementAt(temp, i);
1235 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1239 alignPanel.paintAlignment(true);
1245 synchronized void slideSequences(boolean right, int size)
1247 Vector sg = new Vector();
1248 if(viewport.cursorMode)
1250 sg.addElement(viewport.alignment.getSequenceAt(
1251 alignPanel.seqPanel.seqCanvas.cursorY));
1253 else if(viewport.getSelectionGroup()!=null
1254 && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
1256 sg = viewport.getSelectionGroup().getSequences(
1257 viewport.hiddenRepSequences);
1265 Vector invertGroup = new Vector();
1267 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1269 if(!sg.contains(viewport.alignment.getSequenceAt(i)))
1270 invertGroup.add(viewport.alignment.getSequenceAt(i));
1273 SequenceI[] seqs1 = new SequenceI[sg.size()];
1274 for (int i = 0; i < sg.size(); i++)
1275 seqs1[i] = (SequenceI) sg.elementAt(i);
1277 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1278 for (int i = 0; i < invertGroup.size(); i++)
1279 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1281 SlideSequencesCommand ssc;
1283 ssc = new SlideSequencesCommand("Slide Sequences",
1285 viewport.getGapCharacter()
1288 ssc = new SlideSequencesCommand("Slide Sequences",
1290 viewport.getGapCharacter()
1293 int groupAdjustment = 0;
1294 if (ssc.getGapsInsertedBegin() && right)
1296 if (viewport.cursorMode)
1297 alignPanel.seqPanel.moveCursor(size, 0);
1299 groupAdjustment = size;
1301 else if (!ssc.getGapsInsertedBegin() && !right)
1303 if (viewport.cursorMode)
1304 alignPanel.seqPanel.moveCursor( -size, 0);
1306 groupAdjustment = -size;
1309 if (groupAdjustment != 0)
1311 viewport.getSelectionGroup().setStartRes(
1312 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1313 viewport.getSelectionGroup().setEndRes(
1314 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1318 boolean appendHistoryItem = false;
1319 if(viewport.historyList!=null
1320 && viewport.historyList.size()>0
1321 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1323 appendHistoryItem = ssc.appendSlideCommand(
1324 (SlideSequencesCommand)viewport.historyList.peek())
1328 if(!appendHistoryItem)
1329 addHistoryItem(ssc);
1338 * @param e DOCUMENT ME!
1340 protected void copy_actionPerformed(ActionEvent e)
1343 if (viewport.getSelectionGroup() == null)
1347 // TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
1348 SequenceI [] seqs = viewport.getSelectionAsNewSequence();
1349 String[] omitHidden = null;
1351 if (viewport.hasHiddenColumns)
1353 omitHidden = viewport.getViewAsString(true);
1356 String output = new FormatAdapter().formatSequences(
1361 StringSelection ss = new StringSelection(output);
1365 jalview.gui.Desktop.internalCopy = true;
1366 //Its really worth setting the clipboard contents
1367 //to empty before setting the large StringSelection!!
1368 Toolkit.getDefaultToolkit().getSystemClipboard()
1369 .setContents(new StringSelection(""), null);
1371 Toolkit.getDefaultToolkit().getSystemClipboard()
1372 .setContents(ss, Desktop.instance);
1374 catch (OutOfMemoryError er)
1376 er.printStackTrace();
1377 javax.swing.SwingUtilities.invokeLater(new Runnable()
1381 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1382 "Out of memory copying region!!"
1384 "\nSee help files for increasing Java Virtual Machine memory."
1386 javax.swing.JOptionPane.WARNING_MESSAGE);
1393 Vector hiddenColumns = null;
1394 if(viewport.hasHiddenColumns)
1396 hiddenColumns =new Vector();
1397 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1398 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
1401 int[] region = (int[])
1402 viewport.getColumnSelection().getHiddenColumns().elementAt(i);
1404 hiddenColumns.addElement(new int[]
1405 {region[0] - hiddenOffset,
1406 region[1]-hiddenOffset});
1410 Desktop.jalviewClipboard = new Object[]
1413 viewport.alignment.getDataset(),
1415 statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
1421 * @param e DOCUMENT ME!
1423 protected void pasteNew_actionPerformed(ActionEvent e)
1431 * @param e DOCUMENT ME!
1433 protected void pasteThis_actionPerformed(ActionEvent e)
1441 * @param newAlignment DOCUMENT ME!
1443 void paste(boolean newAlignment)
1445 boolean externalPaste=true;
1448 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1449 Transferable contents = c.getContents(this);
1451 if (contents == null)
1459 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1460 if (str.length() < 1)
1465 format = new IdentifyFile().Identify(str, "Paste");
1468 catch (OutOfMemoryError er)
1470 er.printStackTrace();
1471 javax.swing.SwingUtilities.invokeLater(new Runnable()
1475 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1476 "Out of memory pasting sequences!!"
1478 "\nSee help files for increasing Java Virtual Machine memory."
1480 javax.swing.JOptionPane.WARNING_MESSAGE);
1487 SequenceI[] sequences;
1488 boolean annotationAdded = false;
1489 AlignmentI alignment = null;
1491 if(Desktop.jalviewClipboard!=null)
1493 // The clipboard was filled from within Jalview, we must use the sequences
1494 // And dataset from the copied alignment
1495 SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
1496 // be doubly sure that we create *new* sequence objects.
1497 sequences = new SequenceI[newseq.length];
1498 for (int i=0;i<newseq.length;i++) {
1499 sequences[i] = new Sequence(newseq[i]);
1501 alignment = new Alignment(sequences);
1502 externalPaste = false;
1506 // parse the clipboard as an alignment.
1507 alignment = new FormatAdapter().readFile(str, "Paste", format);
1508 sequences = alignment.getSequencesArray();
1516 if (Desktop.jalviewClipboard != null)
1518 // dataset is inherited
1519 alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
1523 // new dataset is constructed
1524 alignment.setDataset(null);
1526 alwidth = alignment.getWidth()+1;
1530 AlignmentI pastedal = alignment; // preserve pasted alignment object
1531 // Add pasted sequences and dataset into existing alignment.
1532 alignment = viewport.getAlignment();
1533 alwidth = alignment.getWidth()+1;
1534 // decide if we need to import sequences from an existing dataset
1535 boolean importDs = Desktop.jalviewClipboard != null
1536 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1537 // importDs==true instructs us to copy over new dataset sequences from
1538 // an existing alignment
1539 Vector newDs = (importDs) ? new Vector() : null; // used to create
1540 // minimum dataset set
1542 for (int i = 0; i < sequences.length; i++)
1546 newDs.addElement(null);
1548 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1550 if (importDs && ds != null)
1552 if (!newDs.contains(ds))
1554 newDs.setElementAt(ds, i);
1555 ds = new Sequence(ds);
1556 // update with new dataset sequence
1557 sequences[i].setDatasetSequence(ds);
1561 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1566 // copy and derive new dataset sequence
1567 sequences[i] = sequences[i].deriveSequence();
1568 alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
1569 // TODO: avoid creation of duplicate dataset sequences with a
1570 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1572 alignment.addSequence(sequences[i]); // merges dataset
1576 newDs.clear(); // tidy up
1578 if (pastedal.getAlignmentAnnotation()!=null) {
1579 // Add any annotation attached to alignment.
1580 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1581 for (int i=0; i<alann.length; i++)
1583 annotationAdded=true;
1584 if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
1585 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1586 newann.padAnnotation(alwidth);
1587 alignment.addAnnotation(newann);
1592 if (!newAlignment) {
1596 addHistoryItem(new EditCommand(
1601 alignment.getWidth(),
1605 // Add any annotations attached to sequences
1606 for (int i = 0; i < sequences.length; i++)
1608 if (sequences[i].getAnnotation() != null)
1610 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1612 annotationAdded=true;
1613 sequences[i].getAnnotation()[a].adjustForAlignment();
1614 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1615 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
1616 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1620 if (!newAlignment) {
1622 // propagate alignment changed.
1623 viewport.setEndSeq(alignment.getHeight());
1624 if (annotationAdded)
1626 // Duplicate sequence annotation in all views.
1627 AlignmentI[] alview = this.getViewAlignments();
1628 for (int i = 0; i < sequences.length; i++)
1630 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1633 for (int avnum=0;avnum<alview.length; avnum++)
1635 if (alview[avnum]!=alignment)
1637 // duplicate in a view other than the one with input focus
1638 int avwidth = alview[avnum].getWidth()+1;
1639 // this relies on sann being preserved after we
1640 // modify the sequence's annotation array for each duplication
1641 for (int a=0; a<sann.length; a++)
1643 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
1644 sequences[i].addAlignmentAnnotation(newann);
1645 newann.padAnnotation(avwidth);
1646 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
1647 alview[avnum].setAnnotationIndex(newann, a);
1652 buildSortByAnnotationScoresMenu();
1654 viewport.firePropertyChange("alignment", null, alignment.getSequences());
1657 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
1658 String newtitle = new String("Copied sequences");
1660 if(Desktop.jalviewClipboard!=null && Desktop.jalviewClipboard[2]!=null)
1662 Vector hc = (Vector)Desktop.jalviewClipboard[2];
1663 for(int i=0; i<hc.size(); i++)
1665 int [] region = (int[]) hc.elementAt(i);
1666 af.viewport.hideColumns(region[0], region[1]);
1671 //>>>This is a fix for the moment, until a better solution is found!!<<<
1672 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
1673 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1675 // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
1676 if (!externalPaste) {
1677 if (title.startsWith("Copied sequences"))
1683 newtitle = newtitle.concat("- from " + title);
1686 newtitle = new String("Pasted sequences");
1689 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1696 catch (Exception ex)
1698 ex.printStackTrace();
1699 System.out.println("Exception whilst pasting: "+ex);
1700 // could be anything being pasted in here
1709 * @param e DOCUMENT ME!
1711 protected void cut_actionPerformed(ActionEvent e)
1713 copy_actionPerformed(null);
1714 delete_actionPerformed(null);
1720 * @param e DOCUMENT ME!
1722 protected void delete_actionPerformed(ActionEvent evt)
1725 SequenceGroup sg = viewport.getSelectionGroup();
1731 Vector seqs = new Vector();
1733 for (int i = 0; i < sg.getSize(); i++)
1735 seq = sg.getSequenceAt(i);
1736 seqs.addElement(seq);
1740 // If the cut affects all sequences, remove highlighted columns
1741 if (sg.getSize() == viewport.alignment.getHeight())
1743 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1744 sg.getEndRes() + 1);
1748 SequenceI [] cut = new SequenceI[seqs.size()];
1749 for(int i=0; i<seqs.size(); i++)
1751 cut[i] = (SequenceI)seqs.elementAt(i);
1758 addHistoryItem(new EditCommand("Cut Sequences",
1762 sg.getEndRes()-sg.getStartRes()+1,
1763 viewport.alignment));
1766 viewport.setSelectionGroup(null);
1767 viewport.alignment.deleteGroup(sg);
1769 viewport.firePropertyChange("alignment", null,
1770 viewport.getAlignment().getSequences());
1772 if (viewport.getAlignment().getHeight() < 1)
1776 this.setClosed(true);
1778 catch (Exception ex)
1787 * @param e DOCUMENT ME!
1789 protected void deleteGroups_actionPerformed(ActionEvent e)
1791 viewport.alignment.deleteAllGroups();
1792 viewport.sequenceColours = null;
1793 viewport.setSelectionGroup(null);
1794 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1795 alignPanel.paintAlignment(true);
1801 * @param e DOCUMENT ME!
1803 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1805 SequenceGroup sg = new SequenceGroup();
1807 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1810 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1813 sg.setEndRes(viewport.alignment.getWidth() - 1);
1814 viewport.setSelectionGroup(sg);
1815 alignPanel.paintAlignment(true);
1816 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1822 * @param e DOCUMENT ME!
1824 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1826 if(viewport.cursorMode)
1828 alignPanel.seqPanel.keyboardNo1 = null;
1829 alignPanel.seqPanel.keyboardNo2 = null;
1831 viewport.setSelectionGroup(null);
1832 viewport.getColumnSelection().clear();
1833 viewport.setSelectionGroup(null);
1834 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1835 alignPanel.idPanel.idCanvas.searchResults = null;
1836 alignPanel.paintAlignment(true);
1837 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1843 * @param e DOCUMENT ME!
1845 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1847 SequenceGroup sg = viewport.getSelectionGroup();
1851 selectAllSequenceMenuItem_actionPerformed(null);
1856 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1859 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1862 alignPanel.paintAlignment(true);
1864 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1867 public void invertColSel_actionPerformed(ActionEvent e)
1869 viewport.invertColumnSelection();
1870 alignPanel.paintAlignment(true);
1877 * @param e DOCUMENT ME!
1879 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1881 trimAlignment(true);
1887 * @param e DOCUMENT ME!
1889 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1891 trimAlignment(false);
1894 void trimAlignment(boolean trimLeft)
1896 ColumnSelection colSel = viewport.getColumnSelection();
1899 if (colSel.size() > 0)
1903 column = colSel.getMin();
1907 column = colSel.getMax();
1911 if(viewport.getSelectionGroup()!=null)
1913 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1914 hiddenRepSequences);
1918 seqs = viewport.alignment.getSequencesArray();
1922 TrimRegionCommand trimRegion;
1925 trimRegion = new TrimRegionCommand("Remove Left",
1926 TrimRegionCommand.TRIM_LEFT,
1931 viewport.selectionGroup);
1932 viewport.setStartRes(0);
1936 trimRegion = new TrimRegionCommand("Remove Right",
1937 TrimRegionCommand.TRIM_RIGHT,
1942 viewport.selectionGroup);
1945 statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
1948 addHistoryItem(trimRegion);
1950 Vector groups = viewport.alignment.getGroups();
1952 for (int i = 0; i < groups.size(); i++)
1954 SequenceGroup sg = (SequenceGroup) groups.get(i);
1956 if ( (trimLeft && !sg.adjustForRemoveLeft(column))
1957 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1959 viewport.alignment.deleteGroup(sg);
1963 viewport.firePropertyChange("alignment", null,
1964 viewport.getAlignment().getSequences());
1971 * @param e DOCUMENT ME!
1973 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1975 int start = 0, end = viewport.alignment.getWidth()-1;
1978 if (viewport.getSelectionGroup() != null)
1980 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1981 hiddenRepSequences);
1982 start = viewport.getSelectionGroup().getStartRes();
1983 end = viewport.getSelectionGroup().getEndRes();
1987 seqs = viewport.alignment.getSequencesArray();
1991 RemoveGapColCommand removeGapCols =
1992 new RemoveGapColCommand("Remove Gapped Columns",
1995 viewport.alignment);
1997 addHistoryItem(removeGapCols);
1999 statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
2001 //This is to maintain viewport position on first residue
2003 SequenceI seq = viewport.alignment.getSequenceAt(0);
2004 int startRes = seq.findPosition(viewport.startRes);
2005 // ShiftList shifts;
2006 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2007 // edit.alColumnChanges=shifts.getInverse();
2008 // if (viewport.hasHiddenColumns)
2009 // viewport.getColumnSelection().compensateForEdits(shifts);
2010 viewport.setStartRes(seq.findIndex(startRes)-1);
2011 viewport.firePropertyChange("alignment", null,
2012 viewport.getAlignment().getSequences());
2019 * @param e DOCUMENT ME!
2021 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2023 int start = 0, end = viewport.alignment.getWidth()-1;
2026 if (viewport.getSelectionGroup() != null)
2028 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
2029 hiddenRepSequences);
2030 start = viewport.getSelectionGroup().getStartRes();
2031 end = viewport.getSelectionGroup().getEndRes();
2035 seqs = viewport.alignment.getSequencesArray();
2038 //This is to maintain viewport position on first residue
2040 SequenceI seq = viewport.alignment.getSequenceAt(0);
2041 int startRes = seq.findPosition(viewport.startRes);
2043 addHistoryItem(new RemoveGapsCommand("Remove Gaps",
2046 viewport.alignment));
2048 viewport.setStartRes(seq.findIndex(startRes)-1);
2050 viewport.firePropertyChange("alignment", null,
2051 viewport.getAlignment().getSequences());
2058 * @param e DOCUMENT ME!
2060 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2062 viewport.padGaps = padGapsMenuitem.isSelected();
2064 viewport.firePropertyChange("alignment",
2066 viewport.getAlignment().getSequences());
2072 * @param e DOCUMENT ME!
2074 public void findMenuItem_actionPerformed(ActionEvent e)
2079 public void newView_actionPerformed(ActionEvent e)
2081 AlignmentPanel newap =
2082 new Jalview2XML().copyAlignPanel(alignPanel, true);
2084 newap.av.gatherViewsHere = false;
2086 if (viewport.viewName == null)
2088 viewport.viewName = "Original";
2091 newap.av.historyList = viewport.historyList;
2092 newap.av.redoList = viewport.redoList;
2094 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2095 String newViewName = "View " +index;
2097 Vector comps = (Vector) PaintRefresher.components.get(viewport.
2098 getSequenceSetId());
2099 Vector existingNames = new Vector();
2100 for(int i=0; i<comps.size(); i++)
2102 if(comps.elementAt(i) instanceof AlignmentPanel)
2104 AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
2105 if(!existingNames.contains(ap.av.viewName))
2107 existingNames.addElement(ap.av.viewName);
2112 while(existingNames.contains(newViewName))
2114 newViewName = "View "+ (++index);
2117 newap.av.viewName = newViewName;
2119 addAlignmentPanel(newap, false);
2121 if(alignPanels.size()==2)
2123 viewport.gatherViewsHere = true;
2125 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2128 public void expandViews_actionPerformed(ActionEvent e)
2130 Desktop.instance.explodeViews(this);
2133 public void gatherViews_actionPerformed(ActionEvent e)
2135 Desktop.instance.gatherViews(this);
2143 * @param e DOCUMENT ME!
2145 public void font_actionPerformed(ActionEvent e)
2147 new FontChooser(alignPanel);
2154 * @param e DOCUMENT ME!
2156 protected void seqLimit_actionPerformed(ActionEvent e)
2158 viewport.setShowJVSuffix(seqLimits.isSelected());
2160 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
2161 alignPanel.paintAlignment(true);
2164 public void idRightAlign_actionPerformed(ActionEvent e)
2166 viewport.rightAlignIds = idRightAlign.isSelected();
2167 alignPanel.paintAlignment(true);
2175 * @param e DOCUMENT ME!
2177 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2179 viewport.setColourText(colourTextMenuItem.isSelected());
2180 alignPanel.paintAlignment(true);
2186 * @param e DOCUMENT ME!
2188 public void wrapMenuItem_actionPerformed(ActionEvent e)
2190 scaleAbove.setVisible(wrapMenuItem.isSelected());
2191 scaleLeft.setVisible(wrapMenuItem.isSelected());
2192 scaleRight.setVisible(wrapMenuItem.isSelected());
2193 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2194 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2197 public void showAllSeqs_actionPerformed(ActionEvent e)
2199 viewport.showAllHiddenSeqs();
2202 public void showAllColumns_actionPerformed(ActionEvent e)
2204 viewport.showAllHiddenColumns();
2208 public void hideSelSequences_actionPerformed(ActionEvent e)
2210 viewport.hideAllSelectedSeqs();
2211 alignPanel.paintAlignment(true);
2214 public void hideSelColumns_actionPerformed(ActionEvent e)
2216 viewport.hideSelectedColumns();
2217 alignPanel.paintAlignment(true);
2220 public void hiddenMarkers_actionPerformed(ActionEvent e)
2222 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2229 * @param e DOCUMENT ME!
2231 protected void scaleAbove_actionPerformed(ActionEvent e)
2233 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2234 alignPanel.paintAlignment(true);
2240 * @param e DOCUMENT ME!
2242 protected void scaleLeft_actionPerformed(ActionEvent e)
2244 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2245 alignPanel.paintAlignment(true);
2251 * @param e DOCUMENT ME!
2253 protected void scaleRight_actionPerformed(ActionEvent e)
2255 viewport.setScaleRightWrapped(scaleRight.isSelected());
2256 alignPanel.paintAlignment(true);
2262 * @param e DOCUMENT ME!
2264 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2266 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2267 alignPanel.paintAlignment(true);
2273 * @param e DOCUMENT ME!
2275 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2277 viewport.setShowText(viewTextMenuItem.isSelected());
2278 alignPanel.paintAlignment(true);
2284 * @param e DOCUMENT ME!
2286 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2288 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2289 alignPanel.paintAlignment(true);
2293 public FeatureSettings featureSettings;
2294 public void featureSettings_actionPerformed(ActionEvent e)
2296 if(featureSettings !=null )
2298 featureSettings.close();
2299 featureSettings = null;
2301 featureSettings = new FeatureSettings(this);
2307 * @param evt DOCUMENT ME!
2309 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2311 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2312 alignPanel.paintAlignment(true);
2313 if (alignPanel.getOverviewPanel() != null)
2315 alignPanel.getOverviewPanel().updateOverviewImage();
2322 * @param e DOCUMENT ME!
2324 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2326 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2327 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2330 public void alignmentProperties()
2332 JEditorPane editPane = new JEditorPane("text/html","");
2333 editPane.setEditable(false);
2334 StringBuffer contents = new StringBuffer("<html>");
2337 int min=Integer.MAX_VALUE, max=0;
2338 for(int i=0; i<viewport.alignment.getHeight(); i++)
2340 int size = viewport.alignment.getSequenceAt(i).getEnd()
2341 -viewport.alignment.getSequenceAt(i).getStart();
2348 avg = avg/(float)viewport.alignment.getHeight();
2350 contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
2351 contents.append("<br>Minimum Sequence Length: "+min);
2352 contents.append("<br>Maximum Sequence Length: "+max);
2353 contents.append("<br>Average Length: "+(int)avg);
2355 if (((Alignment)viewport.alignment).getProperties() != null)
2357 Hashtable props = ((Alignment)viewport.alignment).getProperties();
2358 Enumeration en = props.keys();
2359 contents.append("<br><br><table border=\"1\">");
2360 while(en.hasMoreElements())
2362 String key = en.nextElement().toString();
2363 StringBuffer val = new StringBuffer();
2364 String vals = props.get(key).toString();
2367 npos = vals.indexOf("\n",pos);
2370 val.append(vals.substring(pos));
2372 val.append(vals.substring(pos, npos));
2377 contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
2379 contents.append("</table>");
2381 editPane.setText(contents.toString()+"</html>");
2382 JInternalFrame frame = new JInternalFrame();
2383 frame.getContentPane().add(new JScrollPane(editPane));
2385 Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
2392 * @param e DOCUMENT ME!
2394 public void overviewMenuItem_actionPerformed(ActionEvent e)
2396 if (alignPanel.overviewPanel != null)
2401 JInternalFrame frame = new JInternalFrame();
2402 OverviewPanel overview = new OverviewPanel(alignPanel);
2403 frame.setContentPane(overview);
2404 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(),
2405 frame.getWidth(), frame.getHeight());
2407 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2408 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2410 public void internalFrameClosed(
2411 javax.swing.event.InternalFrameEvent evt)
2413 alignPanel.setOverviewPanel(null);
2418 alignPanel.setOverviewPanel(overview);
2421 public void textColour_actionPerformed(ActionEvent e)
2423 new TextColourChooser().chooseColour(alignPanel, null);
2429 * @param e DOCUMENT ME!
2431 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2439 * @param e DOCUMENT ME!
2441 public void clustalColour_actionPerformed(ActionEvent e)
2443 changeColour(new ClustalxColourScheme(
2444 viewport.alignment.getSequences(), viewport.alignment.getWidth()));
2450 * @param e DOCUMENT ME!
2452 public void zappoColour_actionPerformed(ActionEvent e)
2454 changeColour(new ZappoColourScheme());
2460 * @param e DOCUMENT ME!
2462 public void taylorColour_actionPerformed(ActionEvent e)
2464 changeColour(new TaylorColourScheme());
2470 * @param e DOCUMENT ME!
2472 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2474 changeColour(new HydrophobicColourScheme());
2480 * @param e DOCUMENT ME!
2482 public void helixColour_actionPerformed(ActionEvent e)
2484 changeColour(new HelixColourScheme());
2490 * @param e DOCUMENT ME!
2492 public void strandColour_actionPerformed(ActionEvent e)
2494 changeColour(new StrandColourScheme());
2500 * @param e DOCUMENT ME!
2502 public void turnColour_actionPerformed(ActionEvent e)
2504 changeColour(new TurnColourScheme());
2510 * @param e DOCUMENT ME!
2512 public void buriedColour_actionPerformed(ActionEvent e)
2514 changeColour(new BuriedColourScheme());
2520 * @param e DOCUMENT ME!
2522 public void nucleotideColour_actionPerformed(ActionEvent e)
2524 changeColour(new NucleotideColourScheme());
2527 public void annotationColour_actionPerformed(ActionEvent e)
2529 new AnnotationColourChooser(viewport, alignPanel);
2536 * @param e DOCUMENT ME!
2538 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2540 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2546 * @param cs DOCUMENT ME!
2548 public void changeColour(ColourSchemeI cs)
2554 if (viewport.getAbovePIDThreshold())
2556 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2559 cs.setThreshold(threshold,
2560 viewport.getIgnoreGapsConsensus());
2562 viewport.setGlobalColourScheme(cs);
2566 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2569 if (viewport.getConservationSelected())
2572 Alignment al = (Alignment) viewport.alignment;
2573 Conservation c = new Conservation("All",
2574 ResidueProperties.propHash, 3,
2575 al.getSequences(), 0,
2579 c.verdict(false, viewport.ConsPercGaps);
2581 cs.setConservation(c);
2583 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel, cs,
2588 cs.setConservation(null);
2591 cs.setConsensus(viewport.hconsensus);
2594 viewport.setGlobalColourScheme(cs);
2596 if (viewport.getColourAppliesToAllGroups())
2598 Vector groups = viewport.alignment.getGroups();
2600 for (int i = 0; i < groups.size(); i++)
2602 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2610 if (cs instanceof ClustalxColourScheme)
2612 sg.cs = new ClustalxColourScheme(
2613 sg.getSequences(viewport.hiddenRepSequences), sg.getWidth());
2615 else if (cs instanceof UserColourScheme)
2617 sg.cs = new UserColourScheme( ( (UserColourScheme) cs).getColours());
2623 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2625 catch (Exception ex)
2630 if (viewport.getAbovePIDThreshold()
2631 || cs instanceof PIDColourScheme
2632 || cs instanceof Blosum62ColourScheme)
2634 sg.cs.setThreshold(threshold,
2635 viewport.getIgnoreGapsConsensus());
2637 sg.cs.setConsensus(AAFrequency.calculate(
2638 sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
2643 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2647 if (viewport.getConservationSelected())
2649 Conservation c = new Conservation("Group",
2650 ResidueProperties.propHash, 3,
2651 sg.getSequences(viewport.
2652 hiddenRepSequences),
2656 c.verdict(false, viewport.ConsPercGaps);
2657 sg.cs.setConservation(c);
2661 sg.cs.setConservation(null);
2666 if (alignPanel.getOverviewPanel() != null)
2668 alignPanel.getOverviewPanel().updateOverviewImage();
2674 alignPanel.paintAlignment(true);
2680 * @param e DOCUMENT ME!
2682 protected void modifyPID_actionPerformed(ActionEvent e)
2684 if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme!=null)
2686 SliderPanel.setPIDSliderSource(alignPanel,
2687 viewport.getGlobalColourScheme(),
2689 SliderPanel.showPIDSlider();
2696 * @param e DOCUMENT ME!
2698 protected void modifyConservation_actionPerformed(ActionEvent e)
2700 if (viewport.getConservationSelected() && viewport.globalColourScheme!=null)
2702 SliderPanel.setConservationSlider(alignPanel,
2703 viewport.globalColourScheme,
2705 SliderPanel.showConservationSlider();
2712 * @param e DOCUMENT ME!
2714 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2716 viewport.setConservationSelected(conservationMenuItem.isSelected());
2718 viewport.setAbovePIDThreshold(false);
2719 abovePIDThreshold.setSelected(false);
2721 changeColour(viewport.getGlobalColourScheme());
2723 modifyConservation_actionPerformed(null);
2729 * @param e DOCUMENT ME!
2731 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2733 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2735 conservationMenuItem.setSelected(false);
2736 viewport.setConservationSelected(false);
2738 changeColour(viewport.getGlobalColourScheme());
2740 modifyPID_actionPerformed(null);
2746 * @param e DOCUMENT ME!
2748 public void userDefinedColour_actionPerformed(ActionEvent e)
2750 if (e.getActionCommand().equals("User Defined..."))
2752 new UserDefinedColours(alignPanel, null);
2756 UserColourScheme udc = (UserColourScheme) UserDefinedColours.
2757 getUserColourSchemes().get(e.getActionCommand());
2763 public void updateUserColourMenu()
2766 Component[] menuItems = colourMenu.getMenuComponents();
2767 int i, iSize = menuItems.length;
2768 for (i = 0; i < iSize; i++)
2770 if (menuItems[i].getName() != null &&
2771 menuItems[i].getName().equals("USER_DEFINED"))
2773 colourMenu.remove(menuItems[i]);
2777 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2779 java.util.Enumeration userColours = jalview.gui.UserDefinedColours.
2780 getUserColourSchemes().keys();
2782 while (userColours.hasMoreElements())
2784 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2786 nextElement().toString());
2787 radioItem.setName("USER_DEFINED");
2788 radioItem.addMouseListener(new MouseAdapter()
2790 public void mousePressed(MouseEvent evt)
2792 if(evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
2794 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
2796 int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
2798 "Remove from default list?",
2799 "Remove user defined colour",
2800 JOptionPane.YES_NO_OPTION);
2801 if(option == JOptionPane.YES_OPTION)
2803 jalview.gui.UserDefinedColours.removeColourFromDefaults(
2804 radioItem.getText());
2805 colourMenu.remove(radioItem);
2809 radioItem.addActionListener(new ActionListener()
2811 public void actionPerformed(ActionEvent evt)
2813 userDefinedColour_actionPerformed(evt);
2820 radioItem.addActionListener(new ActionListener()
2822 public void actionPerformed(ActionEvent evt)
2824 userDefinedColour_actionPerformed(evt);
2828 colourMenu.insert(radioItem, 15);
2829 colours.add(radioItem);
2837 * @param e DOCUMENT ME!
2839 public void PIDColour_actionPerformed(ActionEvent e)
2841 changeColour(new PIDColourScheme());
2847 * @param e DOCUMENT ME!
2849 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2851 changeColour(new Blosum62ColourScheme());
2857 * @param e DOCUMENT ME!
2859 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2861 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2862 AlignmentSorter.sortByPID(viewport.getAlignment(),
2863 viewport.getAlignment().getSequenceAt(0));
2864 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2865 viewport.alignment));
2866 alignPanel.paintAlignment(true);
2872 * @param e DOCUMENT ME!
2874 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2876 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2877 AlignmentSorter.sortByID(viewport.getAlignment());
2878 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2879 alignPanel.paintAlignment(true);
2885 * @param e DOCUMENT ME!
2887 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2889 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2890 AlignmentSorter.sortByGroup(viewport.getAlignment());
2891 addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
2893 alignPanel.paintAlignment(true);
2898 * @param e DOCUMENT ME!
2900 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2902 new RedundancyPanel(alignPanel, this);
2909 * @param e DOCUMENT ME!
2911 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2913 if ( (viewport.getSelectionGroup() == null) ||
2914 (viewport.getSelectionGroup().getSize() < 2))
2916 JOptionPane.showInternalMessageDialog(this,
2917 "You must select at least 2 sequences.",
2918 "Invalid Selection",
2919 JOptionPane.WARNING_MESSAGE);
2923 JInternalFrame frame = new JInternalFrame();
2924 frame.setContentPane(new PairwiseAlignPanel(viewport));
2925 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2932 * @param e DOCUMENT ME!
2934 public void PCAMenuItem_actionPerformed(ActionEvent e)
2936 if ( ( (viewport.getSelectionGroup() != null) &&
2937 (viewport.getSelectionGroup().getSize() < 4) &&
2938 (viewport.getSelectionGroup().getSize() > 0)) ||
2939 (viewport.getAlignment().getHeight() < 4))
2941 JOptionPane.showInternalMessageDialog(this,
2942 "Principal component analysis must take\n" +
2943 "at least 4 input sequences.",
2944 "Sequence selection insufficient",
2945 JOptionPane.WARNING_MESSAGE);
2950 new PCAPanel(alignPanel);
2954 public void autoCalculate_actionPerformed(ActionEvent e)
2956 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2957 if(viewport.autoCalculateConsensus)
2959 viewport.firePropertyChange("alignment",
2961 viewport.getAlignment().getSequences());
2969 * @param e DOCUMENT ME!
2971 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2973 NewTreePanel("AV", "PID", "Average distance tree using PID");
2979 * @param e DOCUMENT ME!
2981 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
2983 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
2989 * @param e DOCUMENT ME!
2991 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2993 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
2999 * @param e DOCUMENT ME!
3001 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3003 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3009 * @param type DOCUMENT ME!
3010 * @param pwType DOCUMENT ME!
3011 * @param title DOCUMENT ME!
3013 void NewTreePanel(String type, String pwType, String title)
3017 if (viewport.getSelectionGroup() != null)
3019 if (viewport.getSelectionGroup().getSize() < 3)
3021 JOptionPane.showMessageDialog(Desktop.desktop,
3022 "You need to have more than two sequences selected to build a tree!",
3023 "Not enough sequences",
3024 JOptionPane.WARNING_MESSAGE);
3029 SequenceGroup sg = viewport.getSelectionGroup();
3031 /* Decide if the selection is a column region */
3032 while (s < sg.getSize())
3034 if ( ( (SequenceI) sg.getSequences(null).elementAt(s++)).getLength() <
3037 JOptionPane.showMessageDialog(Desktop.desktop,
3038 "The selected region to create a tree may\nonly contain residues or gaps.\n" +
3039 "Try using the Pad function in the edit menu,\n" +
3040 "or one of the multiple sequence alignment web services.",
3041 "Sequences in selection are not aligned",
3042 JOptionPane.WARNING_MESSAGE);
3048 title = title + " on region";
3049 tp = new TreePanel(alignPanel, type, pwType);
3053 //are the sequences aligned?
3054 if (!viewport.alignment.isAligned())
3056 JOptionPane.showMessageDialog(Desktop.desktop,
3057 "The sequences must be aligned before creating a tree.\n" +
3058 "Try using the Pad function in the edit menu,\n" +
3059 "or one of the multiple sequence alignment web services.",
3060 "Sequences not aligned",
3061 JOptionPane.WARNING_MESSAGE);
3066 if(viewport.alignment.getHeight()<2)
3071 tp = new TreePanel(alignPanel, type, pwType);
3076 if(viewport.viewName!=null)
3078 title+= viewport.viewName+" of ";
3081 title += this.title;
3083 Desktop.addInternalFrame(tp, title, 600, 500);
3089 * @param title DOCUMENT ME!
3090 * @param order DOCUMENT ME!
3092 public void addSortByOrderMenuItem(String title, final AlignmentOrder order)
3094 final JMenuItem item = new JMenuItem("by " + title);
3096 item.addActionListener(new java.awt.event.ActionListener()
3098 public void actionPerformed(ActionEvent e)
3100 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3102 // TODO: JBPNote - have to map order entries to curent SequenceI pointers
3103 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3105 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3106 viewport.alignment));
3108 alignPanel.paintAlignment(true);
3113 * Add a new sort by annotation score menu item
3114 * @param sort the menu to add the option to
3115 * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
3117 public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
3119 final JMenuItem item = new JMenuItem(scoreLabel);
3121 item.addActionListener(new java.awt.event.ActionListener()
3123 public void actionPerformed(ActionEvent e)
3125 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3126 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());
3127 addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
3128 alignPanel.paintAlignment(true);
3133 * last hash for alignment's annotation array - used to minimise cost of rebuild.
3135 protected int _annotationScoreVectorHash;
3137 * search the alignment and rebuild the sort by annotation score submenu
3138 * the last alignment annotation vector hash is stored to minimize
3139 * cost of rebuilding in subsequence calls.
3142 public void buildSortByAnnotationScoresMenu()
3144 if(viewport.alignment.getAlignmentAnnotation()==null)
3149 if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
3151 sortByAnnotScore.removeAll();
3152 // almost certainly a quicker way to do this - but we keep it simple
3153 Hashtable scoreSorts=new Hashtable();
3154 AlignmentAnnotation aann[];
3155 Enumeration sq = viewport.alignment.getSequences().elements();
3156 while (sq.hasMoreElements())
3158 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3159 for (int i=0;aann!=null && i<aann.length; i++)
3161 if (aann[i].hasScore() && aann[i].sequenceRef!=null)
3163 scoreSorts.put(aann[i].label, aann[i].label);
3167 Enumeration labels = scoreSorts.keys();
3168 while (labels.hasMoreElements())
3170 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
3172 sortByAnnotScore.setVisible(scoreSorts.size()>0);
3175 _annotationScoreVectorHash =
3176 viewport.alignment.getAlignmentAnnotation().hashCode();
3181 * Maintain the Order by->Displayed Tree menu.
3182 * Creates a new menu item for a TreePanel with an appropriate
3183 * <code>jalview.analysis.AlignmentSorter</code> call. Listeners are added
3184 * to remove the menu item when the treePanel is closed, and adjust
3185 * the tree leaf to sequence mapping when the alignment is modified.
3186 * @param treePanel Displayed tree window.
3187 * @param title SortBy menu item title.
3189 public void buildTreeMenu()
3191 sortByTreeMenu.removeAll();
3193 Vector comps = (Vector) PaintRefresher.components.get(viewport.
3194 getSequenceSetId());
3195 Vector treePanels = new Vector();
3196 int i, iSize = comps.size();
3197 for(i=0; i<iSize; i++)
3199 if(comps.elementAt(i) instanceof TreePanel)
3201 treePanels.add(comps.elementAt(i));
3205 iSize = treePanels.size();
3209 sortByTreeMenu.setVisible(false);
3213 sortByTreeMenu.setVisible(true);
3215 for(i=0; i<treePanels.size(); i++)
3217 TreePanel tp = (TreePanel)treePanels.elementAt(i);
3218 final JMenuItem item = new JMenuItem(tp.getTitle());
3219 final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
3220 item.addActionListener(new java.awt.event.ActionListener()
3222 public void actionPerformed(ActionEvent e)
3224 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3225 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3227 addHistoryItem(new OrderCommand("Tree Sort",
3229 viewport.alignment));
3231 alignPanel.paintAlignment(true);
3235 sortByTreeMenu.add(item);
3240 * Work out whether the whole set of sequences
3241 * or just the selected set will be submitted for multiple alignment.
3244 private jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3246 // Now, check we have enough sequences
3247 AlignmentView msa = null;
3249 if ( (viewport.getSelectionGroup() != null) &&
3250 (viewport.getSelectionGroup().getSize() > 1))
3252 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
3253 /*SequenceGroup seqs = viewport.getSelectionGroup();
3255 msa = new SequenceI[sz = seqs.getSize(false)];
3257 for (int i = 0; i < sz; i++)
3259 msa[i] = (SequenceI) seqs.getSequenceAt(i);
3261 msa = viewport.getAlignmentView(true);
3265 /*Vector seqs = viewport.getAlignment().getSequences();
3267 if (seqs.size() > 1)
3269 msa = new SequenceI[seqs.size()];
3271 for (int i = 0; i < seqs.size(); i++)
3273 msa[i] = (SequenceI) seqs.elementAt(i);
3276 msa = viewport.getAlignmentView(false);
3282 * Decides what is submitted to a secondary structure prediction service,
3283 * the currently selected sequence, or the currently selected alignment
3284 * (where the first sequence in the set is the one that the prediction
3287 AlignmentView gatherSeqOrMsaForSecStrPrediction()
3289 AlignmentView seqs = null;
3291 if ( (viewport.getSelectionGroup() != null) &&
3292 (viewport.getSelectionGroup().getSize() > 0))
3294 seqs = viewport.getAlignmentView(true);
3298 seqs = viewport.getAlignmentView(false);
3300 // limit sequences - JBPNote in future - could spawn multiple prediction jobs
3301 // TODO: viewport.alignment.isAligned is a global state - the local selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3302 if (!viewport.alignment.isAligned())
3304 seqs.setSequences(new SeqCigar[]
3305 {seqs.getSequences()[0]});
3312 * @param e DOCUMENT ME!
3314 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3316 // Pick the tree file
3317 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3320 chooser.setFileView(new JalviewFileView());
3321 chooser.setDialogTitle("Select a newick-like tree file");
3322 chooser.setToolTipText("Load a tree file");
3324 int value = chooser.showOpenDialog(null);
3326 if (value == JalviewFileChooser.APPROVE_OPTION)
3328 String choice = chooser.getSelectedFile().getPath();
3329 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3330 jalview.io.NewickFile fin = null;
3333 fin = new jalview.io.NewickFile(choice,
3335 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3337 catch (Exception ex)
3339 JOptionPane.showMessageDialog(Desktop.desktop,
3341 "Problem reading tree file",
3342 JOptionPane.WARNING_MESSAGE);
3343 ex.printStackTrace();
3345 if (fin!=null && fin.hasWarningMessage())
3347 JOptionPane.showMessageDialog(Desktop.desktop,
3348 fin.getWarningMessage(),
3349 "Possible problem with tree file",
3350 JOptionPane.WARNING_MESSAGE);
3356 public TreePanel ShowNewickTree(NewickFile nf, String title)
3358 return ShowNewickTree(nf,title,600,500,4,5);
3361 public TreePanel ShowNewickTree(NewickFile nf, String title,
3362 AlignmentView input)
3364 return ShowNewickTree(nf,title, input, 600,500,4,5);
3367 public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
3370 return ShowNewickTree(nf, title, null, w, h, x, y);
3373 * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
3375 * @param nf the tree
3376 * @param title tree viewer title
3377 * @param input Associated alignment input data (or null)
3382 * @return TreePanel handle
3384 public TreePanel ShowNewickTree(NewickFile nf, String title,
3385 AlignmentView input, int w, int h, int x,
3388 TreePanel tp = null;
3394 if (nf.getTree() != null)
3396 tp = new TreePanel(alignPanel,
3405 tp.setLocation(x,y);
3409 Desktop.addInternalFrame(tp, title, w, h);
3412 catch (Exception ex)
3414 ex.printStackTrace();
3422 * Generates menu items and listener event actions for web service clients
3425 public void BuildWebServiceMenu()
3427 if ( (Discoverer.services != null)
3428 && (Discoverer.services.size() > 0))
3430 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3431 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3432 Vector wsmenu = new Vector();
3433 final AlignFrame af = this;
3436 // Add any Multiple Sequence Alignment Services
3437 final JMenu msawsmenu = new JMenu("Alignment");
3438 for (int i = 0, j = msaws.size(); i < j; i++)
3440 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws.
3442 final JMenuItem method = new JMenuItem(sh.getName());
3443 method.addActionListener(new ActionListener()
3445 public void actionPerformed(ActionEvent e)
3447 AlignmentView msa = gatherSequencesForAlignment();
3448 new jalview.ws.MsaWSClient(sh, title, msa,
3450 viewport.getAlignment().getDataset(),
3456 msawsmenu.add(method);
3457 // Deal with services that we know accept partial alignments.
3458 if (sh.getName().indexOf("lustal") > -1)
3460 // We know that ClustalWS can accept partial alignments for refinement.
3461 final JMenuItem methodR = new JMenuItem(sh.getName()+" Realign");
3462 methodR.addActionListener(new ActionListener()
3464 public void actionPerformed(ActionEvent e)
3466 AlignmentView msa = gatherSequencesForAlignment();
3467 new jalview.ws.MsaWSClient(sh, title, msa,
3469 viewport.getAlignment().getDataset(),
3475 msawsmenu.add(methodR);
3479 wsmenu.add(msawsmenu);
3481 if (secstrpr != null)
3483 // Add any secondary structure prediction services
3484 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3485 for (int i = 0, j = secstrpr.size(); i < j; i++)
3487 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle)
3489 final JMenuItem method = new JMenuItem(sh.getName());
3490 method.addActionListener(new ActionListener()
3492 public void actionPerformed(ActionEvent e)
3494 AlignmentView msa = gatherSeqOrMsaForSecStrPrediction();
3495 if (msa.getSequences().length == 1)
3497 // Single Sequence prediction
3498 new jalview.ws.JPredClient(sh, title, false, msa, af, true);
3502 if (msa.getSequences().length > 1)
3504 // Sequence profile based prediction
3505 new jalview.ws.JPredClient(sh,
3506 title, true, msa, af, true);
3511 secstrmenu.add(method);
3513 wsmenu.add(secstrmenu);
3515 resetWebServiceMenu();
3516 for (int i = 0, j = wsmenu.size(); i < j; i++)
3518 webService.add( (JMenu) wsmenu.get(i));
3523 resetWebServiceMenu();
3524 this.webService.add(this.webServiceNoServices);
3526 // TODO: add in rediscovery function
3527 // TODO: reduce code redundancy.
3528 // TODO: group services by location as well as function.
3533 * empty the web service menu and add any ad-hoc functions
3534 * not dynamically discovered.
3537 private void resetWebServiceMenu()
3539 webService.removeAll();
3540 // Temporary hack - DBRef Fetcher always top level ws entry.
3541 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3542 rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
3543 webService.add(rfetch);
3544 rfetch.addActionListener(new ActionListener() {
3546 public void actionPerformed(ActionEvent e)
3548 new jalview.ws.DBRefFetcher(
3549 alignPanel.av.getSequenceSelection(),
3550 alignPanel.alignFrame).fetchDBRefs(false);
3556 /* public void vamsasStore_actionPerformed(ActionEvent e)
3558 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3559 getProperty("LAST_DIRECTORY"));
3561 chooser.setFileView(new JalviewFileView());
3562 chooser.setDialogTitle("Export to Vamsas file");
3563 chooser.setToolTipText("Export");
3565 int value = chooser.showSaveDialog(this);
3567 if (value == JalviewFileChooser.APPROVE_OPTION)
3569 jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3570 //vs.store(chooser.getSelectedFile().getAbsolutePath() );
3571 vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
3575 * prototype of an automatically enabled/disabled analysis function
3578 protected void setShowProductsEnabled()
3580 SequenceI [] selection = viewport.getSequenceSelection();
3581 if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
3583 showProducts.setEnabled(true);
3586 showProducts.setEnabled(false);
3590 * search selection for sequence xRef products and build the
3591 * show products menu.
3594 * @return true if showProducts menu should be enabled.
3596 public boolean canShowProducts(SequenceI[] selection, boolean isRegionSelection, Alignment dataset)
3598 boolean showp=false;
3600 showProducts.removeAll();
3601 final boolean dna = viewport.getAlignment().isNucleotide();
3602 final Alignment ds = dataset;
3603 String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection, dataset);
3604 //Object[] prods = CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(), selection, dataset, true);
3605 final SequenceI[] sel = selection;
3606 for (int t=0; ptypes!=null && t<ptypes.length; t++)
3609 final boolean isRegSel = isRegionSelection;
3610 final AlignFrame af = this;
3611 final String source = ptypes[t];
3612 JMenuItem xtype = new JMenuItem(ptypes[t]);
3613 xtype.addActionListener(new ActionListener() {
3615 public void actionPerformed(ActionEvent e)
3617 af.showProductsFor(sel, ds, isRegSel, dna, source);
3621 showProducts.add(xtype);
3623 showProducts.setVisible(showp);
3624 showProducts.setEnabled(showp);
3625 } catch (Exception e)
3627 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3632 protected void showProductsFor(SequenceI[] sel, Alignment ds, boolean isRegSel, boolean dna, String source)
3634 ds = this.getViewport().alignment.getDataset(); // update our local dataset reference
3635 Alignment prods = CrossRef.findXrefSequences(sel, dna, source, ds);
3638 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3639 for (int s=0; s<sprods.length;s++)
3641 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3642 if (ds.getSequences()==null || !ds.getSequences().contains(sprods[s].getDatasetSequence()))
3643 ds.addSequence(sprods[s].getDatasetSequence());
3645 Alignment al = new Alignment(sprods);
3646 AlignedCodonFrame[] cf = prods.getCodonFrames();
3647 for (int s=0; cf!=null && s<cf.length; s++)
3649 al.addCodonFrame(cf[s]);
3653 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3654 String newtitle =""+((dna) ? "Proteins " : "Nucleotides ") + " for "+((isRegSel) ? "selected region of " : "")
3656 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3659 System.err.println("No Sequences generated for xRef type "+source);
3664 public boolean canShowTranslationProducts(SequenceI[] selection, AlignmentI alignment)
3668 return (jalview.analysis.Dna.canTranslate(selection, viewport.getViewAsVisibleContigs(true)));
3669 } catch (Exception e)
3671 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3676 public void showProducts_actionPerformed(ActionEvent e)
3678 ///////////////////////////////
3679 // Collect Data to be translated/transferred
3681 SequenceI [] selection = viewport.getSequenceSelection();
3682 AlignmentI al = null;
3684 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport.getViewAsVisibleContigs(true),
3685 viewport.getGapCharacter(), viewport.getAlignment().getDataset());
3686 } catch (Exception ex) {
3688 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3692 JOptionPane.showMessageDialog(Desktop.desktop,
3693 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3694 "Translation Failed",
3695 JOptionPane.WARNING_MESSAGE);
3697 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3698 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3704 public void showTranslation_actionPerformed(ActionEvent e)
3706 ///////////////////////////////
3707 // Collect Data to be translated/transferred
3709 SequenceI [] selection = viewport.getSequenceSelection();
3710 String [] seqstring = viewport.getViewAsString(true);
3711 AlignmentI al = null;
3713 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
3714 viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
3715 viewport.alignment.getWidth(), viewport.getAlignment().getDataset());
3716 } catch (Exception ex) {
3718 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3722 JOptionPane.showMessageDialog(Desktop.desktop,
3723 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3724 "Translation Failed",
3725 JOptionPane.WARNING_MESSAGE);
3727 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3728 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3737 * @param String DOCUMENT ME!
3739 public boolean parseFeaturesFile(String file, String type)
3741 boolean featuresFile = false;
3744 featuresFile = new FeaturesFile(file,
3745 type).parse(viewport.alignment.getDataset(),
3746 alignPanel.seqPanel.seqCanvas.
3747 getFeatureRenderer().featureColours,
3752 ex.printStackTrace();
3757 viewport.showSequenceFeatures = true;
3758 showSeqFeatures.setSelected(true);
3759 alignPanel.paintAlignment(true);
3762 return featuresFile;
3765 public void dragEnter(DropTargetDragEvent evt)
3768 public void dragExit(DropTargetEvent evt)
3771 public void dragOver(DropTargetDragEvent evt)
3774 public void dropActionChanged(DropTargetDragEvent evt)
3777 public void drop(DropTargetDropEvent evt)
3779 Transferable t = evt.getTransferable();
3780 java.util.List files = null;
3784 DataFlavor uriListFlavor = new DataFlavor(
3785 "text/uri-list;class=java.lang.String");
3786 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3788 //Works on Windows and MacOSX
3789 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3790 files = (java.util.List) t.getTransferData(DataFlavor.
3791 javaFileListFlavor);
3793 else if (t.isDataFlavorSupported(uriListFlavor))
3795 // This is used by Unix drag system
3796 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3797 String data = (String) t.getTransferData(uriListFlavor);
3798 files = new java.util.ArrayList(1);
3799 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3802 st.hasMoreTokens(); )
3804 String s = st.nextToken();
3805 if (s.startsWith("#"))
3807 // the line is a comment (as per the RFC 2483)
3811 java.net.URI uri = new java.net.URI(s);
3812 java.io.File file = new java.io.File(uri);
3819 e.printStackTrace();
3826 for (int i = 0; i < files.size(); i++)
3828 loadJalviewDataFile(files.get(i).toString());
3831 catch (Exception ex)
3833 ex.printStackTrace();
3838 // This method will attempt to load a "dropped" file first by testing
3839 // whether its and Annotation file, then features file. If both are
3840 // false then the user may have dropped an alignment file onto this
3842 public void loadJalviewDataFile(String file)
3846 String protocol = "File";
3848 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3853 boolean isAnnotation = new AnnotationFile().readAnnotationFile(viewport.
3854 alignment, file, protocol);
3858 boolean isGroupsFile = parseFeaturesFile(file,protocol);
3861 String format = new IdentifyFile().Identify(file, protocol);
3863 if(format.equalsIgnoreCase("JnetFile"))
3865 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
3867 new JnetAnnotationMaker().add_annotation(predictions,
3868 viewport.getAlignment(),
3870 alignPanel.adjustAnnotationHeight();
3871 alignPanel.paintAlignment(true);
3875 new FileLoader().LoadFile(viewport, file, protocol, format);
3882 alignPanel.adjustAnnotationHeight();
3883 buildSortByAnnotationScoresMenu();
3887 catch (Exception ex)
3889 ex.printStackTrace();
3893 public void tabSelectionChanged(int index)
3897 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
3898 viewport = alignPanel.av;
3899 setMenusFromViewport(viewport);
3903 public void tabbedPane_mousePressed(MouseEvent e)
3905 if(SwingUtilities.isRightMouseButton(e))
3907 String reply = JOptionPane.showInternalInputDialog(this,
3910 JOptionPane.QUESTION_MESSAGE);
3914 viewport.viewName = reply;
3915 tabbedPane.setTitleAt( tabbedPane.getSelectedIndex() ,reply);
3921 public AlignViewport getCurrentView()
3928 * Open the dialog for regex description parsing.
3930 protected void extractScores_actionPerformed(ActionEvent e)
3932 ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
3933 if (pp.getScoresFromDescription("col", "score column ", "\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)")>0)
3935 buildSortByAnnotationScoresMenu();
3944 public PrintThread(AlignmentPanel ap)
3948 static PageFormat pf;
3951 PrinterJob printJob = PrinterJob.getPrinterJob();
3955 printJob.setPrintable(ap, pf);
3959 printJob.setPrintable(ap);
3962 if (printJob.printDialog())
3968 catch (Exception PrintException)
3970 PrintException.printStackTrace();