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 String currentFileFormat = null;
65 String fileName = null;
69 * Creates a new AlignFrame object.
71 * @param al DOCUMENT ME!
73 public AlignFrame(AlignmentI al, int width, int height)
75 this(al, null, width, height);
80 * new alignment window with hidden columns
81 * @param al AlignmentI
82 * @param hiddenColumns ColumnSelection or null
84 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
85 int width, int height)
87 this.setSize(width, height);
88 viewport = new AlignViewport(al, hiddenColumns);
90 alignPanel = new AlignmentPanel(this, viewport);
92 if(al.getDataset()==null)
97 addAlignmentPanel(alignPanel, true);
102 * Make a new AlignFrame from exisiting alignmentPanels
103 * @param ap AlignmentPanel
104 * @param av AlignViewport
106 public AlignFrame(AlignmentPanel ap)
110 addAlignmentPanel(ap, false);
116 if (viewport.conservation == null)
118 BLOSUM62Colour.setEnabled(false);
119 conservationMenuItem.setEnabled(false);
120 modifyConservation.setEnabled(false);
121 // PIDColour.setEnabled(false);
122 // abovePIDThreshold.setEnabled(false);
123 // modifyPID.setEnabled(false);
126 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT", "No sort");
128 if (sortby.equals("Id"))
130 sortIDMenuItem_actionPerformed(null);
132 else if (sortby.equals("Pairwise Identity"))
134 sortPairwiseMenuItem_actionPerformed(null);
137 if (Desktop.desktop != null)
139 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
140 addServiceListeners();
141 setGUINucleotide(viewport.alignment.isNucleotide());
144 setMenusFromViewport(viewport);
145 buildSortByAnnotationScoresMenu();
146 if (viewport.wrapAlignment)
148 wrapMenuItem_actionPerformed(null);
151 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW",false))
153 this.overviewMenuItem_actionPerformed(null);
160 public void setFileName(String file, String format)
163 currentFileFormat = format;
164 reload.setEnabled(true);
167 void addKeyListener()
169 addKeyListener(new KeyAdapter()
171 public void keyPressed(KeyEvent evt)
173 if (viewport.cursorMode &&
174 ( (evt.getKeyCode() >= KeyEvent.VK_0 &&
175 evt.getKeyCode() <= KeyEvent.VK_9)
177 (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0 &&
178 evt.getKeyCode() <= KeyEvent.VK_NUMPAD9)
180 && Character.isDigit(evt.getKeyChar()))
181 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
183 switch (evt.getKeyCode())
186 case 27: // escape key
187 deselectAllSequenceMenuItem_actionPerformed(null);
191 case KeyEvent.VK_DOWN:
192 if (evt.isAltDown() || !viewport.cursorMode)
193 moveSelectedSequences(false);
194 if (viewport.cursorMode)
195 alignPanel.seqPanel.moveCursor(0, 1);
199 if (evt.isAltDown() || !viewport.cursorMode)
200 moveSelectedSequences(true);
201 if (viewport.cursorMode)
202 alignPanel.seqPanel.moveCursor(0, -1);
206 case KeyEvent.VK_LEFT:
207 if (evt.isAltDown() || !viewport.cursorMode)
208 slideSequences(false,
209 alignPanel.seqPanel.getKeyboardNo1());
211 alignPanel.seqPanel.moveCursor( -1, 0);
216 case KeyEvent.VK_RIGHT:
217 if (evt.isAltDown() || !viewport.cursorMode)
219 alignPanel.seqPanel.getKeyboardNo1());
221 alignPanel.seqPanel.moveCursor(1, 0);
224 case KeyEvent.VK_SPACE:
225 if (viewport.cursorMode)
227 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
233 case KeyEvent.VK_DELETE:
234 case KeyEvent.VK_BACK_SPACE:
235 if (!viewport.cursorMode)
237 cut_actionPerformed(null);
241 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
249 if (viewport.cursorMode)
251 alignPanel.seqPanel.setCursorRow();
255 if (viewport.cursorMode && !evt.isControlDown())
257 alignPanel.seqPanel.setCursorColumn();
261 if (viewport.cursorMode)
263 alignPanel.seqPanel.setCursorPosition();
267 case KeyEvent.VK_ENTER:
268 case KeyEvent.VK_COMMA:
269 if (viewport.cursorMode)
271 alignPanel.seqPanel.setCursorRowAndColumn();
276 if (viewport.cursorMode)
278 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
282 if (viewport.cursorMode)
284 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
289 viewport.cursorMode = !viewport.cursorMode;
290 statusBar.setText("Keyboard editing mode is " +
291 (viewport.cursorMode ? "on" : "off"));
292 if (viewport.cursorMode)
294 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
295 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
297 alignPanel.seqPanel.seqCanvas.repaint();
303 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
304 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
305 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
307 javax.help.HelpBroker hb = hs.createHelpBroker();
308 hb.setCurrentID("home");
309 hb.setDisplayed(true);
313 ex.printStackTrace();
319 boolean toggleSeqs = !evt.isControlDown();
320 boolean toggleCols = !evt.isShiftDown();
322 boolean hide = false;
324 SequenceGroup sg = viewport.getSelectionGroup();
327 if (sg != null && sg.getSize() != viewport.alignment.getHeight())
329 hideSelSequences_actionPerformed(null);
332 else if (! (toggleCols &&
333 viewport.colSel.getSelected().size() > 0))
335 showAllSeqs_actionPerformed(null);
341 if (viewport.colSel.getSelected().size() > 0)
343 hideSelColumns_actionPerformed(null);
346 viewport.selectionGroup = sg;
351 showAllColumns_actionPerformed(null);
356 case KeyEvent.VK_PAGE_UP:
357 if (viewport.wrapAlignment)
359 alignPanel.scrollUp(true);
363 alignPanel.setScrollValues(viewport.startRes,
365 - viewport.endSeq + viewport.startSeq);
368 case KeyEvent.VK_PAGE_DOWN:
369 if (viewport.wrapAlignment)
371 alignPanel.scrollUp(false);
375 alignPanel.setScrollValues(viewport.startRes,
377 + viewport.endSeq - viewport.startSeq);
383 public void keyReleased(KeyEvent evt)
385 switch(evt.getKeyCode())
387 case KeyEvent.VK_LEFT:
388 if (evt.isAltDown() || !viewport.cursorMode)
389 viewport.firePropertyChange("alignment", null,
390 viewport.getAlignment().getSequences());
393 case KeyEvent.VK_RIGHT:
394 if (evt.isAltDown() || !viewport.cursorMode)
395 viewport.firePropertyChange("alignment", null,
396 viewport.getAlignment().getSequences());
404 public void addAlignmentPanel(final AlignmentPanel ap,
407 ap.alignFrame = this;
409 alignPanels.addElement(ap);
411 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
413 int aSize = alignPanels.size();
415 tabbedPane.setVisible(aSize>1 || ap.av.viewName!=null);
417 if (aSize == 1 && ap.av.viewName==null)
419 this.getContentPane().add(ap, BorderLayout.CENTER);
425 setInitialTabVisible();
428 expandViews.setEnabled(true);
429 gatherViews.setEnabled(true);
430 tabbedPane.addTab(ap.av.viewName, ap);
432 ap.setVisible(false);
439 ap.av.alignment.padGaps();
441 ap.av.updateConservation(ap);
442 ap.av.updateConsensus(ap);
446 public void setInitialTabVisible()
448 expandViews.setEnabled(true);
449 gatherViews.setEnabled(true);
450 tabbedPane.setVisible(true);
451 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
452 tabbedPane.addTab(first.av.viewName,first);
453 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
457 public AlignViewport getViewport()
462 /* Set up intrinsic listeners for dynamically generated GUI bits. */
463 private void addServiceListeners()
465 final java.beans.PropertyChangeListener thisListener;
466 // Do this once to get current state
467 BuildWebServiceMenu();
468 Desktop.discoverer.addPropertyChangeListener(
469 thisListener = new java.beans.PropertyChangeListener()
471 public void propertyChange(PropertyChangeEvent evt)
473 // System.out.println("Discoverer property change.");
474 if (evt.getPropertyName().equals("services"))
476 // System.out.println("Rebuilding web service menu");
477 BuildWebServiceMenu();
482 addInternalFrameListener(new javax.swing.event.
483 InternalFrameAdapter()
485 public void internalFrameClosed(
486 javax.swing.event.InternalFrameEvent evt)
488 // System.out.println("deregistering discoverer listener");
489 Desktop.discoverer.removePropertyChangeListener(thisListener);
490 closeMenuItem_actionPerformed(true);
496 public void setGUINucleotide(boolean nucleotide)
498 showTranslation.setVisible( nucleotide );
499 conservationMenuItem.setEnabled( !nucleotide );
500 modifyConservation.setEnabled( !nucleotide );
502 //Remember AlignFrame always starts as protein
505 calculateMenu.remove(calculateMenu.getItemCount()-2);
507 setShowProductsEnabled();
513 * Need to call this method when tabs are selected for multiple views,
514 * or when loading from Jalview2XML.java
515 * @param av AlignViewport
517 void setMenusFromViewport(AlignViewport av)
519 padGapsMenuitem.setSelected(av.padGaps);
520 colourTextMenuItem.setSelected(av.showColourText);
521 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
522 conservationMenuItem.setSelected(av.getConservationSelected());
523 seqLimits.setSelected(av.getShowJVSuffix());
524 idRightAlign.setSelected(av.rightAlignIds);
525 renderGapsMenuItem.setSelected(av.renderGaps);
526 wrapMenuItem.setSelected(av.wrapAlignment);
527 scaleAbove.setVisible(av.wrapAlignment);
528 scaleLeft.setVisible(av.wrapAlignment);
529 scaleRight.setVisible(av.wrapAlignment);
530 annotationPanelMenuItem.setState(av.showAnnotation);
531 viewBoxesMenuItem.setSelected(av.showBoxes);
532 viewTextMenuItem.setSelected(av.showText);
534 setColourSelected(ColourSchemeProperty.
535 getColourName(av.getGlobalColourScheme()));
537 showSeqFeatures.setSelected(av.showSequenceFeatures);
538 hiddenMarkers.setState(av.showHiddenMarkers);
539 applyToAllGroups.setState(av.colourAppliesToAllGroups);
545 Hashtable progressBars;
546 public void setProgressBar(String message, long id)
548 if(progressBars == null)
550 progressBars = new Hashtable();
553 JPanel progressPanel;
554 GridLayout layout = (GridLayout) statusPanel.getLayout();
555 if(progressBars.get( new Long(id) )!=null)
557 progressPanel = (JPanel)progressBars.get( new Long(id) );
558 statusPanel.remove(progressPanel);
559 progressBars.remove( progressPanel );
560 progressPanel = null;
563 statusBar.setText(message);
566 layout.setRows(layout.getRows() - 1);
570 progressPanel = new JPanel(new BorderLayout(10, 5));
572 JProgressBar progressBar = new JProgressBar();
573 progressBar.setIndeterminate(true);
575 progressPanel.add(new JLabel(message), BorderLayout.WEST);
576 progressPanel.add(progressBar, BorderLayout.CENTER);
578 layout.setRows(layout.getRows() + 1);
579 statusPanel.add(progressPanel);
581 progressBars.put(new Long(id), progressPanel);
591 Added so Castor Mapping file can obtain Jalview Version
593 public String getVersion()
595 return jalview.bin.Cache.getProperty("VERSION");
598 public FeatureRenderer getFeatureRenderer()
600 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
604 public void fetchSequence_actionPerformed(ActionEvent e)
606 new SequenceFetcher(this);
609 public void addFromFile_actionPerformed(ActionEvent e)
611 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
614 public void reload_actionPerformed(ActionEvent e)
618 if(currentFileFormat.equals("Jalview"))
620 JInternalFrame [] frames = Desktop.desktop.getAllFrames();
621 for(int i=0; i<frames.length; i++)
623 if (frames[i] instanceof AlignFrame
625 && ( (AlignFrame) frames[i]).fileName.equals(fileName))
629 frames[i].setSelected(true);
630 Desktop.instance.closeAssociatedWindows();
632 catch (java.beans.PropertyVetoException ex)
637 Desktop.instance.closeAssociatedWindows();
639 FileLoader loader = new FileLoader();
640 String protocol = fileName.startsWith("http:")? "URL":"File";
641 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
645 Rectangle bounds = this.getBounds();
647 FileLoader loader = new FileLoader();
648 String protocol = fileName.startsWith("http:") ? "URL" : "File";
649 AlignFrame newframe =
650 loader.LoadFileWaitTillLoaded(fileName, protocol, currentFileFormat);
652 newframe.setBounds(bounds);
654 this.closeMenuItem_actionPerformed(true);
660 public void addFromText_actionPerformed(ActionEvent e)
662 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
665 public void addFromURL_actionPerformed(ActionEvent e)
667 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
671 public void save_actionPerformed(ActionEvent e)
674 || currentFileFormat==null
675 || fileName.startsWith("http")
678 saveAs_actionPerformed(null);
682 saveAlignment(fileName, currentFileFormat);
689 * @param e DOCUMENT ME!
691 public void saveAs_actionPerformed(ActionEvent e)
693 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
694 getProperty( "LAST_DIRECTORY"),
696 { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","amsa","jar" },
698 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" },
703 chooser.setFileView(new JalviewFileView());
704 chooser.setDialogTitle("Save Alignment to file");
705 chooser.setToolTipText("Save");
707 int value = chooser.showSaveDialog(this);
709 if (value == JalviewFileChooser.APPROVE_OPTION)
711 currentFileFormat = chooser.getSelectedFormat();
712 if (currentFileFormat == null)
714 JOptionPane.showInternalMessageDialog(Desktop.desktop,
715 "You must select a file format before saving!",
716 "File format not specified",
717 JOptionPane.WARNING_MESSAGE);
718 value = chooser.showSaveDialog(this);
722 fileName = chooser.getSelectedFile().getPath();
724 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
727 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
729 saveAlignment(fileName, currentFileFormat.substring(0,currentFileFormat.indexOf(" ")));
733 public boolean saveAlignment(String file, String format)
735 boolean success = true;
737 if (format.equalsIgnoreCase("Jalview"))
739 String shortName = title;
741 if (shortName.indexOf(java.io.File.separatorChar) > -1)
743 shortName = shortName.substring(shortName.lastIndexOf(
744 java.io.File.separatorChar) + 1);
747 success = new Jalview2XML().SaveAlignment(this, file, shortName);
749 statusBar.setText("Successfully saved to file: "
751 +format +" format.");
757 String[] omitHidden = null;
759 if (viewport.hasHiddenColumns)
761 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
762 "The Alignment contains hidden columns."
763 + "\nDo you want to save only the visible alignment?",
764 "Save / Omit Hidden Columns",
765 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
767 if (reply == JOptionPane.YES_OPTION)
769 omitHidden = viewport.getViewAsString(false);
772 FormatAdapter f = new FormatAdapter();
774 String output = f.formatSequences(
776 (Alignment) viewport.alignment, // class cast exceptions will occur in the distant future
777 omitHidden, f.getCacheSuffixDefault(format));
787 java.io.PrintWriter out = new java.io.PrintWriter(
788 new java.io.FileWriter(file));
793 statusBar.setText("Successfully saved to file: "
795 + format + " format.");
800 ex.printStackTrace();
807 JOptionPane.showInternalMessageDialog(
808 this, "Couldn't save file: " + fileName,
810 JOptionPane.WARNING_MESSAGE);
819 * @param e DOCUMENT ME!
821 protected void outputText_actionPerformed(ActionEvent e)
823 String [] omitHidden = null;
825 if(viewport.hasHiddenColumns)
827 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
828 "The Alignment contains hidden columns."
829 +"\nDo you want to output only the visible alignment?",
830 "Save / Omit Hidden Columns",
831 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
833 if(reply==JOptionPane.YES_OPTION)
835 omitHidden = viewport.getViewAsString(false);
839 CutAndPasteTransfer cap = new CutAndPasteTransfer();
840 cap.setForInput(null);
841 Desktop.addInternalFrame(cap,
842 "Alignment output - " + e.getActionCommand(), 600,
846 cap.setText(new FormatAdapter().formatSequences(
847 e.getActionCommand(),
855 * @param e DOCUMENT ME!
857 protected void htmlMenuItem_actionPerformed(ActionEvent e)
859 new HTMLOutput(alignPanel,
860 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
861 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
864 public void createImageMap(File file, String image)
866 alignPanel.makePNGImageMap(file, image);
872 * @param e DOCUMENT ME!
874 public void createPNG(File f)
876 alignPanel.makePNG(f);
882 * @param e DOCUMENT ME!
884 public void createEPS(File f)
886 alignPanel.makeEPS(f);
890 public void pageSetup_actionPerformed(ActionEvent e)
892 PrinterJob printJob = PrinterJob.getPrinterJob();
893 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
899 * @param e DOCUMENT ME!
901 public void printMenuItem_actionPerformed(ActionEvent e)
903 //Putting in a thread avoids Swing painting problems
904 PrintThread thread = new PrintThread(alignPanel);
908 public void exportFeatures_actionPerformed(ActionEvent e)
910 new AnnotationExporter().exportFeatures(alignPanel);
914 public void exportAnnotations_actionPerformed(ActionEvent e)
916 new AnnotationExporter().exportAnnotations(
918 viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
919 viewport.alignment.getGroups(),
920 ((Alignment)viewport.alignment).alignmentProperties
925 public void associatedData_actionPerformed(ActionEvent e)
927 // Pick the tree file
928 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
931 chooser.setFileView(new JalviewFileView());
932 chooser.setDialogTitle("Load Jalview Annotations or Features File");
933 chooser.setToolTipText("Load Jalview Annotations / Features file");
935 int value = chooser.showOpenDialog(null);
937 if (value == JalviewFileChooser.APPROVE_OPTION)
939 String choice = chooser.getSelectedFile().getPath();
940 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
941 loadJalviewDataFile(choice);
950 * @param e DOCUMENT ME!
952 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
954 if(alignPanels!=null && alignPanels.size()<2)
961 if(alignPanels!=null)
965 for (int i = 0; i < alignPanels.size(); i++)
967 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
968 jalview.structure.StructureSelectionManager.getStructureSelectionManager()
969 .removeStructureViewerListener(ap.seqPanel, null);
970 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
971 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
972 PaintRefresher.RemoveComponent(ap);
973 ap.av.alignment = null;
978 int index = tabbedPane.getSelectedIndex();
980 alignPanels.removeElement(alignPanel);
981 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
982 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
983 PaintRefresher.RemoveComponent(alignPanel);
984 viewport.alignment = null;
988 tabbedPane.removeTabAt(index);
989 tabbedPane.validate();
991 if(index==tabbedPane.getTabCount())
996 this.tabSelectionChanged(index);
1002 this.setClosed(true);
1005 catch (Exception ex)
1007 ex.printStackTrace();
1015 void updateEditMenuBar()
1018 if (viewport.historyList.size() > 0)
1020 undoMenuItem.setEnabled(true);
1021 CommandI command = (CommandI) viewport.historyList.peek();
1022 undoMenuItem.setText("Undo " + command.getDescription());
1026 undoMenuItem.setEnabled(false);
1027 undoMenuItem.setText("Undo");
1030 if (viewport.redoList.size() > 0)
1032 redoMenuItem.setEnabled(true);
1034 CommandI command = (CommandI) viewport.redoList.peek();
1035 redoMenuItem.setText("Redo " + command.getDescription());
1039 redoMenuItem.setEnabled(false);
1040 redoMenuItem.setText("Redo");
1045 public void addHistoryItem(CommandI command)
1047 if(command.getSize()>0)
1049 viewport.historyList.push(command);
1050 viewport.redoList.clear();
1051 updateEditMenuBar();
1052 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1058 * @return alignment objects for all views
1060 AlignmentI[] getViewAlignments()
1062 if (alignPanels!=null)
1064 Enumeration e = alignPanels.elements();
1065 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1066 for (int i=0; e.hasMoreElements(); i++)
1068 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1074 return new AlignmentI[] { viewport.alignment };
1081 * @param e DOCUMENT ME!
1083 protected void undoMenuItem_actionPerformed(ActionEvent e)
1085 if (viewport.historyList.empty())
1087 CommandI command = (CommandI)viewport.historyList.pop();
1088 viewport.redoList.push(command);
1089 command.undoCommand(getViewAlignments());
1091 AlignViewport originalSource = getOriginatingSource(command);
1092 updateEditMenuBar();
1094 if(originalSource!=null)
1096 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1097 originalSource.firePropertyChange("alignment",
1099 originalSource.alignment.getSequences());
1106 * @param e DOCUMENT ME!
1108 protected void redoMenuItem_actionPerformed(ActionEvent e)
1110 if(viewport.redoList.size()<1)
1115 CommandI command = (CommandI) viewport.redoList.pop();
1116 viewport.historyList.push(command);
1117 command.doCommand(getViewAlignments());
1119 AlignViewport originalSource = getOriginatingSource(command);
1120 updateEditMenuBar();
1122 if(originalSource!=null)
1124 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1125 originalSource.firePropertyChange("alignment",
1127 originalSource.alignment.getSequences());
1131 AlignViewport getOriginatingSource(CommandI command)
1133 AlignViewport originalSource = null;
1134 //For sequence removal and addition, we need to fire
1135 //the property change event FROM the viewport where the
1136 //original alignment was altered
1138 if (command instanceof EditCommand)
1140 EditCommand editCommand = (EditCommand) command;
1141 al = editCommand.getAlignment();
1142 Vector comps = (Vector) PaintRefresher.components
1143 .get(viewport.getSequenceSetId());
1145 for (int i = 0; i < comps.size(); i++)
1147 if (comps.elementAt(i) instanceof AlignmentPanel)
1149 if (al == ( (AlignmentPanel) comps.elementAt(i)).av.alignment)
1151 originalSource = ( (AlignmentPanel) comps.elementAt(i)).av;
1158 if (originalSource == null)
1160 //The original view is closed, we must validate
1161 //the current view against the closed view first
1164 PaintRefresher.validateSequences(al, viewport.alignment);
1167 originalSource = viewport;
1170 return originalSource;
1176 * @param up DOCUMENT ME!
1178 public void moveSelectedSequences(boolean up)
1180 SequenceGroup sg = viewport.getSelectionGroup();
1189 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1191 SequenceI seq = viewport.alignment.getSequenceAt(i);
1193 if (!sg.getSequences(null).contains(seq))
1198 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1200 if (sg.getSequences(null).contains(temp))
1205 viewport.alignment.getSequences().setElementAt(temp, i);
1206 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1211 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1213 SequenceI seq = viewport.alignment.getSequenceAt(i);
1215 if (!sg.getSequences(null).contains(seq))
1220 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1222 if (sg.getSequences(null).contains(temp))
1227 viewport.alignment.getSequences().setElementAt(temp, i);
1228 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1232 alignPanel.paintAlignment(true);
1238 synchronized void slideSequences(boolean right, int size)
1240 Vector sg = new Vector();
1241 if(viewport.cursorMode)
1243 sg.addElement(viewport.alignment.getSequenceAt(
1244 alignPanel.seqPanel.seqCanvas.cursorY));
1246 else if(viewport.getSelectionGroup()!=null
1247 && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
1249 sg = viewport.getSelectionGroup().getSequences(
1250 viewport.hiddenRepSequences);
1258 Vector invertGroup = new Vector();
1260 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1262 if(!sg.contains(viewport.alignment.getSequenceAt(i)))
1263 invertGroup.add(viewport.alignment.getSequenceAt(i));
1266 SequenceI[] seqs1 = new SequenceI[sg.size()];
1267 for (int i = 0; i < sg.size(); i++)
1268 seqs1[i] = (SequenceI) sg.elementAt(i);
1270 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1271 for (int i = 0; i < invertGroup.size(); i++)
1272 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1274 SlideSequencesCommand ssc;
1276 ssc = new SlideSequencesCommand("Slide Sequences",
1278 viewport.getGapCharacter()
1281 ssc = new SlideSequencesCommand("Slide Sequences",
1283 viewport.getGapCharacter()
1286 int groupAdjustment = 0;
1287 if (ssc.getGapsInsertedBegin() && right)
1289 if (viewport.cursorMode)
1290 alignPanel.seqPanel.moveCursor(size, 0);
1292 groupAdjustment = size;
1294 else if (!ssc.getGapsInsertedBegin() && !right)
1296 if (viewport.cursorMode)
1297 alignPanel.seqPanel.moveCursor( -size, 0);
1299 groupAdjustment = -size;
1302 if (groupAdjustment != 0)
1304 viewport.getSelectionGroup().setStartRes(
1305 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1306 viewport.getSelectionGroup().setEndRes(
1307 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1311 boolean appendHistoryItem = false;
1312 if(viewport.historyList!=null
1313 && viewport.historyList.size()>0
1314 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1316 appendHistoryItem = ssc.appendSlideCommand(
1317 (SlideSequencesCommand)viewport.historyList.peek())
1321 if(!appendHistoryItem)
1322 addHistoryItem(ssc);
1331 * @param e DOCUMENT ME!
1333 protected void copy_actionPerformed(ActionEvent e)
1336 if (viewport.getSelectionGroup() == null)
1340 // TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
1341 SequenceI [] seqs = viewport.getSelectionAsNewSequence();
1342 String[] omitHidden = null;
1344 if (viewport.hasHiddenColumns)
1346 omitHidden = viewport.getViewAsString(true);
1349 String output = new FormatAdapter().formatSequences(
1354 StringSelection ss = new StringSelection(output);
1358 jalview.gui.Desktop.internalCopy = true;
1359 //Its really worth setting the clipboard contents
1360 //to empty before setting the large StringSelection!!
1361 Toolkit.getDefaultToolkit().getSystemClipboard()
1362 .setContents(new StringSelection(""), null);
1364 Toolkit.getDefaultToolkit().getSystemClipboard()
1365 .setContents(ss, Desktop.instance);
1367 catch (OutOfMemoryError er)
1369 er.printStackTrace();
1370 javax.swing.SwingUtilities.invokeLater(new Runnable()
1374 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1375 "Out of memory copying region!!"
1377 "\nSee help files for increasing Java Virtual Machine memory."
1379 javax.swing.JOptionPane.WARNING_MESSAGE);
1386 Vector hiddenColumns = null;
1387 if(viewport.hasHiddenColumns)
1389 hiddenColumns =new Vector();
1390 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1391 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
1394 int[] region = (int[])
1395 viewport.getColumnSelection().getHiddenColumns().elementAt(i);
1397 hiddenColumns.addElement(new int[]
1398 {region[0] - hiddenOffset,
1399 region[1]-hiddenOffset});
1403 Desktop.jalviewClipboard = new Object[]
1406 viewport.alignment.getDataset(),
1408 statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
1414 * @param e DOCUMENT ME!
1416 protected void pasteNew_actionPerformed(ActionEvent e)
1424 * @param e DOCUMENT ME!
1426 protected void pasteThis_actionPerformed(ActionEvent e)
1434 * @param newAlignment DOCUMENT ME!
1436 void paste(boolean newAlignment)
1438 boolean externalPaste=true;
1441 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1442 Transferable contents = c.getContents(this);
1444 if (contents == null)
1452 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1453 if (str.length() < 1)
1458 format = new IdentifyFile().Identify(str, "Paste");
1461 catch (OutOfMemoryError er)
1463 er.printStackTrace();
1464 javax.swing.SwingUtilities.invokeLater(new Runnable()
1468 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1469 "Out of memory pasting sequences!!"
1471 "\nSee help files for increasing Java Virtual Machine memory."
1473 javax.swing.JOptionPane.WARNING_MESSAGE);
1480 SequenceI[] sequences;
1481 boolean annotationAdded = false;
1482 AlignmentI alignment = null;
1484 if(Desktop.jalviewClipboard!=null)
1486 // The clipboard was filled from within Jalview, we must use the sequences
1487 // And dataset from the copied alignment
1488 SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
1489 // be doubly sure that we create *new* sequence objects.
1490 sequences = new SequenceI[newseq.length];
1491 for (int i=0;i<newseq.length;i++) {
1492 sequences[i] = new Sequence(newseq[i]);
1494 alignment = new Alignment(sequences);
1495 externalPaste = false;
1499 // parse the clipboard as an alignment.
1500 alignment = new FormatAdapter().readFile(str, "Paste", format);
1501 sequences = alignment.getSequencesArray();
1509 if (Desktop.jalviewClipboard != null)
1511 // dataset is inherited
1512 alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
1516 // new dataset is constructed
1517 alignment.setDataset(null);
1519 alwidth = alignment.getWidth()+1;
1523 AlignmentI pastedal = alignment; // preserve pasted alignment object
1524 // Add pasted sequences and dataset into existing alignment.
1525 alignment = viewport.getAlignment();
1526 alwidth = alignment.getWidth()+1;
1527 // decide if we need to import sequences from an existing dataset
1528 boolean importDs = Desktop.jalviewClipboard != null
1529 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1530 // importDs==true instructs us to copy over new dataset sequences from
1531 // an existing alignment
1532 Vector newDs = (importDs) ? new Vector() : null; // used to create
1533 // minimum dataset set
1535 for (int i = 0; i < sequences.length; i++)
1539 newDs.addElement(null);
1541 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1543 if (importDs && ds != null)
1545 if (!newDs.contains(ds))
1547 newDs.setElementAt(ds, i);
1548 ds = new Sequence(ds);
1549 // update with new dataset sequence
1550 sequences[i].setDatasetSequence(ds);
1554 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1559 // copy and derive new dataset sequence
1560 sequences[i] = sequences[i].deriveSequence();
1561 alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
1562 // TODO: avoid creation of duplicate dataset sequences with a
1563 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1565 alignment.addSequence(sequences[i]); // merges dataset
1569 newDs.clear(); // tidy up
1571 if (pastedal.getAlignmentAnnotation()!=null) {
1572 // Add any annotation attached to alignment.
1573 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1574 for (int i=0; i<alann.length; i++)
1576 annotationAdded=true;
1577 if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
1578 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1579 newann.padAnnotation(alwidth);
1580 alignment.addAnnotation(newann);
1585 if (!newAlignment) {
1589 addHistoryItem(new EditCommand(
1594 alignment.getWidth(),
1598 // Add any annotations attached to sequences
1599 for (int i = 0; i < sequences.length; i++)
1601 if (sequences[i].getAnnotation() != null)
1603 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1605 annotationAdded=true;
1606 sequences[i].getAnnotation()[a].adjustForAlignment();
1607 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1608 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
1609 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1613 if (!newAlignment) {
1615 // propagate alignment changed.
1616 viewport.setEndSeq(alignment.getHeight());
1617 if (annotationAdded)
1619 // Duplicate sequence annotation in all views.
1620 AlignmentI[] alview = this.getViewAlignments();
1621 for (int i = 0; i < sequences.length; i++)
1623 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1626 for (int avnum=0;avnum<alview.length; avnum++)
1628 if (alview[avnum]!=alignment)
1630 // duplicate in a view other than the one with input focus
1631 int avwidth = alview[avnum].getWidth()+1;
1632 // this relies on sann being preserved after we
1633 // modify the sequence's annotation array for each duplication
1634 for (int a=0; a<sann.length; a++)
1636 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
1637 sequences[i].addAlignmentAnnotation(newann);
1638 newann.padAnnotation(avwidth);
1639 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
1640 alview[avnum].setAnnotationIndex(newann, a);
1645 buildSortByAnnotationScoresMenu();
1647 viewport.firePropertyChange("alignment", null, alignment.getSequences());
1650 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
1651 String newtitle = new String("Copied sequences");
1653 if(Desktop.jalviewClipboard!=null && Desktop.jalviewClipboard[2]!=null)
1655 Vector hc = (Vector)Desktop.jalviewClipboard[2];
1656 for(int i=0; i<hc.size(); i++)
1658 int [] region = (int[]) hc.elementAt(i);
1659 af.viewport.hideColumns(region[0], region[1]);
1664 //>>>This is a fix for the moment, until a better solution is found!!<<<
1665 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
1666 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1668 // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
1669 if (!externalPaste) {
1670 if (title.startsWith("Copied sequences"))
1676 newtitle = newtitle.concat("- from " + title);
1679 newtitle = new String("Pasted sequences");
1682 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1689 catch (Exception ex)
1691 ex.printStackTrace();
1692 System.out.println("Exception whilst pasting: "+ex);
1693 // could be anything being pasted in here
1702 * @param e DOCUMENT ME!
1704 protected void cut_actionPerformed(ActionEvent e)
1706 copy_actionPerformed(null);
1707 delete_actionPerformed(null);
1713 * @param e DOCUMENT ME!
1715 protected void delete_actionPerformed(ActionEvent evt)
1718 SequenceGroup sg = viewport.getSelectionGroup();
1724 Vector seqs = new Vector();
1726 for (int i = 0; i < sg.getSize(); i++)
1728 seq = sg.getSequenceAt(i);
1729 seqs.addElement(seq);
1733 // If the cut affects all sequences, remove highlighted columns
1734 if (sg.getSize() == viewport.alignment.getHeight())
1736 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1737 sg.getEndRes() + 1);
1741 SequenceI [] cut = new SequenceI[seqs.size()];
1742 for(int i=0; i<seqs.size(); i++)
1744 cut[i] = (SequenceI)seqs.elementAt(i);
1751 addHistoryItem(new EditCommand("Cut Sequences",
1755 sg.getEndRes()-sg.getStartRes()+1,
1756 viewport.alignment));
1759 viewport.setSelectionGroup(null);
1760 viewport.alignment.deleteGroup(sg);
1762 viewport.firePropertyChange("alignment", null,
1763 viewport.getAlignment().getSequences());
1765 if (viewport.getAlignment().getHeight() < 1)
1769 this.setClosed(true);
1771 catch (Exception ex)
1780 * @param e DOCUMENT ME!
1782 protected void deleteGroups_actionPerformed(ActionEvent e)
1784 viewport.alignment.deleteAllGroups();
1785 viewport.sequenceColours = null;
1786 viewport.setSelectionGroup(null);
1787 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1788 alignPanel.paintAlignment(true);
1794 * @param e DOCUMENT ME!
1796 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1798 SequenceGroup sg = new SequenceGroup();
1800 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1803 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1806 sg.setEndRes(viewport.alignment.getWidth() - 1);
1807 viewport.setSelectionGroup(sg);
1808 alignPanel.paintAlignment(true);
1809 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1815 * @param e DOCUMENT ME!
1817 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1819 if(viewport.cursorMode)
1821 alignPanel.seqPanel.keyboardNo1 = null;
1822 alignPanel.seqPanel.keyboardNo2 = null;
1824 viewport.setSelectionGroup(null);
1825 viewport.getColumnSelection().clear();
1826 viewport.setSelectionGroup(null);
1827 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1828 alignPanel.idPanel.idCanvas.searchResults = null;
1829 alignPanel.paintAlignment(true);
1830 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1836 * @param e DOCUMENT ME!
1838 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1840 SequenceGroup sg = viewport.getSelectionGroup();
1844 selectAllSequenceMenuItem_actionPerformed(null);
1849 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1852 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1855 alignPanel.paintAlignment(true);
1857 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1860 public void invertColSel_actionPerformed(ActionEvent e)
1862 viewport.invertColumnSelection();
1863 alignPanel.paintAlignment(true);
1870 * @param e DOCUMENT ME!
1872 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1874 trimAlignment(true);
1880 * @param e DOCUMENT ME!
1882 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1884 trimAlignment(false);
1887 void trimAlignment(boolean trimLeft)
1889 ColumnSelection colSel = viewport.getColumnSelection();
1892 if (colSel.size() > 0)
1896 column = colSel.getMin();
1900 column = colSel.getMax();
1904 if(viewport.getSelectionGroup()!=null)
1906 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1907 hiddenRepSequences);
1911 seqs = viewport.alignment.getSequencesArray();
1915 TrimRegionCommand trimRegion;
1918 trimRegion = new TrimRegionCommand("Remove Left",
1919 TrimRegionCommand.TRIM_LEFT,
1924 viewport.selectionGroup);
1925 viewport.setStartRes(0);
1929 trimRegion = new TrimRegionCommand("Remove Right",
1930 TrimRegionCommand.TRIM_RIGHT,
1935 viewport.selectionGroup);
1938 statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
1941 addHistoryItem(trimRegion);
1943 Vector groups = viewport.alignment.getGroups();
1945 for (int i = 0; i < groups.size(); i++)
1947 SequenceGroup sg = (SequenceGroup) groups.get(i);
1949 if ( (trimLeft && !sg.adjustForRemoveLeft(column))
1950 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1952 viewport.alignment.deleteGroup(sg);
1956 viewport.firePropertyChange("alignment", null,
1957 viewport.getAlignment().getSequences());
1964 * @param e DOCUMENT ME!
1966 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1968 int start = 0, end = viewport.alignment.getWidth()-1;
1971 if (viewport.getSelectionGroup() != null)
1973 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1974 hiddenRepSequences);
1975 start = viewport.getSelectionGroup().getStartRes();
1976 end = viewport.getSelectionGroup().getEndRes();
1980 seqs = viewport.alignment.getSequencesArray();
1984 RemoveGapColCommand removeGapCols =
1985 new RemoveGapColCommand("Remove Gapped Columns",
1988 viewport.alignment);
1990 addHistoryItem(removeGapCols);
1992 statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
1994 //This is to maintain viewport position on first residue
1996 SequenceI seq = viewport.alignment.getSequenceAt(0);
1997 int startRes = seq.findPosition(viewport.startRes);
1998 // ShiftList shifts;
1999 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2000 // edit.alColumnChanges=shifts.getInverse();
2001 // if (viewport.hasHiddenColumns)
2002 // viewport.getColumnSelection().compensateForEdits(shifts);
2003 viewport.setStartRes(seq.findIndex(startRes)-1);
2004 viewport.firePropertyChange("alignment", null,
2005 viewport.getAlignment().getSequences());
2012 * @param e DOCUMENT ME!
2014 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2016 int start = 0, end = viewport.alignment.getWidth()-1;
2019 if (viewport.getSelectionGroup() != null)
2021 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
2022 hiddenRepSequences);
2023 start = viewport.getSelectionGroup().getStartRes();
2024 end = viewport.getSelectionGroup().getEndRes();
2028 seqs = viewport.alignment.getSequencesArray();
2031 //This is to maintain viewport position on first residue
2033 SequenceI seq = viewport.alignment.getSequenceAt(0);
2034 int startRes = seq.findPosition(viewport.startRes);
2036 addHistoryItem(new RemoveGapsCommand("Remove Gaps",
2039 viewport.alignment));
2041 viewport.setStartRes(seq.findIndex(startRes)-1);
2043 viewport.firePropertyChange("alignment", null,
2044 viewport.getAlignment().getSequences());
2051 * @param e DOCUMENT ME!
2053 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2055 viewport.padGaps = padGapsMenuitem.isSelected();
2057 viewport.firePropertyChange("alignment",
2059 viewport.getAlignment().getSequences());
2065 * @param e DOCUMENT ME!
2067 public void findMenuItem_actionPerformed(ActionEvent e)
2072 public void newView_actionPerformed(ActionEvent e)
2074 AlignmentPanel newap =
2075 new Jalview2XML().copyAlignPanel(alignPanel, true);
2077 newap.av.gatherViewsHere = false;
2079 if (viewport.viewName == null)
2081 viewport.viewName = "Original";
2084 newap.av.historyList = viewport.historyList;
2085 newap.av.redoList = viewport.redoList;
2087 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2088 String newViewName = "View " +index;
2090 Vector comps = (Vector) PaintRefresher.components.get(viewport.
2091 getSequenceSetId());
2092 Vector existingNames = new Vector();
2093 for(int i=0; i<comps.size(); i++)
2095 if(comps.elementAt(i) instanceof AlignmentPanel)
2097 AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
2098 if(!existingNames.contains(ap.av.viewName))
2100 existingNames.addElement(ap.av.viewName);
2105 while(existingNames.contains(newViewName))
2107 newViewName = "View "+ (++index);
2110 newap.av.viewName = newViewName;
2112 addAlignmentPanel(newap, false);
2114 if(alignPanels.size()==2)
2116 viewport.gatherViewsHere = true;
2118 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2121 public void expandViews_actionPerformed(ActionEvent e)
2123 Desktop.instance.explodeViews(this);
2126 public void gatherViews_actionPerformed(ActionEvent e)
2128 Desktop.instance.gatherViews(this);
2136 * @param e DOCUMENT ME!
2138 public void font_actionPerformed(ActionEvent e)
2140 new FontChooser(alignPanel);
2147 * @param e DOCUMENT ME!
2149 protected void seqLimit_actionPerformed(ActionEvent e)
2151 viewport.setShowJVSuffix(seqLimits.isSelected());
2153 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
2154 alignPanel.paintAlignment(true);
2157 public void idRightAlign_actionPerformed(ActionEvent e)
2159 viewport.rightAlignIds = idRightAlign.isSelected();
2160 alignPanel.paintAlignment(true);
2168 * @param e DOCUMENT ME!
2170 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2172 viewport.setColourText(colourTextMenuItem.isSelected());
2173 alignPanel.paintAlignment(true);
2179 * @param e DOCUMENT ME!
2181 public void wrapMenuItem_actionPerformed(ActionEvent e)
2183 scaleAbove.setVisible(wrapMenuItem.isSelected());
2184 scaleLeft.setVisible(wrapMenuItem.isSelected());
2185 scaleRight.setVisible(wrapMenuItem.isSelected());
2186 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2187 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2190 public void showAllSeqs_actionPerformed(ActionEvent e)
2192 viewport.showAllHiddenSeqs();
2195 public void showAllColumns_actionPerformed(ActionEvent e)
2197 viewport.showAllHiddenColumns();
2201 public void hideSelSequences_actionPerformed(ActionEvent e)
2203 viewport.hideAllSelectedSeqs();
2204 alignPanel.paintAlignment(true);
2207 public void hideSelColumns_actionPerformed(ActionEvent e)
2209 viewport.hideSelectedColumns();
2210 alignPanel.paintAlignment(true);
2213 public void hiddenMarkers_actionPerformed(ActionEvent e)
2215 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2222 * @param e DOCUMENT ME!
2224 protected void scaleAbove_actionPerformed(ActionEvent e)
2226 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2227 alignPanel.paintAlignment(true);
2233 * @param e DOCUMENT ME!
2235 protected void scaleLeft_actionPerformed(ActionEvent e)
2237 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2238 alignPanel.paintAlignment(true);
2244 * @param e DOCUMENT ME!
2246 protected void scaleRight_actionPerformed(ActionEvent e)
2248 viewport.setScaleRightWrapped(scaleRight.isSelected());
2249 alignPanel.paintAlignment(true);
2255 * @param e DOCUMENT ME!
2257 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2259 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2260 alignPanel.paintAlignment(true);
2266 * @param e DOCUMENT ME!
2268 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2270 viewport.setShowText(viewTextMenuItem.isSelected());
2271 alignPanel.paintAlignment(true);
2277 * @param e DOCUMENT ME!
2279 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2281 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2282 alignPanel.paintAlignment(true);
2286 public FeatureSettings featureSettings;
2287 public void featureSettings_actionPerformed(ActionEvent e)
2289 if(featureSettings !=null )
2291 featureSettings.close();
2292 featureSettings = null;
2294 featureSettings = new FeatureSettings(this);
2300 * @param evt DOCUMENT ME!
2302 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2304 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2305 alignPanel.paintAlignment(true);
2306 if (alignPanel.getOverviewPanel() != null)
2308 alignPanel.getOverviewPanel().updateOverviewImage();
2315 * @param e DOCUMENT ME!
2317 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2319 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2320 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2323 public void alignmentProperties()
2325 JEditorPane editPane = new JEditorPane("text/html","");
2326 editPane.setEditable(false);
2327 StringBuffer contents = new StringBuffer("<html>");
2330 int min=Integer.MAX_VALUE, max=0;
2331 for(int i=0; i<viewport.alignment.getHeight(); i++)
2333 int size = viewport.alignment.getSequenceAt(i).getEnd()
2334 -viewport.alignment.getSequenceAt(i).getStart();
2341 avg = avg/(float)viewport.alignment.getHeight();
2343 contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
2344 contents.append("<br>Minimum Sequence Length: "+min);
2345 contents.append("<br>Maximum Sequence Length: "+max);
2346 contents.append("<br>Average Length: "+(int)avg);
2348 if (((Alignment)viewport.alignment).getProperties() != null)
2350 Hashtable props = ((Alignment)viewport.alignment).getProperties();
2351 Enumeration en = props.keys();
2352 contents.append("<br><br><table border=\"1\">");
2353 while(en.hasMoreElements())
2355 String key = en.nextElement().toString();
2356 StringBuffer val = new StringBuffer();
2357 String vals = props.get(key).toString();
2360 npos = vals.indexOf("\n",pos);
2363 val.append(vals.substring(pos));
2365 val.append(vals.substring(pos, npos));
2370 contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
2372 contents.append("</table>");
2374 editPane.setText(contents.toString()+"</html>");
2375 JInternalFrame frame = new JInternalFrame();
2376 frame.getContentPane().add(new JScrollPane(editPane));
2378 Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
2385 * @param e DOCUMENT ME!
2387 public void overviewMenuItem_actionPerformed(ActionEvent e)
2389 if (alignPanel.overviewPanel != null)
2394 JInternalFrame frame = new JInternalFrame();
2395 OverviewPanel overview = new OverviewPanel(alignPanel);
2396 frame.setContentPane(overview);
2397 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(),
2398 frame.getWidth(), frame.getHeight());
2400 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2401 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2403 public void internalFrameClosed(
2404 javax.swing.event.InternalFrameEvent evt)
2406 alignPanel.setOverviewPanel(null);
2411 alignPanel.setOverviewPanel(overview);
2414 public void textColour_actionPerformed(ActionEvent e)
2416 new TextColourChooser().chooseColour(alignPanel, null);
2422 * @param e DOCUMENT ME!
2424 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2432 * @param e DOCUMENT ME!
2434 public void clustalColour_actionPerformed(ActionEvent e)
2436 changeColour(new ClustalxColourScheme(
2437 viewport.alignment.getSequences(), viewport.alignment.getWidth()));
2443 * @param e DOCUMENT ME!
2445 public void zappoColour_actionPerformed(ActionEvent e)
2447 changeColour(new ZappoColourScheme());
2453 * @param e DOCUMENT ME!
2455 public void taylorColour_actionPerformed(ActionEvent e)
2457 changeColour(new TaylorColourScheme());
2463 * @param e DOCUMENT ME!
2465 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2467 changeColour(new HydrophobicColourScheme());
2473 * @param e DOCUMENT ME!
2475 public void helixColour_actionPerformed(ActionEvent e)
2477 changeColour(new HelixColourScheme());
2483 * @param e DOCUMENT ME!
2485 public void strandColour_actionPerformed(ActionEvent e)
2487 changeColour(new StrandColourScheme());
2493 * @param e DOCUMENT ME!
2495 public void turnColour_actionPerformed(ActionEvent e)
2497 changeColour(new TurnColourScheme());
2503 * @param e DOCUMENT ME!
2505 public void buriedColour_actionPerformed(ActionEvent e)
2507 changeColour(new BuriedColourScheme());
2513 * @param e DOCUMENT ME!
2515 public void nucleotideColour_actionPerformed(ActionEvent e)
2517 changeColour(new NucleotideColourScheme());
2520 public void annotationColour_actionPerformed(ActionEvent e)
2522 new AnnotationColourChooser(viewport, alignPanel);
2529 * @param e DOCUMENT ME!
2531 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2533 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2539 * @param cs DOCUMENT ME!
2541 public void changeColour(ColourSchemeI cs)
2547 if (viewport.getAbovePIDThreshold())
2549 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2552 cs.setThreshold(threshold,
2553 viewport.getIgnoreGapsConsensus());
2555 viewport.setGlobalColourScheme(cs);
2559 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2562 if (viewport.getConservationSelected())
2565 Alignment al = (Alignment) viewport.alignment;
2566 Conservation c = new Conservation("All",
2567 ResidueProperties.propHash, 3,
2568 al.getSequences(), 0,
2572 c.verdict(false, viewport.ConsPercGaps);
2574 cs.setConservation(c);
2576 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel, cs,
2581 cs.setConservation(null);
2584 cs.setConsensus(viewport.hconsensus);
2587 viewport.setGlobalColourScheme(cs);
2589 if (viewport.getColourAppliesToAllGroups())
2591 Vector groups = viewport.alignment.getGroups();
2593 for (int i = 0; i < groups.size(); i++)
2595 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2603 if (cs instanceof ClustalxColourScheme)
2605 sg.cs = new ClustalxColourScheme(
2606 sg.getSequences(viewport.hiddenRepSequences), sg.getWidth());
2608 else if (cs instanceof UserColourScheme)
2610 sg.cs = new UserColourScheme( ( (UserColourScheme) cs).getColours());
2616 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2618 catch (Exception ex)
2623 if (viewport.getAbovePIDThreshold()
2624 || cs instanceof PIDColourScheme
2625 || cs instanceof Blosum62ColourScheme)
2627 sg.cs.setThreshold(threshold,
2628 viewport.getIgnoreGapsConsensus());
2630 sg.cs.setConsensus(AAFrequency.calculate(
2631 sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
2636 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2640 if (viewport.getConservationSelected())
2642 Conservation c = new Conservation("Group",
2643 ResidueProperties.propHash, 3,
2644 sg.getSequences(viewport.
2645 hiddenRepSequences),
2649 c.verdict(false, viewport.ConsPercGaps);
2650 sg.cs.setConservation(c);
2654 sg.cs.setConservation(null);
2659 if (alignPanel.getOverviewPanel() != null)
2661 alignPanel.getOverviewPanel().updateOverviewImage();
2667 alignPanel.paintAlignment(true);
2673 * @param e DOCUMENT ME!
2675 protected void modifyPID_actionPerformed(ActionEvent e)
2677 if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme!=null)
2679 SliderPanel.setPIDSliderSource(alignPanel,
2680 viewport.getGlobalColourScheme(),
2682 SliderPanel.showPIDSlider();
2689 * @param e DOCUMENT ME!
2691 protected void modifyConservation_actionPerformed(ActionEvent e)
2693 if (viewport.getConservationSelected() && viewport.globalColourScheme!=null)
2695 SliderPanel.setConservationSlider(alignPanel,
2696 viewport.globalColourScheme,
2698 SliderPanel.showConservationSlider();
2705 * @param e DOCUMENT ME!
2707 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2709 viewport.setConservationSelected(conservationMenuItem.isSelected());
2711 viewport.setAbovePIDThreshold(false);
2712 abovePIDThreshold.setSelected(false);
2714 changeColour(viewport.getGlobalColourScheme());
2716 modifyConservation_actionPerformed(null);
2722 * @param e DOCUMENT ME!
2724 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2726 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2728 conservationMenuItem.setSelected(false);
2729 viewport.setConservationSelected(false);
2731 changeColour(viewport.getGlobalColourScheme());
2733 modifyPID_actionPerformed(null);
2739 * @param e DOCUMENT ME!
2741 public void userDefinedColour_actionPerformed(ActionEvent e)
2743 if (e.getActionCommand().equals("User Defined..."))
2745 new UserDefinedColours(alignPanel, null);
2749 UserColourScheme udc = (UserColourScheme) UserDefinedColours.
2750 getUserColourSchemes().get(e.getActionCommand());
2756 public void updateUserColourMenu()
2759 Component[] menuItems = colourMenu.getMenuComponents();
2760 int i, iSize = menuItems.length;
2761 for (i = 0; i < iSize; i++)
2763 if (menuItems[i].getName() != null &&
2764 menuItems[i].getName().equals("USER_DEFINED"))
2766 colourMenu.remove(menuItems[i]);
2770 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2772 java.util.Enumeration userColours = jalview.gui.UserDefinedColours.
2773 getUserColourSchemes().keys();
2775 while (userColours.hasMoreElements())
2777 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2779 nextElement().toString());
2780 radioItem.setName("USER_DEFINED");
2781 radioItem.addMouseListener(new MouseAdapter()
2783 public void mousePressed(MouseEvent evt)
2785 if(evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
2787 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
2789 int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
2791 "Remove from default list?",
2792 "Remove user defined colour",
2793 JOptionPane.YES_NO_OPTION);
2794 if(option == JOptionPane.YES_OPTION)
2796 jalview.gui.UserDefinedColours.removeColourFromDefaults(
2797 radioItem.getText());
2798 colourMenu.remove(radioItem);
2802 radioItem.addActionListener(new ActionListener()
2804 public void actionPerformed(ActionEvent evt)
2806 userDefinedColour_actionPerformed(evt);
2813 radioItem.addActionListener(new ActionListener()
2815 public void actionPerformed(ActionEvent evt)
2817 userDefinedColour_actionPerformed(evt);
2821 colourMenu.insert(radioItem, 15);
2822 colours.add(radioItem);
2830 * @param e DOCUMENT ME!
2832 public void PIDColour_actionPerformed(ActionEvent e)
2834 changeColour(new PIDColourScheme());
2840 * @param e DOCUMENT ME!
2842 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2844 changeColour(new Blosum62ColourScheme());
2850 * @param e DOCUMENT ME!
2852 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2854 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2855 AlignmentSorter.sortByPID(viewport.getAlignment(),
2856 viewport.getAlignment().getSequenceAt(0));
2857 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2858 viewport.alignment));
2859 alignPanel.paintAlignment(true);
2865 * @param e DOCUMENT ME!
2867 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2869 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2870 AlignmentSorter.sortByID(viewport.getAlignment());
2871 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2872 alignPanel.paintAlignment(true);
2878 * @param e DOCUMENT ME!
2880 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2882 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2883 AlignmentSorter.sortByGroup(viewport.getAlignment());
2884 addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
2886 alignPanel.paintAlignment(true);
2891 * @param e DOCUMENT ME!
2893 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2895 new RedundancyPanel(alignPanel, this);
2902 * @param e DOCUMENT ME!
2904 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2906 if ( (viewport.getSelectionGroup() == null) ||
2907 (viewport.getSelectionGroup().getSize() < 2))
2909 JOptionPane.showInternalMessageDialog(this,
2910 "You must select at least 2 sequences.",
2911 "Invalid Selection",
2912 JOptionPane.WARNING_MESSAGE);
2916 JInternalFrame frame = new JInternalFrame();
2917 frame.setContentPane(new PairwiseAlignPanel(viewport));
2918 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2925 * @param e DOCUMENT ME!
2927 public void PCAMenuItem_actionPerformed(ActionEvent e)
2929 if ( ( (viewport.getSelectionGroup() != null) &&
2930 (viewport.getSelectionGroup().getSize() < 4) &&
2931 (viewport.getSelectionGroup().getSize() > 0)) ||
2932 (viewport.getAlignment().getHeight() < 4))
2934 JOptionPane.showInternalMessageDialog(this,
2935 "Principal component analysis must take\n" +
2936 "at least 4 input sequences.",
2937 "Sequence selection insufficient",
2938 JOptionPane.WARNING_MESSAGE);
2943 new PCAPanel(alignPanel);
2947 public void autoCalculate_actionPerformed(ActionEvent e)
2949 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2950 if(viewport.autoCalculateConsensus)
2952 viewport.firePropertyChange("alignment",
2954 viewport.getAlignment().getSequences());
2962 * @param e DOCUMENT ME!
2964 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2966 NewTreePanel("AV", "PID", "Average distance tree using PID");
2972 * @param e DOCUMENT ME!
2974 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
2976 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
2982 * @param e DOCUMENT ME!
2984 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2986 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
2992 * @param e DOCUMENT ME!
2994 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2996 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3002 * @param type DOCUMENT ME!
3003 * @param pwType DOCUMENT ME!
3004 * @param title DOCUMENT ME!
3006 void NewTreePanel(String type, String pwType, String title)
3010 if (viewport.getSelectionGroup() != null)
3012 if (viewport.getSelectionGroup().getSize() < 3)
3014 JOptionPane.showMessageDialog(Desktop.desktop,
3015 "You need to have more than two sequences selected to build a tree!",
3016 "Not enough sequences",
3017 JOptionPane.WARNING_MESSAGE);
3022 SequenceGroup sg = viewport.getSelectionGroup();
3024 /* Decide if the selection is a column region */
3025 while (s < sg.getSize())
3027 if ( ( (SequenceI) sg.getSequences(null).elementAt(s++)).getLength() <
3030 JOptionPane.showMessageDialog(Desktop.desktop,
3031 "The selected region to create a tree may\nonly contain residues or gaps.\n" +
3032 "Try using the Pad function in the edit menu,\n" +
3033 "or one of the multiple sequence alignment web services.",
3034 "Sequences in selection are not aligned",
3035 JOptionPane.WARNING_MESSAGE);
3041 title = title + " on region";
3042 tp = new TreePanel(alignPanel, type, pwType);
3046 //are the sequences aligned?
3047 if (!viewport.alignment.isAligned())
3049 JOptionPane.showMessageDialog(Desktop.desktop,
3050 "The sequences must be aligned before creating a tree.\n" +
3051 "Try using the Pad function in the edit menu,\n" +
3052 "or one of the multiple sequence alignment web services.",
3053 "Sequences not aligned",
3054 JOptionPane.WARNING_MESSAGE);
3059 if(viewport.alignment.getHeight()<2)
3064 tp = new TreePanel(alignPanel, type, pwType);
3069 if(viewport.viewName!=null)
3071 title+= viewport.viewName+" of ";
3074 title += this.title;
3076 Desktop.addInternalFrame(tp, title, 600, 500);
3082 * @param title DOCUMENT ME!
3083 * @param order DOCUMENT ME!
3085 public void addSortByOrderMenuItem(String title, final AlignmentOrder order)
3087 final JMenuItem item = new JMenuItem("by " + title);
3089 item.addActionListener(new java.awt.event.ActionListener()
3091 public void actionPerformed(ActionEvent e)
3093 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3095 // TODO: JBPNote - have to map order entries to curent SequenceI pointers
3096 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3098 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3099 viewport.alignment));
3101 alignPanel.paintAlignment(true);
3106 * Add a new sort by annotation score menu item
3107 * @param sort the menu to add the option to
3108 * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
3110 public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
3112 final JMenuItem item = new JMenuItem(scoreLabel);
3114 item.addActionListener(new java.awt.event.ActionListener()
3116 public void actionPerformed(ActionEvent e)
3118 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3119 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());
3120 addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
3121 alignPanel.paintAlignment(true);
3126 * last hash for alignment's annotation array - used to minimise cost of rebuild.
3128 protected int _annotationScoreVectorHash;
3130 * search the alignment and rebuild the sort by annotation score submenu
3131 * the last alignment annotation vector hash is stored to minimize
3132 * cost of rebuilding in subsequence calls.
3135 public void buildSortByAnnotationScoresMenu()
3137 if(viewport.alignment.getAlignmentAnnotation()==null)
3142 if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
3144 sortByAnnotScore.removeAll();
3145 // almost certainly a quicker way to do this - but we keep it simple
3146 Hashtable scoreSorts=new Hashtable();
3147 AlignmentAnnotation aann[];
3148 Enumeration sq = viewport.alignment.getSequences().elements();
3149 while (sq.hasMoreElements())
3151 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3152 for (int i=0;aann!=null && i<aann.length; i++)
3154 if (aann[i].hasScore() && aann[i].sequenceRef!=null)
3156 scoreSorts.put(aann[i].label, aann[i].label);
3160 Enumeration labels = scoreSorts.keys();
3161 while (labels.hasMoreElements())
3163 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
3165 sortByAnnotScore.setVisible(scoreSorts.size()>0);
3168 _annotationScoreVectorHash =
3169 viewport.alignment.getAlignmentAnnotation().hashCode();
3174 * Maintain the Order by->Displayed Tree menu.
3175 * Creates a new menu item for a TreePanel with an appropriate
3176 * <code>jalview.analysis.AlignmentSorter</code> call. Listeners are added
3177 * to remove the menu item when the treePanel is closed, and adjust
3178 * the tree leaf to sequence mapping when the alignment is modified.
3179 * @param treePanel Displayed tree window.
3180 * @param title SortBy menu item title.
3182 public void buildTreeMenu()
3184 sortByTreeMenu.removeAll();
3186 Vector comps = (Vector) PaintRefresher.components.get(viewport.
3187 getSequenceSetId());
3188 Vector treePanels = new Vector();
3189 int i, iSize = comps.size();
3190 for(i=0; i<iSize; i++)
3192 if(comps.elementAt(i) instanceof TreePanel)
3194 treePanels.add(comps.elementAt(i));
3198 iSize = treePanels.size();
3202 sortByTreeMenu.setVisible(false);
3206 sortByTreeMenu.setVisible(true);
3208 for(i=0; i<treePanels.size(); i++)
3210 TreePanel tp = (TreePanel)treePanels.elementAt(i);
3211 final JMenuItem item = new JMenuItem(tp.getTitle());
3212 final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
3213 item.addActionListener(new java.awt.event.ActionListener()
3215 public void actionPerformed(ActionEvent e)
3217 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3218 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3220 addHistoryItem(new OrderCommand("Tree Sort",
3222 viewport.alignment));
3224 alignPanel.paintAlignment(true);
3228 sortByTreeMenu.add(item);
3233 * Work out whether the whole set of sequences
3234 * or just the selected set will be submitted for multiple alignment.
3237 private jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3239 // Now, check we have enough sequences
3240 AlignmentView msa = null;
3242 if ( (viewport.getSelectionGroup() != null) &&
3243 (viewport.getSelectionGroup().getSize() > 1))
3245 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
3246 /*SequenceGroup seqs = viewport.getSelectionGroup();
3248 msa = new SequenceI[sz = seqs.getSize(false)];
3250 for (int i = 0; i < sz; i++)
3252 msa[i] = (SequenceI) seqs.getSequenceAt(i);
3254 msa = viewport.getAlignmentView(true);
3258 /*Vector seqs = viewport.getAlignment().getSequences();
3260 if (seqs.size() > 1)
3262 msa = new SequenceI[seqs.size()];
3264 for (int i = 0; i < seqs.size(); i++)
3266 msa[i] = (SequenceI) seqs.elementAt(i);
3269 msa = viewport.getAlignmentView(false);
3275 * Decides what is submitted to a secondary structure prediction service,
3276 * the currently selected sequence, or the currently selected alignment
3277 * (where the first sequence in the set is the one that the prediction
3280 AlignmentView gatherSeqOrMsaForSecStrPrediction()
3282 AlignmentView seqs = null;
3284 if ( (viewport.getSelectionGroup() != null) &&
3285 (viewport.getSelectionGroup().getSize() > 0))
3287 seqs = viewport.getAlignmentView(true);
3291 seqs = viewport.getAlignmentView(false);
3293 // limit sequences - JBPNote in future - could spawn multiple prediction jobs
3294 // TODO: viewport.alignment.isAligned is a global state - the local selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3295 if (!viewport.alignment.isAligned())
3297 seqs.setSequences(new SeqCigar[]
3298 {seqs.getSequences()[0]});
3305 * @param e DOCUMENT ME!
3307 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3309 // Pick the tree file
3310 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3313 chooser.setFileView(new JalviewFileView());
3314 chooser.setDialogTitle("Select a newick-like tree file");
3315 chooser.setToolTipText("Load a tree file");
3317 int value = chooser.showOpenDialog(null);
3319 if (value == JalviewFileChooser.APPROVE_OPTION)
3321 String choice = chooser.getSelectedFile().getPath();
3322 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3326 jalview.io.NewickFile fin = new jalview.io.NewickFile(choice,
3328 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3330 catch (Exception ex)
3332 JOptionPane.showMessageDialog(Desktop.desktop,
3333 "Problem reading tree file",
3335 JOptionPane.WARNING_MESSAGE);
3336 ex.printStackTrace();
3342 public TreePanel ShowNewickTree(NewickFile nf, String title)
3344 return ShowNewickTree(nf,title,600,500,4,5);
3347 public TreePanel ShowNewickTree(NewickFile nf, String title,
3348 AlignmentView input)
3350 return ShowNewickTree(nf,title, input, 600,500,4,5);
3353 public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
3356 return ShowNewickTree(nf, title, null, w, h, x, y);
3359 * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
3361 * @param nf the tree
3362 * @param title tree viewer title
3363 * @param input Associated alignment input data (or null)
3368 * @return TreePanel handle
3370 public TreePanel ShowNewickTree(NewickFile nf, String title,
3371 AlignmentView input, int w, int h, int x,
3374 TreePanel tp = null;
3380 if (nf.getTree() != null)
3382 tp = new TreePanel(alignPanel,
3391 tp.setLocation(x,y);
3395 Desktop.addInternalFrame(tp, title, w, h);
3398 catch (Exception ex)
3400 ex.printStackTrace();
3408 * Generates menu items and listener event actions for web service clients
3411 public void BuildWebServiceMenu()
3413 if ( (Discoverer.services != null)
3414 && (Discoverer.services.size() > 0))
3416 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3417 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3418 Vector wsmenu = new Vector();
3419 final AlignFrame af = this;
3422 // Add any Multiple Sequence Alignment Services
3423 final JMenu msawsmenu = new JMenu("Alignment");
3424 for (int i = 0, j = msaws.size(); i < j; i++)
3426 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws.
3428 final JMenuItem method = new JMenuItem(sh.getName());
3429 method.addActionListener(new ActionListener()
3431 public void actionPerformed(ActionEvent e)
3433 AlignmentView msa = gatherSequencesForAlignment();
3434 new jalview.ws.MsaWSClient(sh, title, msa,
3436 viewport.getAlignment().getDataset(),
3442 msawsmenu.add(method);
3443 // Deal with services that we know accept partial alignments.
3444 if (sh.getName().indexOf("lustal") > -1)
3446 // We know that ClustalWS can accept partial alignments for refinement.
3447 final JMenuItem methodR = new JMenuItem(sh.getName()+" Realign");
3448 methodR.addActionListener(new ActionListener()
3450 public void actionPerformed(ActionEvent e)
3452 AlignmentView msa = gatherSequencesForAlignment();
3453 new jalview.ws.MsaWSClient(sh, title, msa,
3455 viewport.getAlignment().getDataset(),
3461 msawsmenu.add(methodR);
3465 wsmenu.add(msawsmenu);
3467 if (secstrpr != null)
3469 // Add any secondary structure prediction services
3470 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3471 for (int i = 0, j = secstrpr.size(); i < j; i++)
3473 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle)
3475 final JMenuItem method = new JMenuItem(sh.getName());
3476 method.addActionListener(new ActionListener()
3478 public void actionPerformed(ActionEvent e)
3480 AlignmentView msa = gatherSeqOrMsaForSecStrPrediction();
3481 if (msa.getSequences().length == 1)
3483 // Single Sequence prediction
3484 new jalview.ws.JPredClient(sh, title, false, msa, af, true);
3488 if (msa.getSequences().length > 1)
3490 // Sequence profile based prediction
3491 new jalview.ws.JPredClient(sh,
3492 title, true, msa, af, true);
3497 secstrmenu.add(method);
3499 wsmenu.add(secstrmenu);
3501 resetWebServiceMenu();
3502 for (int i = 0, j = wsmenu.size(); i < j; i++)
3504 webService.add( (JMenu) wsmenu.get(i));
3509 resetWebServiceMenu();
3510 this.webService.add(this.webServiceNoServices);
3512 // TODO: add in rediscovery function
3513 // TODO: reduce code redundancy.
3514 // TODO: group services by location as well as function.
3519 * empty the web service menu and add any ad-hoc functions
3520 * not dynamically discovered.
3523 private void resetWebServiceMenu()
3525 webService.removeAll();
3526 // Temporary hack - DBRef Fetcher always top level ws entry.
3527 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3528 rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
3529 webService.add(rfetch);
3530 rfetch.addActionListener(new ActionListener() {
3532 public void actionPerformed(ActionEvent e)
3534 new jalview.ws.DBRefFetcher(
3535 alignPanel.av.getSequenceSelection(),
3536 alignPanel.alignFrame).fetchDBRefs(false);
3542 /* public void vamsasStore_actionPerformed(ActionEvent e)
3544 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3545 getProperty("LAST_DIRECTORY"));
3547 chooser.setFileView(new JalviewFileView());
3548 chooser.setDialogTitle("Export to Vamsas file");
3549 chooser.setToolTipText("Export");
3551 int value = chooser.showSaveDialog(this);
3553 if (value == JalviewFileChooser.APPROVE_OPTION)
3555 jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3556 //vs.store(chooser.getSelectedFile().getAbsolutePath() );
3557 vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
3561 * prototype of an automatically enabled/disabled analysis function
3564 protected void setShowProductsEnabled()
3566 SequenceI [] selection = viewport.getSequenceSelection();
3567 if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
3569 showProducts.setEnabled(true);
3572 showProducts.setEnabled(false);
3576 * search selection for sequence xRef products and build the
3577 * show products menu.
3580 * @return true if showProducts menu should be enabled.
3582 public boolean canShowProducts(SequenceI[] selection, boolean isRegionSelection, Alignment dataset)
3584 boolean showp=false;
3586 showProducts.removeAll();
3587 final boolean dna = viewport.getAlignment().isNucleotide();
3588 final Alignment ds = dataset;
3589 String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection, dataset);
3590 //Object[] prods = CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(), selection, dataset, true);
3591 final SequenceI[] sel = selection;
3592 for (int t=0; ptypes!=null && t<ptypes.length; t++)
3595 final boolean isRegSel = isRegionSelection;
3596 final AlignFrame af = this;
3597 final String source = ptypes[t];
3598 JMenuItem xtype = new JMenuItem(ptypes[t]);
3599 xtype.addActionListener(new ActionListener() {
3601 public void actionPerformed(ActionEvent e)
3603 af.showProductsFor(sel, ds, isRegSel, dna, source);
3607 showProducts.add(xtype);
3609 showProducts.setVisible(showp);
3610 showProducts.setEnabled(showp);
3611 } catch (Exception e)
3613 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3618 protected void showProductsFor(SequenceI[] sel, Alignment ds, boolean isRegSel, boolean dna, String source)
3620 Alignment prods = CrossRef.findXrefSequences(sel, dna, source, ds);
3623 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3624 for (int s=0; s<sprods.length;s++)
3626 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3627 if (!ds.getSequences().contains(sprods[s].getDatasetSequence()))
3628 ds.addSequence(sprods[s].getDatasetSequence());
3630 Alignment al = new Alignment(sprods);
3631 AlignedCodonFrame[] cf = prods.getCodonFrames();
3632 for (int s=0; cf!=null && s<cf.length; s++)
3634 al.addCodonFrame(cf[s]);
3638 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3639 String newtitle =""+((dna) ? "Proteins " : "Nucleotides ") + " for "+((isRegSel) ? "selected region of " : "")
3641 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3644 System.err.println("No Sequences generated for xRef type "+source);
3649 public boolean canShowTranslationProducts(SequenceI[] selection, AlignmentI alignment)
3653 return (jalview.analysis.Dna.canTranslate(selection, viewport.getViewAsVisibleContigs(true)));
3654 } catch (Exception e)
3656 jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
3661 public void showProducts_actionPerformed(ActionEvent e)
3663 ///////////////////////////////
3664 // Collect Data to be translated/transferred
3666 SequenceI [] selection = viewport.getSequenceSelection();
3667 AlignmentI al = null;
3669 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport.getViewAsVisibleContigs(true),
3670 viewport.getGapCharacter(), viewport.getAlignment().getDataset());
3671 } catch (Exception ex) {
3673 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3677 JOptionPane.showMessageDialog(Desktop.desktop,
3678 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3679 "Translation Failed",
3680 JOptionPane.WARNING_MESSAGE);
3682 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3683 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3689 public void showTranslation_actionPerformed(ActionEvent e)
3691 ///////////////////////////////
3692 // Collect Data to be translated/transferred
3694 SequenceI [] selection = viewport.getSequenceSelection();
3695 String [] seqstring = viewport.getViewAsString(true);
3696 AlignmentI al = null;
3698 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
3699 viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
3700 viewport.alignment.getWidth(), viewport.getAlignment().getDataset());
3701 } catch (Exception ex) {
3703 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3707 JOptionPane.showMessageDialog(Desktop.desktop,
3708 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3709 "Translation Failed",
3710 JOptionPane.WARNING_MESSAGE);
3712 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3713 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3722 * @param String DOCUMENT ME!
3724 public boolean parseFeaturesFile(String file, String type)
3726 boolean featuresFile = false;
3729 featuresFile = new FeaturesFile(file,
3730 type).parse(viewport.alignment.getDataset(),
3731 alignPanel.seqPanel.seqCanvas.
3732 getFeatureRenderer().featureColours,
3737 ex.printStackTrace();
3742 viewport.showSequenceFeatures = true;
3743 showSeqFeatures.setSelected(true);
3744 alignPanel.paintAlignment(true);
3747 return featuresFile;
3750 public void dragEnter(DropTargetDragEvent evt)
3753 public void dragExit(DropTargetEvent evt)
3756 public void dragOver(DropTargetDragEvent evt)
3759 public void dropActionChanged(DropTargetDragEvent evt)
3762 public void drop(DropTargetDropEvent evt)
3764 Transferable t = evt.getTransferable();
3765 java.util.List files = null;
3769 DataFlavor uriListFlavor = new DataFlavor(
3770 "text/uri-list;class=java.lang.String");
3771 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3773 //Works on Windows and MacOSX
3774 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3775 files = (java.util.List) t.getTransferData(DataFlavor.
3776 javaFileListFlavor);
3778 else if (t.isDataFlavorSupported(uriListFlavor))
3780 // This is used by Unix drag system
3781 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3782 String data = (String) t.getTransferData(uriListFlavor);
3783 files = new java.util.ArrayList(1);
3784 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3787 st.hasMoreTokens(); )
3789 String s = st.nextToken();
3790 if (s.startsWith("#"))
3792 // the line is a comment (as per the RFC 2483)
3796 java.net.URI uri = new java.net.URI(s);
3797 java.io.File file = new java.io.File(uri);
3804 e.printStackTrace();
3811 for (int i = 0; i < files.size(); i++)
3813 loadJalviewDataFile(files.get(i).toString());
3816 catch (Exception ex)
3818 ex.printStackTrace();
3823 // This method will attempt to load a "dropped" file first by testing
3824 // whether its and Annotation file, then features file. If both are
3825 // false then the user may have dropped an alignment file onto this
3827 public void loadJalviewDataFile(String file)
3831 String protocol = "File";
3833 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3838 boolean isAnnotation = new AnnotationFile().readAnnotationFile(viewport.
3839 alignment, file, protocol);
3843 boolean isGroupsFile = parseFeaturesFile(file,protocol);
3846 String format = new IdentifyFile().Identify(file, protocol);
3848 if(format.equalsIgnoreCase("JnetFile"))
3850 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
3852 new JnetAnnotationMaker().add_annotation(predictions,
3853 viewport.getAlignment(),
3855 alignPanel.adjustAnnotationHeight();
3856 alignPanel.paintAlignment(true);
3860 new FileLoader().LoadFile(viewport, file, protocol, format);
3867 alignPanel.adjustAnnotationHeight();
3868 buildSortByAnnotationScoresMenu();
3872 catch (Exception ex)
3874 ex.printStackTrace();
3878 public void tabSelectionChanged(int index)
3882 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
3883 viewport = alignPanel.av;
3884 setMenusFromViewport(viewport);
3888 public void tabbedPane_mousePressed(MouseEvent e)
3890 if(SwingUtilities.isRightMouseButton(e))
3892 String reply = JOptionPane.showInternalInputDialog(this,
3895 JOptionPane.QUESTION_MESSAGE);
3899 viewport.viewName = reply;
3900 tabbedPane.setTitleAt( tabbedPane.getSelectedIndex() ,reply);
3906 public AlignViewport getCurrentView()
3913 * Open the dialog for regex description parsing.
3915 protected void extractScores_actionPerformed(ActionEvent e)
3917 ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
3918 if (pp.getScoresFromDescription("col", "score column ", "\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)")>0)
3920 buildSortByAnnotationScoresMenu();
3929 public PrintThread(AlignmentPanel ap)
3933 static PageFormat pf;
3936 PrinterJob printJob = PrinterJob.getPrinterJob();
3940 printJob.setPrintable(ap, pf);
3944 printJob.setPrintable(ap);
3947 if (printJob.printDialog())
3953 catch (Exception PrintException)
3955 PrintException.printStackTrace();