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);
510 * Need to call this method when tabs are selected for multiple views,
511 * or when loading from Jalview2XML.java
512 * @param av AlignViewport
514 void setMenusFromViewport(AlignViewport av)
516 padGapsMenuitem.setSelected(av.padGaps);
517 colourTextMenuItem.setSelected(av.showColourText);
518 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
519 conservationMenuItem.setSelected(av.getConservationSelected());
520 seqLimits.setSelected(av.getShowJVSuffix());
521 idRightAlign.setSelected(av.rightAlignIds);
522 renderGapsMenuItem.setSelected(av.renderGaps);
523 wrapMenuItem.setSelected(av.wrapAlignment);
524 scaleAbove.setVisible(av.wrapAlignment);
525 scaleLeft.setVisible(av.wrapAlignment);
526 scaleRight.setVisible(av.wrapAlignment);
527 annotationPanelMenuItem.setState(av.showAnnotation);
528 viewBoxesMenuItem.setSelected(av.showBoxes);
529 viewTextMenuItem.setSelected(av.showText);
531 setColourSelected(ColourSchemeProperty.
532 getColourName(av.getGlobalColourScheme()));
534 showSeqFeatures.setSelected(av.showSequenceFeatures);
535 hiddenMarkers.setState(av.showHiddenMarkers);
536 applyToAllGroups.setState(av.colourAppliesToAllGroups);
542 Hashtable progressBars;
543 public void setProgressBar(String message, long id)
545 if(progressBars == null)
547 progressBars = new Hashtable();
550 JPanel progressPanel;
551 GridLayout layout = (GridLayout) statusPanel.getLayout();
552 if(progressBars.get( new Long(id) )!=null)
554 progressPanel = (JPanel)progressBars.get( new Long(id) );
555 statusPanel.remove(progressPanel);
556 progressBars.remove( progressPanel );
557 progressPanel = null;
560 statusBar.setText(message);
563 layout.setRows(layout.getRows() - 1);
567 progressPanel = new JPanel(new BorderLayout(10, 5));
569 JProgressBar progressBar = new JProgressBar();
570 progressBar.setIndeterminate(true);
572 progressPanel.add(new JLabel(message), BorderLayout.WEST);
573 progressPanel.add(progressBar, BorderLayout.CENTER);
575 layout.setRows(layout.getRows() + 1);
576 statusPanel.add(progressPanel);
578 progressBars.put(new Long(id), progressPanel);
588 Added so Castor Mapping file can obtain Jalview Version
590 public String getVersion()
592 return jalview.bin.Cache.getProperty("VERSION");
595 public FeatureRenderer getFeatureRenderer()
597 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
601 public void fetchSequence_actionPerformed(ActionEvent e)
603 new SequenceFetcher(this);
606 public void addFromFile_actionPerformed(ActionEvent e)
608 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
611 public void reload_actionPerformed(ActionEvent e)
615 if(currentFileFormat.equals("Jalview"))
617 JInternalFrame [] frames = Desktop.desktop.getAllFrames();
618 for(int i=0; i<frames.length; i++)
620 if (frames[i] instanceof AlignFrame
622 && ( (AlignFrame) frames[i]).fileName.equals(fileName))
626 frames[i].setSelected(true);
627 Desktop.instance.closeAssociatedWindows();
629 catch (java.beans.PropertyVetoException ex)
634 Desktop.instance.closeAssociatedWindows();
636 FileLoader loader = new FileLoader();
637 String protocol = fileName.startsWith("http:")? "URL":"File";
638 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
642 Rectangle bounds = this.getBounds();
644 FileLoader loader = new FileLoader();
645 String protocol = fileName.startsWith("http:") ? "URL" : "File";
646 AlignFrame newframe =
647 loader.LoadFileWaitTillLoaded(fileName, protocol, currentFileFormat);
649 newframe.setBounds(bounds);
651 this.closeMenuItem_actionPerformed(true);
657 public void addFromText_actionPerformed(ActionEvent e)
659 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
662 public void addFromURL_actionPerformed(ActionEvent e)
664 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
668 public void save_actionPerformed(ActionEvent e)
671 || currentFileFormat==null
672 || fileName.startsWith("http")
675 saveAs_actionPerformed(null);
679 saveAlignment(fileName, currentFileFormat);
686 * @param e DOCUMENT ME!
688 public void saveAs_actionPerformed(ActionEvent e)
690 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
691 getProperty( "LAST_DIRECTORY"),
693 { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","jar" },
695 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "Jalview" },
700 chooser.setFileView(new JalviewFileView());
701 chooser.setDialogTitle("Save Alignment to file");
702 chooser.setToolTipText("Save");
704 int value = chooser.showSaveDialog(this);
706 if (value == JalviewFileChooser.APPROVE_OPTION)
708 currentFileFormat = chooser.getSelectedFormat();
709 if (currentFileFormat == null)
711 JOptionPane.showInternalMessageDialog(Desktop.desktop,
712 "You must select a file format before saving!",
713 "File format not specified",
714 JOptionPane.WARNING_MESSAGE);
715 value = chooser.showSaveDialog(this);
719 fileName = chooser.getSelectedFile().getPath();
721 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
724 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
726 saveAlignment(fileName, currentFileFormat);
730 public boolean saveAlignment(String file, String format)
732 boolean success = true;
734 if (format.equalsIgnoreCase("Jalview"))
736 String shortName = title;
738 if (shortName.indexOf(java.io.File.separatorChar) > -1)
740 shortName = shortName.substring(shortName.lastIndexOf(
741 java.io.File.separatorChar) + 1);
744 success = new Jalview2XML().SaveAlignment(this, file, shortName);
746 statusBar.setText("Successfully saved to file: "
748 +format +" format.");
754 String[] omitHidden = null;
756 if (viewport.hasHiddenColumns)
758 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
759 "The Alignment contains hidden columns."
760 + "\nDo you want to save only the visible alignment?",
761 "Save / Omit Hidden Columns",
762 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
764 if (reply == JOptionPane.YES_OPTION)
766 omitHidden = viewport.getViewAsString(false);
770 String output = new FormatAdapter().formatSequences(
772 viewport.alignment.getSequencesArray(),
783 java.io.PrintWriter out = new java.io.PrintWriter(
784 new java.io.FileWriter(file));
789 statusBar.setText("Successfully saved to file: "
791 + format + " format.");
796 ex.printStackTrace();
803 JOptionPane.showInternalMessageDialog(
804 this, "Couldn't save file: " + fileName,
806 JOptionPane.WARNING_MESSAGE);
815 * @param e DOCUMENT ME!
817 protected void outputText_actionPerformed(ActionEvent e)
819 String [] omitHidden = null;
821 if(viewport.hasHiddenColumns)
823 int reply = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
824 "The Alignment contains hidden columns."
825 +"\nDo you want to output only the visible alignment?",
826 "Save / Omit Hidden Columns",
827 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
829 if(reply==JOptionPane.YES_OPTION)
831 omitHidden = viewport.getViewAsString(false);
835 CutAndPasteTransfer cap = new CutAndPasteTransfer();
836 cap.setForInput(null);
837 Desktop.addInternalFrame(cap,
838 "Alignment output - " + e.getActionCommand(), 600,
842 cap.setText(new FormatAdapter().formatSequences(
843 e.getActionCommand(),
844 viewport.alignment.getSequencesArray(),
851 * @param e DOCUMENT ME!
853 protected void htmlMenuItem_actionPerformed(ActionEvent e)
855 new HTMLOutput(alignPanel,
856 alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
857 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
860 public void createImageMap(File file, String image)
862 alignPanel.makePNGImageMap(file, image);
868 * @param e DOCUMENT ME!
870 public void createPNG(File f)
872 alignPanel.makePNG(f);
878 * @param e DOCUMENT ME!
880 public void createEPS(File f)
882 alignPanel.makeEPS(f);
886 public void pageSetup_actionPerformed(ActionEvent e)
888 PrinterJob printJob = PrinterJob.getPrinterJob();
889 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
895 * @param e DOCUMENT ME!
897 public void printMenuItem_actionPerformed(ActionEvent e)
899 //Putting in a thread avoids Swing painting problems
900 PrintThread thread = new PrintThread(alignPanel);
904 public void exportFeatures_actionPerformed(ActionEvent e)
906 new AnnotationExporter().exportFeatures(alignPanel);
910 public void exportAnnotations_actionPerformed(ActionEvent e)
912 new AnnotationExporter().exportAnnotations(
914 viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
915 viewport.alignment.getGroups(),
916 ((Alignment)viewport.alignment).alignmentProperties
921 public void associatedData_actionPerformed(ActionEvent e)
923 // Pick the tree file
924 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
927 chooser.setFileView(new JalviewFileView());
928 chooser.setDialogTitle("Load Jalview Annotations or Features File");
929 chooser.setToolTipText("Load Jalview Annotations / Features file");
931 int value = chooser.showOpenDialog(null);
933 if (value == JalviewFileChooser.APPROVE_OPTION)
935 String choice = chooser.getSelectedFile().getPath();
936 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
937 loadJalviewDataFile(choice);
946 * @param e DOCUMENT ME!
948 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
950 if(alignPanels!=null && alignPanels.size()<2)
957 if(alignPanels!=null)
961 for (int i = 0; i < alignPanels.size(); i++)
963 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
964 jalview.structure.StructureSelectionManager.getStructureSelectionManager()
965 .removeStructureViewerListener(ap.seqPanel, null);
966 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
967 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
968 PaintRefresher.RemoveComponent(ap);
969 ap.av.alignment = null;
974 int index = tabbedPane.getSelectedIndex();
976 alignPanels.removeElement(alignPanel);
977 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
978 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
979 PaintRefresher.RemoveComponent(alignPanel);
980 viewport.alignment = null;
984 tabbedPane.removeTabAt(index);
985 tabbedPane.validate();
987 if(index==tabbedPane.getTabCount())
992 this.tabSelectionChanged(index);
998 this.setClosed(true);
1001 catch (Exception ex)
1003 ex.printStackTrace();
1011 void updateEditMenuBar()
1014 if (viewport.historyList.size() > 0)
1016 undoMenuItem.setEnabled(true);
1017 CommandI command = (CommandI) viewport.historyList.peek();
1018 undoMenuItem.setText("Undo " + command.getDescription());
1022 undoMenuItem.setEnabled(false);
1023 undoMenuItem.setText("Undo");
1026 if (viewport.redoList.size() > 0)
1028 redoMenuItem.setEnabled(true);
1030 CommandI command = (CommandI) viewport.redoList.peek();
1031 redoMenuItem.setText("Redo " + command.getDescription());
1035 redoMenuItem.setEnabled(false);
1036 redoMenuItem.setText("Redo");
1041 public void addHistoryItem(CommandI command)
1043 if(command.getSize()>0)
1045 viewport.historyList.push(command);
1046 viewport.redoList.clear();
1047 updateEditMenuBar();
1048 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1054 * @return alignment objects for all views
1056 AlignmentI[] getViewAlignments()
1058 if (alignPanels!=null)
1060 Enumeration e = alignPanels.elements();
1061 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1062 for (int i=0; e.hasMoreElements(); i++)
1064 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1070 return new AlignmentI[] { viewport.alignment };
1077 * @param e DOCUMENT ME!
1079 protected void undoMenuItem_actionPerformed(ActionEvent e)
1081 if (viewport.historyList.empty())
1083 CommandI command = (CommandI)viewport.historyList.pop();
1084 viewport.redoList.push(command);
1085 command.undoCommand(getViewAlignments());
1087 AlignViewport originalSource = getOriginatingSource(command);
1088 updateEditMenuBar();
1090 if(originalSource!=null)
1092 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1093 originalSource.firePropertyChange("alignment",
1095 originalSource.alignment.getSequences());
1102 * @param e DOCUMENT ME!
1104 protected void redoMenuItem_actionPerformed(ActionEvent e)
1106 if(viewport.redoList.size()<1)
1111 CommandI command = (CommandI) viewport.redoList.pop();
1112 viewport.historyList.push(command);
1113 command.doCommand(getViewAlignments());
1115 AlignViewport originalSource = getOriginatingSource(command);
1116 updateEditMenuBar();
1118 if(originalSource!=null)
1120 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1121 originalSource.firePropertyChange("alignment",
1123 originalSource.alignment.getSequences());
1127 AlignViewport getOriginatingSource(CommandI command)
1129 AlignViewport originalSource = null;
1130 //For sequence removal and addition, we need to fire
1131 //the property change event FROM the viewport where the
1132 //original alignment was altered
1134 if (command instanceof EditCommand)
1136 EditCommand editCommand = (EditCommand) command;
1137 al = editCommand.getAlignment();
1138 Vector comps = (Vector) PaintRefresher.components
1139 .get(viewport.getSequenceSetId());
1141 for (int i = 0; i < comps.size(); i++)
1143 if (comps.elementAt(i) instanceof AlignmentPanel)
1145 if (al == ( (AlignmentPanel) comps.elementAt(i)).av.alignment)
1147 originalSource = ( (AlignmentPanel) comps.elementAt(i)).av;
1154 if (originalSource == null)
1156 //The original view is closed, we must validate
1157 //the current view against the closed view first
1160 PaintRefresher.validateSequences(al, viewport.alignment);
1163 originalSource = viewport;
1166 return originalSource;
1172 * @param up DOCUMENT ME!
1174 public void moveSelectedSequences(boolean up)
1176 SequenceGroup sg = viewport.getSelectionGroup();
1185 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1187 SequenceI seq = viewport.alignment.getSequenceAt(i);
1189 if (!sg.getSequences(null).contains(seq))
1194 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1196 if (sg.getSequences(null).contains(temp))
1201 viewport.alignment.getSequences().setElementAt(temp, i);
1202 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1207 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1209 SequenceI seq = viewport.alignment.getSequenceAt(i);
1211 if (!sg.getSequences(null).contains(seq))
1216 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1218 if (sg.getSequences(null).contains(temp))
1223 viewport.alignment.getSequences().setElementAt(temp, i);
1224 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1228 alignPanel.paintAlignment(true);
1234 synchronized void slideSequences(boolean right, int size)
1236 Vector sg = new Vector();
1237 if(viewport.cursorMode)
1239 sg.addElement(viewport.alignment.getSequenceAt(
1240 alignPanel.seqPanel.seqCanvas.cursorY));
1242 else if(viewport.getSelectionGroup()!=null
1243 && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
1245 sg = viewport.getSelectionGroup().getSequences(
1246 viewport.hiddenRepSequences);
1254 Vector invertGroup = new Vector();
1256 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1258 if(!sg.contains(viewport.alignment.getSequenceAt(i)))
1259 invertGroup.add(viewport.alignment.getSequenceAt(i));
1262 SequenceI[] seqs1 = new SequenceI[sg.size()];
1263 for (int i = 0; i < sg.size(); i++)
1264 seqs1[i] = (SequenceI) sg.elementAt(i);
1266 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1267 for (int i = 0; i < invertGroup.size(); i++)
1268 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1270 SlideSequencesCommand ssc;
1272 ssc = new SlideSequencesCommand("Slide Sequences",
1274 viewport.getGapCharacter()
1277 ssc = new SlideSequencesCommand("Slide Sequences",
1279 viewport.getGapCharacter()
1282 int groupAdjustment = 0;
1283 if (ssc.getGapsInsertedBegin() && right)
1285 if (viewport.cursorMode)
1286 alignPanel.seqPanel.moveCursor(size, 0);
1288 groupAdjustment = size;
1290 else if (!ssc.getGapsInsertedBegin() && !right)
1292 if (viewport.cursorMode)
1293 alignPanel.seqPanel.moveCursor( -size, 0);
1295 groupAdjustment = -size;
1298 if (groupAdjustment != 0)
1300 viewport.getSelectionGroup().setStartRes(
1301 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1302 viewport.getSelectionGroup().setEndRes(
1303 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1307 boolean appendHistoryItem = false;
1308 if(viewport.historyList!=null
1309 && viewport.historyList.size()>0
1310 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1312 appendHistoryItem = ssc.appendSlideCommand(
1313 (SlideSequencesCommand)viewport.historyList.peek())
1317 if(!appendHistoryItem)
1318 addHistoryItem(ssc);
1327 * @param e DOCUMENT ME!
1329 protected void copy_actionPerformed(ActionEvent e)
1332 if (viewport.getSelectionGroup() == null)
1336 // TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
1337 SequenceI [] seqs = viewport.getSelectionAsNewSequence();
1338 String[] omitHidden = null;
1340 if (viewport.hasHiddenColumns)
1342 omitHidden = viewport.getViewAsString(true);
1345 String output = new FormatAdapter().formatSequences(
1350 StringSelection ss = new StringSelection(output);
1354 jalview.gui.Desktop.internalCopy = true;
1355 //Its really worth setting the clipboard contents
1356 //to empty before setting the large StringSelection!!
1357 Toolkit.getDefaultToolkit().getSystemClipboard()
1358 .setContents(new StringSelection(""), null);
1360 Toolkit.getDefaultToolkit().getSystemClipboard()
1361 .setContents(ss, Desktop.instance);
1363 catch (OutOfMemoryError er)
1365 er.printStackTrace();
1366 javax.swing.SwingUtilities.invokeLater(new Runnable()
1370 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1371 "Out of memory copying region!!"
1373 "\nSee help files for increasing Java Virtual Machine memory."
1375 javax.swing.JOptionPane.WARNING_MESSAGE);
1382 Vector hiddenColumns = null;
1383 if(viewport.hasHiddenColumns)
1385 hiddenColumns =new Vector();
1386 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1387 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
1390 int[] region = (int[])
1391 viewport.getColumnSelection().getHiddenColumns().elementAt(i);
1393 hiddenColumns.addElement(new int[]
1394 {region[0] - hiddenOffset,
1395 region[1]-hiddenOffset});
1399 Desktop.jalviewClipboard = new Object[]
1402 viewport.alignment.getDataset(),
1404 statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
1410 * @param e DOCUMENT ME!
1412 protected void pasteNew_actionPerformed(ActionEvent e)
1420 * @param e DOCUMENT ME!
1422 protected void pasteThis_actionPerformed(ActionEvent e)
1430 * @param newAlignment DOCUMENT ME!
1432 void paste(boolean newAlignment)
1434 boolean externalPaste=true;
1437 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1438 Transferable contents = c.getContents(this);
1440 if (contents == null)
1448 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1449 if (str.length() < 1)
1454 format = new IdentifyFile().Identify(str, "Paste");
1457 catch (OutOfMemoryError er)
1459 er.printStackTrace();
1460 javax.swing.SwingUtilities.invokeLater(new Runnable()
1464 javax.swing.JOptionPane.showInternalMessageDialog(Desktop.desktop,
1465 "Out of memory pasting sequences!!"
1467 "\nSee help files for increasing Java Virtual Machine memory."
1469 javax.swing.JOptionPane.WARNING_MESSAGE);
1476 SequenceI[] sequences;
1477 boolean annotationAdded = false;
1478 AlignmentI alignment = null;
1480 if(Desktop.jalviewClipboard!=null)
1482 // The clipboard was filled from within Jalview, we must use the sequences
1483 // And dataset from the copied alignment
1484 SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
1485 // be doubly sure that we create *new* sequence objects.
1486 sequences = new SequenceI[newseq.length];
1487 for (int i=0;i<newseq.length;i++) {
1488 sequences[i] = new Sequence(newseq[i]);
1490 alignment = new Alignment(sequences);
1491 externalPaste = false;
1495 // parse the clipboard as an alignment.
1496 alignment = new FormatAdapter().readFile(str, "Paste", format);
1497 sequences = alignment.getSequencesArray();
1505 if (Desktop.jalviewClipboard != null)
1507 // dataset is inherited
1508 alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
1512 // new dataset is constructed
1513 alignment.setDataset(null);
1515 alwidth = alignment.getWidth()+1;
1519 AlignmentI pastedal = alignment; // preserve pasted alignment object
1520 // Add pasted sequences and dataset into existing alignment.
1521 alignment = viewport.getAlignment();
1522 alwidth = alignment.getWidth()+1;
1523 // decide if we need to import sequences from an existing dataset
1524 boolean importDs = Desktop.jalviewClipboard != null
1525 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1526 // importDs==true instructs us to copy over new dataset sequences from
1527 // an existing alignment
1528 Vector newDs = (importDs) ? new Vector() : null; // used to create
1529 // minimum dataset set
1531 for (int i = 0; i < sequences.length; i++)
1535 newDs.addElement(null);
1537 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1539 if (importDs && ds != null)
1541 if (!newDs.contains(ds))
1543 newDs.setElementAt(ds, i);
1544 ds = new Sequence(ds);
1545 // update with new dataset sequence
1546 sequences[i].setDatasetSequence(ds);
1550 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1555 // copy and derive new dataset sequence
1556 sequences[i] = sequences[i].deriveSequence();
1557 alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
1558 // TODO: avoid creation of duplicate dataset sequences with a
1559 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1561 alignment.addSequence(sequences[i]); // merges dataset
1565 newDs.clear(); // tidy up
1567 if (pastedal.getAlignmentAnnotation()!=null) {
1568 // Add any annotation attached to alignment.
1569 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1570 for (int i=0; i<alann.length; i++)
1572 annotationAdded=true;
1573 if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
1574 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1575 newann.padAnnotation(alwidth);
1576 alignment.addAnnotation(newann);
1581 if (!newAlignment) {
1585 addHistoryItem(new EditCommand(
1590 alignment.getWidth(),
1594 // Add any annotations attached to sequences
1595 for (int i = 0; i < sequences.length; i++)
1597 if (sequences[i].getAnnotation() != null)
1599 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1601 annotationAdded=true;
1602 sequences[i].getAnnotation()[a].adjustForAlignment();
1603 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1604 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
1605 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1609 if (!newAlignment) {
1611 // propagate alignment changed.
1612 viewport.setEndSeq(alignment.getHeight());
1613 if (annotationAdded)
1615 // Duplicate sequence annotation in all views.
1616 AlignmentI[] alview = this.getViewAlignments();
1617 for (int i = 0; i < sequences.length; i++)
1619 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1622 for (int avnum = 0; avnum < alview.length; avnum++)
1625 if (alview[avnum] != alignment)
1627 // duplicate in a view other than the one with input focus
1628 int avwidth = alview[avnum].getWidth() + 1;
1630 // this relies on sann being preserved after we modify the sequence's annotation array
1631 for (int a=0; a<sann.length; a++)
1633 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
1635 sequences[i].addAlignmentAnnotation(newann);
1636 newann.padAnnotation(avwidth);
1637 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
1638 alview[avnum].setAnnotationIndex(newann, a);
1643 buildSortByAnnotationScoresMenu();
1645 viewport.firePropertyChange("alignment", null, alignment.getSequences());
1648 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
1649 String newtitle = new String("Copied sequences");
1651 if(Desktop.jalviewClipboard!=null && Desktop.jalviewClipboard[2]!=null)
1653 Vector hc = (Vector)Desktop.jalviewClipboard[2];
1654 for(int i=0; i<hc.size(); i++)
1656 int [] region = (int[]) hc.elementAt(i);
1657 af.viewport.hideColumns(region[0], region[1]);
1662 //>>>This is a fix for the moment, until a better solution is found!!<<<
1663 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
1664 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1666 // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
1667 if (!externalPaste) {
1668 if (title.startsWith("Copied sequences"))
1674 newtitle = newtitle.concat("- from " + title);
1677 newtitle = new String("Pasted sequences");
1680 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1687 catch (Exception ex)
1689 ex.printStackTrace();
1690 System.out.println("Exception whilst pasting: "+ex);
1691 // could be anything being pasted in here
1700 * @param e DOCUMENT ME!
1702 protected void cut_actionPerformed(ActionEvent e)
1704 copy_actionPerformed(null);
1705 delete_actionPerformed(null);
1711 * @param e DOCUMENT ME!
1713 protected void delete_actionPerformed(ActionEvent evt)
1716 SequenceGroup sg = viewport.getSelectionGroup();
1722 Vector seqs = new Vector();
1724 for (int i = 0; i < sg.getSize(); i++)
1726 seq = sg.getSequenceAt(i);
1727 seqs.addElement(seq);
1731 // If the cut affects all sequences, remove highlighted columns
1732 if (sg.getSize() == viewport.alignment.getHeight())
1734 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1735 sg.getEndRes() + 1);
1739 SequenceI [] cut = new SequenceI[seqs.size()];
1740 for(int i=0; i<seqs.size(); i++)
1742 cut[i] = (SequenceI)seqs.elementAt(i);
1749 addHistoryItem(new EditCommand("Cut Sequences",
1753 sg.getEndRes()-sg.getStartRes()+1,
1754 viewport.alignment));
1757 viewport.setSelectionGroup(null);
1758 viewport.alignment.deleteGroup(sg);
1760 viewport.firePropertyChange("alignment", null,
1761 viewport.getAlignment().getSequences());
1763 if (viewport.getAlignment().getHeight() < 1)
1767 this.setClosed(true);
1769 catch (Exception ex)
1778 * @param e DOCUMENT ME!
1780 protected void deleteGroups_actionPerformed(ActionEvent e)
1782 viewport.alignment.deleteAllGroups();
1783 viewport.sequenceColours = null;
1784 viewport.setSelectionGroup(null);
1785 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1786 alignPanel.paintAlignment(true);
1792 * @param e DOCUMENT ME!
1794 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1796 SequenceGroup sg = new SequenceGroup();
1798 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1801 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1804 sg.setEndRes(viewport.alignment.getWidth() - 1);
1805 viewport.setSelectionGroup(sg);
1806 alignPanel.paintAlignment(true);
1807 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1813 * @param e DOCUMENT ME!
1815 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1817 if(viewport.cursorMode)
1819 alignPanel.seqPanel.keyboardNo1 = null;
1820 alignPanel.seqPanel.keyboardNo2 = null;
1822 viewport.setSelectionGroup(null);
1823 viewport.getColumnSelection().clear();
1824 viewport.setSelectionGroup(null);
1825 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1826 alignPanel.idPanel.idCanvas.searchResults = null;
1827 alignPanel.paintAlignment(true);
1828 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1834 * @param e DOCUMENT ME!
1836 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1838 SequenceGroup sg = viewport.getSelectionGroup();
1842 selectAllSequenceMenuItem_actionPerformed(null);
1847 for (int i = 0; i < viewport.getAlignment().getSequences().size();
1850 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1853 alignPanel.paintAlignment(true);
1855 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1858 public void invertColSel_actionPerformed(ActionEvent e)
1860 viewport.invertColumnSelection();
1861 alignPanel.paintAlignment(true);
1868 * @param e DOCUMENT ME!
1870 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1872 trimAlignment(true);
1878 * @param e DOCUMENT ME!
1880 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1882 trimAlignment(false);
1885 void trimAlignment(boolean trimLeft)
1887 ColumnSelection colSel = viewport.getColumnSelection();
1890 if (colSel.size() > 0)
1894 column = colSel.getMin();
1898 column = colSel.getMax();
1902 if(viewport.getSelectionGroup()!=null)
1904 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1905 hiddenRepSequences);
1909 seqs = viewport.alignment.getSequencesArray();
1913 TrimRegionCommand trimRegion;
1916 trimRegion = new TrimRegionCommand("Remove Left",
1917 TrimRegionCommand.TRIM_LEFT,
1922 viewport.selectionGroup);
1923 viewport.setStartRes(0);
1927 trimRegion = new TrimRegionCommand("Remove Right",
1928 TrimRegionCommand.TRIM_RIGHT,
1933 viewport.selectionGroup);
1936 statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
1939 addHistoryItem(trimRegion);
1941 Vector groups = viewport.alignment.getGroups();
1943 for (int i = 0; i < groups.size(); i++)
1945 SequenceGroup sg = (SequenceGroup) groups.get(i);
1947 if ( (trimLeft && !sg.adjustForRemoveLeft(column))
1948 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1950 viewport.alignment.deleteGroup(sg);
1954 viewport.firePropertyChange("alignment", null,
1955 viewport.getAlignment().getSequences());
1962 * @param e DOCUMENT ME!
1964 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1966 int start = 0, end = viewport.alignment.getWidth()-1;
1969 if (viewport.getSelectionGroup() != null)
1971 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
1972 hiddenRepSequences);
1973 start = viewport.getSelectionGroup().getStartRes();
1974 end = viewport.getSelectionGroup().getEndRes();
1978 seqs = viewport.alignment.getSequencesArray();
1982 RemoveGapColCommand removeGapCols =
1983 new RemoveGapColCommand("Remove Gapped Columns",
1986 viewport.alignment);
1988 addHistoryItem(removeGapCols);
1990 statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
1992 //This is to maintain viewport position on first residue
1994 SequenceI seq = viewport.alignment.getSequenceAt(0);
1995 int startRes = seq.findPosition(viewport.startRes);
1996 // ShiftList shifts;
1997 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
1998 // edit.alColumnChanges=shifts.getInverse();
1999 // if (viewport.hasHiddenColumns)
2000 // viewport.getColumnSelection().compensateForEdits(shifts);
2001 viewport.setStartRes(seq.findIndex(startRes)-1);
2002 viewport.firePropertyChange("alignment", null,
2003 viewport.getAlignment().getSequences());
2010 * @param e DOCUMENT ME!
2012 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2014 int start = 0, end = viewport.alignment.getWidth()-1;
2017 if (viewport.getSelectionGroup() != null)
2019 seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
2020 hiddenRepSequences);
2021 start = viewport.getSelectionGroup().getStartRes();
2022 end = viewport.getSelectionGroup().getEndRes();
2026 seqs = viewport.alignment.getSequencesArray();
2029 //This is to maintain viewport position on first residue
2031 SequenceI seq = viewport.alignment.getSequenceAt(0);
2032 int startRes = seq.findPosition(viewport.startRes);
2034 addHistoryItem(new RemoveGapsCommand("Remove Gaps",
2037 viewport.alignment));
2039 viewport.setStartRes(seq.findIndex(startRes)-1);
2041 viewport.firePropertyChange("alignment", null,
2042 viewport.getAlignment().getSequences());
2049 * @param e DOCUMENT ME!
2051 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2053 viewport.padGaps = padGapsMenuitem.isSelected();
2055 viewport.firePropertyChange("alignment",
2057 viewport.getAlignment().getSequences());
2063 * @param e DOCUMENT ME!
2065 public void findMenuItem_actionPerformed(ActionEvent e)
2070 public void newView_actionPerformed(ActionEvent e)
2072 AlignmentPanel newap =
2073 new Jalview2XML().copyAlignPanel(alignPanel, true);
2075 newap.av.gatherViewsHere = false;
2077 if (viewport.viewName == null)
2079 viewport.viewName = "Original";
2082 newap.av.historyList = viewport.historyList;
2083 newap.av.redoList = viewport.redoList;
2085 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2086 String newViewName = "View " +index;
2088 Vector comps = (Vector) PaintRefresher.components.get(viewport.
2089 getSequenceSetId());
2090 Vector existingNames = new Vector();
2091 for(int i=0; i<comps.size(); i++)
2093 if(comps.elementAt(i) instanceof AlignmentPanel)
2095 AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
2096 if(!existingNames.contains(ap.av.viewName))
2098 existingNames.addElement(ap.av.viewName);
2103 while(existingNames.contains(newViewName))
2105 newViewName = "View "+ (++index);
2108 newap.av.viewName = newViewName;
2110 addAlignmentPanel(newap, false);
2112 if(alignPanels.size()==2)
2114 viewport.gatherViewsHere = true;
2116 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2119 public void expandViews_actionPerformed(ActionEvent e)
2121 Desktop.instance.explodeViews(this);
2124 public void gatherViews_actionPerformed(ActionEvent e)
2126 Desktop.instance.gatherViews(this);
2134 * @param e DOCUMENT ME!
2136 public void font_actionPerformed(ActionEvent e)
2138 new FontChooser(alignPanel);
2145 * @param e DOCUMENT ME!
2147 protected void seqLimit_actionPerformed(ActionEvent e)
2149 viewport.setShowJVSuffix(seqLimits.isSelected());
2151 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
2152 alignPanel.paintAlignment(true);
2155 public void idRightAlign_actionPerformed(ActionEvent e)
2157 viewport.rightAlignIds = idRightAlign.isSelected();
2158 alignPanel.paintAlignment(true);
2166 * @param e DOCUMENT ME!
2168 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2170 viewport.setColourText(colourTextMenuItem.isSelected());
2171 alignPanel.paintAlignment(true);
2177 * @param e DOCUMENT ME!
2179 public void wrapMenuItem_actionPerformed(ActionEvent e)
2181 scaleAbove.setVisible(wrapMenuItem.isSelected());
2182 scaleLeft.setVisible(wrapMenuItem.isSelected());
2183 scaleRight.setVisible(wrapMenuItem.isSelected());
2184 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2185 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2188 public void showAllSeqs_actionPerformed(ActionEvent e)
2190 viewport.showAllHiddenSeqs();
2193 public void showAllColumns_actionPerformed(ActionEvent e)
2195 viewport.showAllHiddenColumns();
2199 public void hideSelSequences_actionPerformed(ActionEvent e)
2201 viewport.hideAllSelectedSeqs();
2202 alignPanel.paintAlignment(true);
2205 public void hideSelColumns_actionPerformed(ActionEvent e)
2207 viewport.hideSelectedColumns();
2208 alignPanel.paintAlignment(true);
2211 public void hiddenMarkers_actionPerformed(ActionEvent e)
2213 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2220 * @param e DOCUMENT ME!
2222 protected void scaleAbove_actionPerformed(ActionEvent e)
2224 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2225 alignPanel.paintAlignment(true);
2231 * @param e DOCUMENT ME!
2233 protected void scaleLeft_actionPerformed(ActionEvent e)
2235 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2236 alignPanel.paintAlignment(true);
2242 * @param e DOCUMENT ME!
2244 protected void scaleRight_actionPerformed(ActionEvent e)
2246 viewport.setScaleRightWrapped(scaleRight.isSelected());
2247 alignPanel.paintAlignment(true);
2253 * @param e DOCUMENT ME!
2255 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2257 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2258 alignPanel.paintAlignment(true);
2264 * @param e DOCUMENT ME!
2266 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2268 viewport.setShowText(viewTextMenuItem.isSelected());
2269 alignPanel.paintAlignment(true);
2275 * @param e DOCUMENT ME!
2277 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2279 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2280 alignPanel.paintAlignment(true);
2284 public FeatureSettings featureSettings;
2285 public void featureSettings_actionPerformed(ActionEvent e)
2287 if(featureSettings !=null )
2289 featureSettings.close();
2290 featureSettings = null;
2292 featureSettings = new FeatureSettings(this);
2298 * @param evt DOCUMENT ME!
2300 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2302 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2303 alignPanel.paintAlignment(true);
2304 if (alignPanel.getOverviewPanel() != null)
2306 alignPanel.getOverviewPanel().updateOverviewImage();
2313 * @param e DOCUMENT ME!
2315 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2317 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2318 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2321 public void alignmentProperties()
2323 JEditorPane editPane = new JEditorPane("text/html","");
2324 editPane.setEditable(false);
2325 StringBuffer contents = new StringBuffer("<html>");
2328 int min=Integer.MAX_VALUE, max=0;
2329 for(int i=0; i<viewport.alignment.getHeight(); i++)
2331 int size = viewport.alignment.getSequenceAt(i).getEnd()
2332 -viewport.alignment.getSequenceAt(i).getStart();
2339 avg = avg/(float)viewport.alignment.getHeight();
2341 contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
2342 contents.append("<br>Minimum Sequence Length: "+min);
2343 contents.append("<br>Maximum Sequence Length: "+max);
2344 contents.append("<br>Average Length: "+(int)avg);
2346 if (((Alignment)viewport.alignment).getProperties() != null)
2348 Hashtable props = ((Alignment)viewport.alignment).getProperties();
2349 Enumeration en = props.keys();
2350 contents.append("<br><br><table border=\"1\">");
2351 while(en.hasMoreElements())
2353 String key = en.nextElement().toString();
2354 StringBuffer val = new StringBuffer();
2355 String vals = props.get(key).toString();
2358 npos = vals.indexOf("\n",pos);
2361 val.append(vals.substring(pos));
2363 val.append(vals.substring(pos, npos));
2368 contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
2370 contents.append("</table>");
2372 editPane.setText(contents.toString()+"</html>");
2373 JInternalFrame frame = new JInternalFrame();
2374 frame.getContentPane().add(new JScrollPane(editPane));
2376 Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
2383 * @param e DOCUMENT ME!
2385 public void overviewMenuItem_actionPerformed(ActionEvent e)
2387 if (alignPanel.overviewPanel != null)
2392 JInternalFrame frame = new JInternalFrame();
2393 OverviewPanel overview = new OverviewPanel(alignPanel);
2394 frame.setContentPane(overview);
2395 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(),
2396 frame.getWidth(), frame.getHeight());
2398 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2399 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2401 public void internalFrameClosed(
2402 javax.swing.event.InternalFrameEvent evt)
2404 alignPanel.setOverviewPanel(null);
2409 alignPanel.setOverviewPanel(overview);
2412 public void textColour_actionPerformed(ActionEvent e)
2414 new TextColourChooser().chooseColour(alignPanel, null);
2420 * @param e DOCUMENT ME!
2422 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2430 * @param e DOCUMENT ME!
2432 public void clustalColour_actionPerformed(ActionEvent e)
2434 changeColour(new ClustalxColourScheme(
2435 viewport.alignment.getSequences(), viewport.alignment.getWidth()));
2441 * @param e DOCUMENT ME!
2443 public void zappoColour_actionPerformed(ActionEvent e)
2445 changeColour(new ZappoColourScheme());
2451 * @param e DOCUMENT ME!
2453 public void taylorColour_actionPerformed(ActionEvent e)
2455 changeColour(new TaylorColourScheme());
2461 * @param e DOCUMENT ME!
2463 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2465 changeColour(new HydrophobicColourScheme());
2471 * @param e DOCUMENT ME!
2473 public void helixColour_actionPerformed(ActionEvent e)
2475 changeColour(new HelixColourScheme());
2481 * @param e DOCUMENT ME!
2483 public void strandColour_actionPerformed(ActionEvent e)
2485 changeColour(new StrandColourScheme());
2491 * @param e DOCUMENT ME!
2493 public void turnColour_actionPerformed(ActionEvent e)
2495 changeColour(new TurnColourScheme());
2501 * @param e DOCUMENT ME!
2503 public void buriedColour_actionPerformed(ActionEvent e)
2505 changeColour(new BuriedColourScheme());
2511 * @param e DOCUMENT ME!
2513 public void nucleotideColour_actionPerformed(ActionEvent e)
2515 changeColour(new NucleotideColourScheme());
2518 public void annotationColour_actionPerformed(ActionEvent e)
2520 new AnnotationColourChooser(viewport, alignPanel);
2527 * @param e DOCUMENT ME!
2529 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2531 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2537 * @param cs DOCUMENT ME!
2539 public void changeColour(ColourSchemeI cs)
2545 if (viewport.getAbovePIDThreshold())
2547 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2550 cs.setThreshold(threshold,
2551 viewport.getIgnoreGapsConsensus());
2553 viewport.setGlobalColourScheme(cs);
2557 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2560 if (viewport.getConservationSelected())
2563 Alignment al = (Alignment) viewport.alignment;
2564 Conservation c = new Conservation("All",
2565 ResidueProperties.propHash, 3,
2566 al.getSequences(), 0,
2570 c.verdict(false, viewport.ConsPercGaps);
2572 cs.setConservation(c);
2574 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel, cs,
2579 cs.setConservation(null);
2582 cs.setConsensus(viewport.hconsensus);
2585 viewport.setGlobalColourScheme(cs);
2587 if (viewport.getColourAppliesToAllGroups())
2589 Vector groups = viewport.alignment.getGroups();
2591 for (int i = 0; i < groups.size(); i++)
2593 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2601 if (cs instanceof ClustalxColourScheme)
2603 sg.cs = new ClustalxColourScheme(
2604 sg.getSequences(viewport.hiddenRepSequences), sg.getWidth());
2606 else if (cs instanceof UserColourScheme)
2608 sg.cs = new UserColourScheme( ( (UserColourScheme) cs).getColours());
2614 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2616 catch (Exception ex)
2621 if (viewport.getAbovePIDThreshold()
2622 || cs instanceof PIDColourScheme
2623 || cs instanceof Blosum62ColourScheme)
2625 sg.cs.setThreshold(threshold,
2626 viewport.getIgnoreGapsConsensus());
2628 sg.cs.setConsensus(AAFrequency.calculate(
2629 sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
2634 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2638 if (viewport.getConservationSelected())
2640 Conservation c = new Conservation("Group",
2641 ResidueProperties.propHash, 3,
2642 sg.getSequences(viewport.
2643 hiddenRepSequences),
2647 c.verdict(false, viewport.ConsPercGaps);
2648 sg.cs.setConservation(c);
2652 sg.cs.setConservation(null);
2657 if (alignPanel.getOverviewPanel() != null)
2659 alignPanel.getOverviewPanel().updateOverviewImage();
2665 alignPanel.paintAlignment(true);
2671 * @param e DOCUMENT ME!
2673 protected void modifyPID_actionPerformed(ActionEvent e)
2675 if (viewport.getAbovePIDThreshold() && viewport.globalColourScheme!=null)
2677 SliderPanel.setPIDSliderSource(alignPanel,
2678 viewport.getGlobalColourScheme(),
2680 SliderPanel.showPIDSlider();
2687 * @param e DOCUMENT ME!
2689 protected void modifyConservation_actionPerformed(ActionEvent e)
2691 if (viewport.getConservationSelected() && viewport.globalColourScheme!=null)
2693 SliderPanel.setConservationSlider(alignPanel,
2694 viewport.globalColourScheme,
2696 SliderPanel.showConservationSlider();
2703 * @param e DOCUMENT ME!
2705 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2707 viewport.setConservationSelected(conservationMenuItem.isSelected());
2709 viewport.setAbovePIDThreshold(false);
2710 abovePIDThreshold.setSelected(false);
2712 changeColour(viewport.getGlobalColourScheme());
2714 modifyConservation_actionPerformed(null);
2720 * @param e DOCUMENT ME!
2722 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2724 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2726 conservationMenuItem.setSelected(false);
2727 viewport.setConservationSelected(false);
2729 changeColour(viewport.getGlobalColourScheme());
2731 modifyPID_actionPerformed(null);
2737 * @param e DOCUMENT ME!
2739 public void userDefinedColour_actionPerformed(ActionEvent e)
2741 if (e.getActionCommand().equals("User Defined..."))
2743 new UserDefinedColours(alignPanel, null);
2747 UserColourScheme udc = (UserColourScheme) UserDefinedColours.
2748 getUserColourSchemes().get(e.getActionCommand());
2754 public void updateUserColourMenu()
2757 Component[] menuItems = colourMenu.getMenuComponents();
2758 int i, iSize = menuItems.length;
2759 for (i = 0; i < iSize; i++)
2761 if (menuItems[i].getName() != null &&
2762 menuItems[i].getName().equals("USER_DEFINED"))
2764 colourMenu.remove(menuItems[i]);
2768 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2770 java.util.Enumeration userColours = jalview.gui.UserDefinedColours.
2771 getUserColourSchemes().keys();
2773 while (userColours.hasMoreElements())
2775 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2777 nextElement().toString());
2778 radioItem.setName("USER_DEFINED");
2779 radioItem.addMouseListener(new MouseAdapter()
2781 public void mousePressed(MouseEvent evt)
2783 if(evt.isControlDown() || SwingUtilities.isRightMouseButton(evt))
2785 radioItem.removeActionListener(radioItem.getActionListeners()[0]);
2787 int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
2789 "Remove from default list?",
2790 "Remove user defined colour",
2791 JOptionPane.YES_NO_OPTION);
2792 if(option == JOptionPane.YES_OPTION)
2794 jalview.gui.UserDefinedColours.removeColourFromDefaults(
2795 radioItem.getText());
2796 colourMenu.remove(radioItem);
2800 radioItem.addActionListener(new ActionListener()
2802 public void actionPerformed(ActionEvent evt)
2804 userDefinedColour_actionPerformed(evt);
2811 radioItem.addActionListener(new ActionListener()
2813 public void actionPerformed(ActionEvent evt)
2815 userDefinedColour_actionPerformed(evt);
2819 colourMenu.insert(radioItem, 15);
2820 colours.add(radioItem);
2828 * @param e DOCUMENT ME!
2830 public void PIDColour_actionPerformed(ActionEvent e)
2832 changeColour(new PIDColourScheme());
2838 * @param e DOCUMENT ME!
2840 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2842 changeColour(new Blosum62ColourScheme());
2848 * @param e DOCUMENT ME!
2850 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2852 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2853 AlignmentSorter.sortByPID(viewport.getAlignment(),
2854 viewport.getAlignment().getSequenceAt(0));
2855 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2856 viewport.alignment));
2857 alignPanel.paintAlignment(true);
2863 * @param e DOCUMENT ME!
2865 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2867 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2868 AlignmentSorter.sortByID(viewport.getAlignment());
2869 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2870 alignPanel.paintAlignment(true);
2876 * @param e DOCUMENT ME!
2878 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2880 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
2881 AlignmentSorter.sortByGroup(viewport.getAlignment());
2882 addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
2884 alignPanel.paintAlignment(true);
2889 * @param e DOCUMENT ME!
2891 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2893 new RedundancyPanel(alignPanel, this);
2900 * @param e DOCUMENT ME!
2902 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2904 if ( (viewport.getSelectionGroup() == null) ||
2905 (viewport.getSelectionGroup().getSize() < 2))
2907 JOptionPane.showInternalMessageDialog(this,
2908 "You must select at least 2 sequences.",
2909 "Invalid Selection",
2910 JOptionPane.WARNING_MESSAGE);
2914 JInternalFrame frame = new JInternalFrame();
2915 frame.setContentPane(new PairwiseAlignPanel(viewport));
2916 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2923 * @param e DOCUMENT ME!
2925 public void PCAMenuItem_actionPerformed(ActionEvent e)
2927 if ( ( (viewport.getSelectionGroup() != null) &&
2928 (viewport.getSelectionGroup().getSize() < 4) &&
2929 (viewport.getSelectionGroup().getSize() > 0)) ||
2930 (viewport.getAlignment().getHeight() < 4))
2932 JOptionPane.showInternalMessageDialog(this,
2933 "Principal component analysis must take\n" +
2934 "at least 4 input sequences.",
2935 "Sequence selection insufficient",
2936 JOptionPane.WARNING_MESSAGE);
2941 new PCAPanel(alignPanel);
2945 public void autoCalculate_actionPerformed(ActionEvent e)
2947 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2948 if(viewport.autoCalculateConsensus)
2950 viewport.firePropertyChange("alignment",
2952 viewport.getAlignment().getSequences());
2960 * @param e DOCUMENT ME!
2962 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2964 NewTreePanel("AV", "PID", "Average distance tree using PID");
2970 * @param e DOCUMENT ME!
2972 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
2974 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
2980 * @param e DOCUMENT ME!
2982 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2984 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
2990 * @param e DOCUMENT ME!
2992 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
2994 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3000 * @param type DOCUMENT ME!
3001 * @param pwType DOCUMENT ME!
3002 * @param title DOCUMENT ME!
3004 void NewTreePanel(String type, String pwType, String title)
3008 if (viewport.getSelectionGroup() != null)
3010 if (viewport.getSelectionGroup().getSize() < 3)
3012 JOptionPane.showMessageDialog(Desktop.desktop,
3013 "You need to have more than two sequences selected to build a tree!",
3014 "Not enough sequences",
3015 JOptionPane.WARNING_MESSAGE);
3020 SequenceGroup sg = viewport.getSelectionGroup();
3022 /* Decide if the selection is a column region */
3023 while (s < sg.getSize())
3025 if ( ( (SequenceI) sg.getSequences(null).elementAt(s++)).getLength() <
3028 JOptionPane.showMessageDialog(Desktop.desktop,
3029 "The selected region to create a tree may\nonly contain residues or gaps.\n" +
3030 "Try using the Pad function in the edit menu,\n" +
3031 "or one of the multiple sequence alignment web services.",
3032 "Sequences in selection are not aligned",
3033 JOptionPane.WARNING_MESSAGE);
3039 title = title + " on region";
3040 tp = new TreePanel(alignPanel, type, pwType);
3044 //are the sequences aligned?
3045 if (!viewport.alignment.isAligned())
3047 JOptionPane.showMessageDialog(Desktop.desktop,
3048 "The sequences must be aligned before creating a tree.\n" +
3049 "Try using the Pad function in the edit menu,\n" +
3050 "or one of the multiple sequence alignment web services.",
3051 "Sequences not aligned",
3052 JOptionPane.WARNING_MESSAGE);
3057 if(viewport.alignment.getHeight()<2)
3062 tp = new TreePanel(alignPanel, type, pwType);
3067 if(viewport.viewName!=null)
3069 title+= viewport.viewName+" of ";
3072 title += this.title;
3074 Desktop.addInternalFrame(tp, title, 600, 500);
3080 * @param title DOCUMENT ME!
3081 * @param order DOCUMENT ME!
3083 public void addSortByOrderMenuItem(String title, final AlignmentOrder order)
3085 final JMenuItem item = new JMenuItem("by " + title);
3087 item.addActionListener(new java.awt.event.ActionListener()
3089 public void actionPerformed(ActionEvent e)
3091 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3093 // TODO: JBPNote - have to map order entries to curent SequenceI pointers
3094 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3096 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3097 viewport.alignment));
3099 alignPanel.paintAlignment(true);
3104 * Add a new sort by annotation score menu item
3105 * @param sort the menu to add the option to
3106 * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
3108 public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
3110 final JMenuItem item = new JMenuItem(scoreLabel);
3112 item.addActionListener(new java.awt.event.ActionListener()
3114 public void actionPerformed(ActionEvent e)
3116 SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
3117 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());
3118 addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
3119 alignPanel.paintAlignment(true);
3124 * last hash for alignment's annotation array - used to minimise cost of rebuild.
3126 protected int _annotationScoreVectorHash;
3128 * search the alignment and rebuild the sort by annotation score submenu
3129 * the last alignment annotation vector hash is stored to minimize
3130 * cost of rebuilding in subsequence calls.
3133 public void buildSortByAnnotationScoresMenu()
3135 if(viewport.alignment.getAlignmentAnnotation()==null)
3140 if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
3142 sortByAnnotScore.removeAll();
3143 // almost certainly a quicker way to do this - but we keep it simple
3144 Hashtable scoreSorts=new Hashtable();
3145 AlignmentAnnotation aann[];
3146 Enumeration sq = viewport.alignment.getSequences().elements();
3147 while (sq.hasMoreElements())
3149 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3150 for (int i=0;aann!=null && i<aann.length; i++)
3152 if (aann[i].hasScore() && aann[i].sequenceRef!=null)
3154 scoreSorts.put(aann[i].label, aann[i].label);
3158 Enumeration labels = scoreSorts.keys();
3159 while (labels.hasMoreElements())
3161 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
3163 sortByAnnotScore.setVisible(scoreSorts.size()>0);
3166 _annotationScoreVectorHash =
3167 viewport.alignment.getAlignmentAnnotation().hashCode();
3172 * Maintain the Order by->Displayed Tree menu.
3173 * Creates a new menu item for a TreePanel with an appropriate
3174 * <code>jalview.analysis.AlignmentSorter</code> call. Listeners are added
3175 * to remove the menu item when the treePanel is closed, and adjust
3176 * the tree leaf to sequence mapping when the alignment is modified.
3177 * @param treePanel Displayed tree window.
3178 * @param title SortBy menu item title.
3180 public void buildTreeMenu()
3182 sortByTreeMenu.removeAll();
3184 Vector comps = (Vector) PaintRefresher.components.get(viewport.
3185 getSequenceSetId());
3186 Vector treePanels = new Vector();
3187 int i, iSize = comps.size();
3188 for(i=0; i<iSize; i++)
3190 if(comps.elementAt(i) instanceof TreePanel)
3192 treePanels.add(comps.elementAt(i));
3196 iSize = treePanels.size();
3200 sortByTreeMenu.setVisible(false);
3204 sortByTreeMenu.setVisible(true);
3206 for(i=0; i<treePanels.size(); i++)
3208 TreePanel tp = (TreePanel)treePanels.elementAt(i);
3209 final JMenuItem item = new JMenuItem(tp.getTitle());
3210 final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
3211 item.addActionListener(new java.awt.event.ActionListener()
3213 public void actionPerformed(ActionEvent e)
3215 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3216 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3218 addHistoryItem(new OrderCommand("Tree Sort",
3220 viewport.alignment));
3222 alignPanel.paintAlignment(true);
3226 sortByTreeMenu.add(item);
3231 * Work out whether the whole set of sequences
3232 * or just the selected set will be submitted for multiple alignment.
3235 private jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3237 // Now, check we have enough sequences
3238 AlignmentView msa = null;
3240 if ( (viewport.getSelectionGroup() != null) &&
3241 (viewport.getSelectionGroup().getSize() > 1))
3243 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
3244 /*SequenceGroup seqs = viewport.getSelectionGroup();
3246 msa = new SequenceI[sz = seqs.getSize(false)];
3248 for (int i = 0; i < sz; i++)
3250 msa[i] = (SequenceI) seqs.getSequenceAt(i);
3252 msa = viewport.getAlignmentView(true);
3256 /*Vector seqs = viewport.getAlignment().getSequences();
3258 if (seqs.size() > 1)
3260 msa = new SequenceI[seqs.size()];
3262 for (int i = 0; i < seqs.size(); i++)
3264 msa[i] = (SequenceI) seqs.elementAt(i);
3267 msa = viewport.getAlignmentView(false);
3273 * Decides what is submitted to a secondary structure prediction service,
3274 * the currently selected sequence, or the currently selected alignment
3275 * (where the first sequence in the set is the one that the prediction
3278 AlignmentView gatherSeqOrMsaForSecStrPrediction()
3280 AlignmentView seqs = null;
3282 if ( (viewport.getSelectionGroup() != null) &&
3283 (viewport.getSelectionGroup().getSize() > 0))
3285 seqs = viewport.getAlignmentView(true);
3289 seqs = viewport.getAlignmentView(false);
3291 // limit sequences - JBPNote in future - could spawn multiple prediction jobs
3292 // TODO: viewport.alignment.isAligned is a global state - the local selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3293 if (!viewport.alignment.isAligned())
3295 seqs.setSequences(new SeqCigar[]
3296 {seqs.getSequences()[0]});
3303 * @param e DOCUMENT ME!
3305 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3307 // Pick the tree file
3308 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3311 chooser.setFileView(new JalviewFileView());
3312 chooser.setDialogTitle("Select a newick-like tree file");
3313 chooser.setToolTipText("Load a tree file");
3315 int value = chooser.showOpenDialog(null);
3317 if (value == JalviewFileChooser.APPROVE_OPTION)
3319 String choice = chooser.getSelectedFile().getPath();
3320 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3324 jalview.io.NewickFile fin = new jalview.io.NewickFile(choice,
3326 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3328 catch (Exception ex)
3330 JOptionPane.showMessageDialog(Desktop.desktop,
3331 "Problem reading tree file",
3333 JOptionPane.WARNING_MESSAGE);
3334 ex.printStackTrace();
3340 public TreePanel ShowNewickTree(NewickFile nf, String title)
3342 return ShowNewickTree(nf,title,600,500,4,5);
3345 public TreePanel ShowNewickTree(NewickFile nf, String title,
3346 AlignmentView input)
3348 return ShowNewickTree(nf,title, input, 600,500,4,5);
3351 public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
3354 return ShowNewickTree(nf, title, null, w, h, x, y);
3357 * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
3359 * @param nf the tree
3360 * @param title tree viewer title
3361 * @param input Associated alignment input data (or null)
3366 * @return TreePanel handle
3368 public TreePanel ShowNewickTree(NewickFile nf, String title,
3369 AlignmentView input, int w, int h, int x,
3372 TreePanel tp = null;
3378 if (nf.getTree() != null)
3380 tp = new TreePanel(alignPanel,
3389 tp.setLocation(x,y);
3393 Desktop.addInternalFrame(tp, title, w, h);
3396 catch (Exception ex)
3398 ex.printStackTrace();
3406 * Generates menu items and listener event actions for web service clients
3409 public void BuildWebServiceMenu()
3411 if ( (Discoverer.services != null)
3412 && (Discoverer.services.size() > 0))
3414 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3415 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3416 Vector wsmenu = new Vector();
3417 final AlignFrame af = this;
3420 // Add any Multiple Sequence Alignment Services
3421 final JMenu msawsmenu = new JMenu("Alignment");
3422 for (int i = 0, j = msaws.size(); i < j; i++)
3424 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws.
3426 final JMenuItem method = new JMenuItem(sh.getName());
3427 method.addActionListener(new ActionListener()
3429 public void actionPerformed(ActionEvent e)
3431 AlignmentView msa = gatherSequencesForAlignment();
3432 new jalview.ws.MsaWSClient(sh, title, msa,
3434 viewport.getAlignment().getDataset(),
3440 msawsmenu.add(method);
3441 // Deal with services that we know accept partial alignments.
3442 if (sh.getName().indexOf("lustal") > -1)
3444 // We know that ClustalWS can accept partial alignments for refinement.
3445 final JMenuItem methodR = new JMenuItem(sh.getName()+" Realign");
3446 methodR.addActionListener(new ActionListener()
3448 public void actionPerformed(ActionEvent e)
3450 AlignmentView msa = gatherSequencesForAlignment();
3451 new jalview.ws.MsaWSClient(sh, title, msa,
3453 viewport.getAlignment().getDataset(),
3459 msawsmenu.add(methodR);
3463 wsmenu.add(msawsmenu);
3465 if (secstrpr != null)
3467 // Add any secondary structure prediction services
3468 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3469 for (int i = 0, j = secstrpr.size(); i < j; i++)
3471 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle)
3473 final JMenuItem method = new JMenuItem(sh.getName());
3474 method.addActionListener(new ActionListener()
3476 public void actionPerformed(ActionEvent e)
3478 AlignmentView msa = gatherSeqOrMsaForSecStrPrediction();
3479 if (msa.getSequences().length == 1)
3481 // Single Sequence prediction
3482 new jalview.ws.JPredClient(sh, title, false, msa, af, true);
3486 if (msa.getSequences().length > 1)
3488 // Sequence profile based prediction
3489 new jalview.ws.JPredClient(sh,
3490 title, true, msa, af, true);
3495 secstrmenu.add(method);
3497 wsmenu.add(secstrmenu);
3499 resetWebServiceMenu();
3500 for (int i = 0, j = wsmenu.size(); i < j; i++)
3502 webService.add( (JMenu) wsmenu.get(i));
3507 resetWebServiceMenu();
3508 this.webService.add(this.webServiceNoServices);
3510 // TODO: add in rediscovery function
3511 // TODO: reduce code redundancy.
3512 // TODO: group services by location as well as function.
3517 * empty the web service menu and add any ad-hoc functions
3518 * not dynamically discovered.
3521 private void resetWebServiceMenu()
3523 webService.removeAll();
3524 // Temporary hack - DBRef Fetcher always top level ws entry.
3525 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3526 rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
3527 webService.add(rfetch);
3528 rfetch.addActionListener(new ActionListener() {
3530 public void actionPerformed(ActionEvent e)
3532 new jalview.io.DBRefFetcher(
3533 alignPanel.av.getSequenceSelection(),
3534 alignPanel.alignFrame).fetchDBRefs(false);
3540 /* public void vamsasStore_actionPerformed(ActionEvent e)
3542 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
3543 getProperty("LAST_DIRECTORY"));
3545 chooser.setFileView(new JalviewFileView());
3546 chooser.setDialogTitle("Export to Vamsas file");
3547 chooser.setToolTipText("Export");
3549 int value = chooser.showSaveDialog(this);
3551 if (value == JalviewFileChooser.APPROVE_OPTION)
3553 jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3554 //vs.store(chooser.getSelectedFile().getAbsolutePath() );
3555 vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
3561 public void showTranslation_actionPerformed(ActionEvent e)
3563 ///////////////////////////////
3564 // Collect Data to be translated/transferred
3566 SequenceI [] selection = viewport.getSequenceSelection();
3567 String [] seqstring = viewport.getViewAsString(true);
3568 AlignmentI al = null;
3570 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
3571 viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
3572 viewport.alignment.getWidth());
3573 } catch (Exception ex) {
3575 jalview.bin.Cache.log.debug("Exception during translation.",ex);
3579 JOptionPane.showMessageDialog(Desktop.desktop,
3580 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3581 "Translation Failed",
3582 JOptionPane.WARNING_MESSAGE);
3584 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3585 Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
3594 * @param String DOCUMENT ME!
3596 public boolean parseFeaturesFile(String file, String type)
3598 boolean featuresFile = false;
3601 featuresFile = new FeaturesFile(file,
3602 type).parse(viewport.alignment.getDataset(),
3603 alignPanel.seqPanel.seqCanvas.
3604 getFeatureRenderer().featureColours,
3609 ex.printStackTrace();
3614 viewport.showSequenceFeatures = true;
3615 showSeqFeatures.setSelected(true);
3616 alignPanel.paintAlignment(true);
3619 return featuresFile;
3622 public void dragEnter(DropTargetDragEvent evt)
3625 public void dragExit(DropTargetEvent evt)
3628 public void dragOver(DropTargetDragEvent evt)
3631 public void dropActionChanged(DropTargetDragEvent evt)
3634 public void drop(DropTargetDropEvent evt)
3636 Transferable t = evt.getTransferable();
3637 java.util.List files = null;
3641 DataFlavor uriListFlavor = new DataFlavor(
3642 "text/uri-list;class=java.lang.String");
3643 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3645 //Works on Windows and MacOSX
3646 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3647 files = (java.util.List) t.getTransferData(DataFlavor.
3648 javaFileListFlavor);
3650 else if (t.isDataFlavorSupported(uriListFlavor))
3652 // This is used by Unix drag system
3653 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3654 String data = (String) t.getTransferData(uriListFlavor);
3655 files = new java.util.ArrayList(1);
3656 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3659 st.hasMoreTokens(); )
3661 String s = st.nextToken();
3662 if (s.startsWith("#"))
3664 // the line is a comment (as per the RFC 2483)
3668 java.net.URI uri = new java.net.URI(s);
3669 java.io.File file = new java.io.File(uri);
3676 e.printStackTrace();
3683 for (int i = 0; i < files.size(); i++)
3685 loadJalviewDataFile(files.get(i).toString());
3688 catch (Exception ex)
3690 ex.printStackTrace();
3695 // This method will attempt to load a "dropped" file first by testing
3696 // whether its and Annotation file, then features file. If both are
3697 // false then the user may have dropped an alignment file onto this
3699 public void loadJalviewDataFile(String file)
3703 String protocol = "File";
3705 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3710 boolean isAnnotation = new AnnotationFile().readAnnotationFile(viewport.
3711 alignment, file, protocol);
3715 boolean isGroupsFile = parseFeaturesFile(file,protocol);
3718 String format = new IdentifyFile().Identify(file, protocol);
3720 if(format.equalsIgnoreCase("JnetFile"))
3722 jalview.io.JPredFile predictions = new jalview.io.JPredFile(
3724 new JnetAnnotationMaker().add_annotation(predictions,
3725 viewport.getAlignment(),
3727 alignPanel.adjustAnnotationHeight();
3728 alignPanel.paintAlignment(true);
3732 new FileLoader().LoadFile(viewport, file, protocol, format);
3739 alignPanel.adjustAnnotationHeight();
3740 buildSortByAnnotationScoresMenu();
3744 catch (Exception ex)
3746 ex.printStackTrace();
3750 public void tabSelectionChanged(int index)
3754 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
3755 viewport = alignPanel.av;
3756 setMenusFromViewport(viewport);
3760 public void tabbedPane_mousePressed(MouseEvent e)
3762 if(SwingUtilities.isRightMouseButton(e))
3764 String reply = JOptionPane.showInternalInputDialog(this,
3767 JOptionPane.QUESTION_MESSAGE);
3771 viewport.viewName = reply;
3772 tabbedPane.setTitleAt( tabbedPane.getSelectedIndex() ,reply);
3778 public AlignViewport getCurrentView()
3785 * Open the dialog for regex description parsing.
3787 protected void extractScores_actionPerformed(ActionEvent e)
3789 ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
3790 if (pp.getScoresFromDescription("col", "score column ", "\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)")>0)
3792 buildSortByAnnotationScoresMenu();
3801 public PrintThread(AlignmentPanel ap)
3805 static PageFormat pf;
3808 PrinterJob printJob = PrinterJob.getPrinterJob();
3812 printJob.setPrintable(ap, pf);
3816 printJob.setPrintable(ap);
3819 if (printJob.printDialog())
3825 catch (Exception PrintException)
3827 PrintException.printStackTrace();