2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 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 Software
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 extends GAlignFrame implements DropTargetListener,
51 public static final int DEFAULT_WIDTH = 700;
54 public static final int DEFAULT_HEIGHT = 500;
56 public AlignmentPanel alignPanel;
58 AlignViewport viewport;
60 Vector alignPanels = new Vector();
63 * Last format used to load or save alignments in this window
65 String currentFileFormat = null;
68 * Current filename for this alignment
70 String fileName = null;
73 * Creates a new AlignFrame object.
78 public AlignFrame(AlignmentI al, int width, int height)
80 this(al, null, width, height);
84 * new alignment window with hidden columns
88 * @param hiddenColumns
89 * ColumnSelection or null
91 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
92 int width, int height)
94 this.setSize(width, height);
95 viewport = new AlignViewport(al, hiddenColumns);
97 alignPanel = new AlignmentPanel(this, viewport);
99 if (al.getDataset() == null)
104 addAlignmentPanel(alignPanel, true);
109 * Make a new AlignFrame from exisiting alignmentPanels
116 public AlignFrame(AlignmentPanel ap)
120 addAlignmentPanel(ap, false);
126 if (viewport.conservation == null)
128 BLOSUM62Colour.setEnabled(false);
129 conservationMenuItem.setEnabled(false);
130 modifyConservation.setEnabled(false);
131 // PIDColour.setEnabled(false);
132 // abovePIDThreshold.setEnabled(false);
133 // modifyPID.setEnabled(false);
136 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
139 if (sortby.equals("Id"))
141 sortIDMenuItem_actionPerformed(null);
143 else if (sortby.equals("Pairwise Identity"))
145 sortPairwiseMenuItem_actionPerformed(null);
148 if (Desktop.desktop != null)
150 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
151 addServiceListeners();
152 setGUINucleotide(viewport.alignment.isNucleotide());
155 setMenusFromViewport(viewport);
156 buildSortByAnnotationScoresMenu();
157 if (viewport.wrapAlignment)
159 wrapMenuItem_actionPerformed(null);
162 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
164 this.overviewMenuItem_actionPerformed(null);
172 * Change the filename and format for the alignment, and enable the 'reload'
173 * button functionality.
180 public void setFileName(String file, String format)
183 currentFileFormat = format;
184 reload.setEnabled(true);
187 void addKeyListener()
189 addKeyListener(new KeyAdapter()
191 public void keyPressed(KeyEvent evt)
193 if (viewport.cursorMode
194 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
195 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
196 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
197 && Character.isDigit(evt.getKeyChar()))
198 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
200 switch (evt.getKeyCode())
203 case 27: // escape key
204 deselectAllSequenceMenuItem_actionPerformed(null);
208 case KeyEvent.VK_DOWN:
209 if (evt.isAltDown() || !viewport.cursorMode)
210 moveSelectedSequences(false);
211 if (viewport.cursorMode)
212 alignPanel.seqPanel.moveCursor(0, 1);
216 if (evt.isAltDown() || !viewport.cursorMode)
217 moveSelectedSequences(true);
218 if (viewport.cursorMode)
219 alignPanel.seqPanel.moveCursor(0, -1);
223 case KeyEvent.VK_LEFT:
224 if (evt.isAltDown() || !viewport.cursorMode)
225 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
227 alignPanel.seqPanel.moveCursor(-1, 0);
231 case KeyEvent.VK_RIGHT:
232 if (evt.isAltDown() || !viewport.cursorMode)
233 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
235 alignPanel.seqPanel.moveCursor(1, 0);
238 case KeyEvent.VK_SPACE:
239 if (viewport.cursorMode)
241 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
242 || evt.isShiftDown() || evt.isAltDown());
246 case KeyEvent.VK_DELETE:
247 case KeyEvent.VK_BACK_SPACE:
248 if (!viewport.cursorMode)
250 cut_actionPerformed(null);
254 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
255 || evt.isShiftDown() || evt.isAltDown());
261 if (viewport.cursorMode)
263 alignPanel.seqPanel.setCursorRow();
267 if (viewport.cursorMode && !evt.isControlDown())
269 alignPanel.seqPanel.setCursorColumn();
273 if (viewport.cursorMode)
275 alignPanel.seqPanel.setCursorPosition();
279 case KeyEvent.VK_ENTER:
280 case KeyEvent.VK_COMMA:
281 if (viewport.cursorMode)
283 alignPanel.seqPanel.setCursorRowAndColumn();
288 if (viewport.cursorMode)
290 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
294 if (viewport.cursorMode)
296 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
301 viewport.cursorMode = !viewport.cursorMode;
302 statusBar.setText("Keyboard editing mode is "
303 + (viewport.cursorMode ? "on" : "off"));
304 if (viewport.cursorMode)
306 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
307 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
309 alignPanel.seqPanel.seqCanvas.repaint();
315 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
316 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
318 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
320 javax.help.HelpBroker hb = hs.createHelpBroker();
321 hb.setCurrentID("home");
322 hb.setDisplayed(true);
323 } catch (Exception ex)
325 ex.printStackTrace();
330 boolean toggleSeqs = !evt.isControlDown();
331 boolean toggleCols = !evt.isShiftDown();
333 boolean hide = false;
335 SequenceGroup sg = viewport.getSelectionGroup();
339 && sg.getSize() != viewport.alignment.getHeight())
341 hideSelSequences_actionPerformed(null);
344 else if (!(toggleCols && viewport.colSel.getSelected().size() > 0))
346 showAllSeqs_actionPerformed(null);
352 if (viewport.colSel.getSelected().size() > 0)
354 hideSelColumns_actionPerformed(null);
357 viewport.selectionGroup = sg;
362 showAllColumns_actionPerformed(null);
367 case KeyEvent.VK_PAGE_UP:
368 if (viewport.wrapAlignment)
370 alignPanel.scrollUp(true);
374 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
375 - viewport.endSeq + viewport.startSeq);
378 case KeyEvent.VK_PAGE_DOWN:
379 if (viewport.wrapAlignment)
381 alignPanel.scrollUp(false);
385 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
386 + viewport.endSeq - viewport.startSeq);
392 public void keyReleased(KeyEvent evt)
394 switch (evt.getKeyCode())
396 case KeyEvent.VK_LEFT:
397 if (evt.isAltDown() || !viewport.cursorMode)
398 viewport.firePropertyChange("alignment", null, viewport
399 .getAlignment().getSequences());
402 case KeyEvent.VK_RIGHT:
403 if (evt.isAltDown() || !viewport.cursorMode)
404 viewport.firePropertyChange("alignment", null, viewport
405 .getAlignment().getSequences());
412 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
414 ap.alignFrame = this;
416 alignPanels.addElement(ap);
418 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
420 int aSize = alignPanels.size();
422 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
424 if (aSize == 1 && ap.av.viewName == null)
426 this.getContentPane().add(ap, BorderLayout.CENTER);
432 setInitialTabVisible();
435 expandViews.setEnabled(true);
436 gatherViews.setEnabled(true);
437 tabbedPane.addTab(ap.av.viewName, ap);
439 ap.setVisible(false);
446 ap.av.alignment.padGaps();
448 ap.av.updateConservation(ap);
449 ap.av.updateConsensus(ap);
453 public void setInitialTabVisible()
455 expandViews.setEnabled(true);
456 gatherViews.setEnabled(true);
457 tabbedPane.setVisible(true);
458 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
459 tabbedPane.addTab(first.av.viewName, first);
460 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
463 public AlignViewport getViewport()
468 /* Set up intrinsic listeners for dynamically generated GUI bits. */
469 private void addServiceListeners()
471 final java.beans.PropertyChangeListener thisListener;
472 // Do this once to get current state
473 BuildWebServiceMenu();
475 .addPropertyChangeListener(thisListener = new java.beans.PropertyChangeListener()
477 public void propertyChange(PropertyChangeEvent evt)
479 // System.out.println("Discoverer property change.");
480 if (evt.getPropertyName().equals("services"))
482 // System.out.println("Rebuilding web service menu");
483 BuildWebServiceMenu();
488 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
490 public void internalFrameClosed(
491 javax.swing.event.InternalFrameEvent evt)
493 // System.out.println("deregistering discoverer listener");
494 Desktop.discoverer.removePropertyChangeListener(thisListener);
495 closeMenuItem_actionPerformed(true);
500 public void setGUINucleotide(boolean nucleotide)
502 showTranslation.setVisible(nucleotide);
503 conservationMenuItem.setEnabled(!nucleotide);
504 modifyConservation.setEnabled(!nucleotide);
506 // Remember AlignFrame always starts as protein
509 calculateMenu.remove(calculateMenu.getItemCount() - 2);
514 * set up menus for the currently viewport. This may be called after any
515 * operation that affects the data in the current view (selection changed,
516 * etc) to update the menus to reflect the new state.
518 public void setMenusForViewport()
520 setMenusFromViewport(viewport);
524 * Need to call this method when tabs are selected for multiple views, or when
525 * loading from Jalview2XML.java
530 void setMenusFromViewport(AlignViewport av)
532 padGapsMenuitem.setSelected(av.padGaps);
533 colourTextMenuItem.setSelected(av.showColourText);
534 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
535 conservationMenuItem.setSelected(av.getConservationSelected());
536 seqLimits.setSelected(av.getShowJVSuffix());
537 idRightAlign.setSelected(av.rightAlignIds);
538 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
539 renderGapsMenuItem.setSelected(av.renderGaps);
540 wrapMenuItem.setSelected(av.wrapAlignment);
541 scaleAbove.setVisible(av.wrapAlignment);
542 scaleLeft.setVisible(av.wrapAlignment);
543 scaleRight.setVisible(av.wrapAlignment);
544 annotationPanelMenuItem.setState(av.showAnnotation);
545 viewBoxesMenuItem.setSelected(av.showBoxes);
546 viewTextMenuItem.setSelected(av.showText);
548 setColourSelected(ColourSchemeProperty.getColourName(av
549 .getGlobalColourScheme()));
551 showSeqFeatures.setSelected(av.showSequenceFeatures);
552 hiddenMarkers.setState(av.showHiddenMarkers);
553 applyToAllGroups.setState(av.colourAppliesToAllGroups);
554 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
555 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
557 setShowProductsEnabled();
562 Hashtable progressBars;
567 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
569 public void setProgressBar(String message, long id)
571 if (progressBars == null)
573 progressBars = new Hashtable();
576 JPanel progressPanel;
577 GridLayout layout = (GridLayout) statusPanel.getLayout();
578 if (progressBars.get(new Long(id)) != null)
580 progressPanel = (JPanel) progressBars.get(new Long(id));
581 statusPanel.remove(progressPanel);
582 progressBars.remove(progressPanel);
583 progressPanel = null;
586 statusBar.setText(message);
589 layout.setRows(layout.getRows() - 1);
593 progressPanel = new JPanel(new BorderLayout(10, 5));
595 JProgressBar progressBar = new JProgressBar();
596 progressBar.setIndeterminate(true);
598 progressPanel.add(new JLabel(message), BorderLayout.WEST);
599 progressPanel.add(progressBar, BorderLayout.CENTER);
601 layout.setRows(layout.getRows() + 1);
602 statusPanel.add(progressPanel);
604 progressBars.put(new Long(id), progressPanel);
607 setMenusForViewport();
613 * @return true if any progress bars are still active
615 public boolean operationInProgress()
617 if (progressBars != null && progressBars.size() > 0)
625 * Added so Castor Mapping file can obtain Jalview Version
627 public String getVersion()
629 return jalview.bin.Cache.getProperty("VERSION");
632 public FeatureRenderer getFeatureRenderer()
634 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
637 public void fetchSequence_actionPerformed(ActionEvent e)
639 new SequenceFetcher(this);
642 public void addFromFile_actionPerformed(ActionEvent e)
644 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
647 public void reload_actionPerformed(ActionEvent e)
649 if (fileName != null)
651 if (currentFileFormat.equals("Jalview"))
653 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
654 for (int i = 0; i < frames.length; i++)
656 if (frames[i] instanceof AlignFrame && frames[i] != this
657 && ((AlignFrame) frames[i]).fileName.equals(fileName))
661 frames[i].setSelected(true);
662 Desktop.instance.closeAssociatedWindows();
663 } catch (java.beans.PropertyVetoException ex)
669 Desktop.instance.closeAssociatedWindows();
671 FileLoader loader = new FileLoader();
672 String protocol = fileName.startsWith("http:") ? "URL" : "File";
673 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
677 Rectangle bounds = this.getBounds();
679 FileLoader loader = new FileLoader();
680 String protocol = fileName.startsWith("http:") ? "URL" : "File";
681 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
682 protocol, currentFileFormat);
684 newframe.setBounds(bounds);
686 this.closeMenuItem_actionPerformed(true);
691 public void addFromText_actionPerformed(ActionEvent e)
693 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
696 public void addFromURL_actionPerformed(ActionEvent e)
698 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
701 public void save_actionPerformed(ActionEvent e)
704 || (currentFileFormat == null || jalview.io.AppletFormatAdapter
705 .isValidFormat(currentFileFormat, true))
706 || fileName.startsWith("http"))
708 saveAs_actionPerformed(null);
712 saveAlignment(fileName, currentFileFormat);
722 public void saveAs_actionPerformed(ActionEvent e)
724 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
725 .getProperty("LAST_DIRECTORY"),
726 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
727 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
728 currentFileFormat, false);
730 chooser.setFileView(new JalviewFileView());
731 chooser.setDialogTitle("Save Alignment to file");
732 chooser.setToolTipText("Save");
734 int value = chooser.showSaveDialog(this);
736 if (value == JalviewFileChooser.APPROVE_OPTION)
738 currentFileFormat = chooser.getSelectedFormat();
739 if (currentFileFormat == null)
741 JOptionPane.showInternalMessageDialog(Desktop.desktop,
742 "You must select a file format before saving!",
743 "File format not specified", JOptionPane.WARNING_MESSAGE);
744 value = chooser.showSaveDialog(this);
748 fileName = chooser.getSelectedFile().getPath();
750 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
753 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
754 if (currentFileFormat.indexOf(" ") > -1)
756 currentFileFormat = currentFileFormat.substring(0,
757 currentFileFormat.indexOf(" "));
759 saveAlignment(fileName, currentFileFormat);
763 public boolean saveAlignment(String file, String format)
765 boolean success = true;
767 if (format.equalsIgnoreCase("Jalview"))
769 String shortName = title;
771 if (shortName.indexOf(java.io.File.separatorChar) > -1)
773 shortName = shortName.substring(shortName
774 .lastIndexOf(java.io.File.separatorChar) + 1);
777 success = new Jalview2XML().SaveAlignment(this, file, shortName);
779 statusBar.setText("Successfully saved to file: " + fileName + " in "
780 + format + " format.");
785 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
787 // JBPNote need to have a raise_gui flag here
788 JOptionPane.showInternalMessageDialog(this, "Cannot save file "
789 + fileName + " using format " + format,
790 "Alignment output format not supported",
791 JOptionPane.WARNING_MESSAGE);
792 saveAs_actionPerformed(null);
796 String[] omitHidden = null;
798 if (viewport.hasHiddenColumns)
800 int reply = JOptionPane
801 .showInternalConfirmDialog(
803 "The Alignment contains hidden columns."
804 + "\nDo you want to save only the visible alignment?",
805 "Save / Omit Hidden Columns",
806 JOptionPane.YES_NO_OPTION,
807 JOptionPane.QUESTION_MESSAGE);
809 if (reply == JOptionPane.YES_OPTION)
811 omitHidden = viewport.getViewAsString(false);
814 FormatAdapter f = new FormatAdapter();
815 String output = f.formatSequences(format,
816 (Alignment) viewport.alignment, // class cast exceptions will
817 // occur in the distant future
818 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
828 java.io.PrintWriter out = new java.io.PrintWriter(
829 new java.io.FileWriter(file));
834 statusBar.setText("Successfully saved to file: " + fileName
835 + " in " + format + " format.");
836 } catch (Exception ex)
839 ex.printStackTrace();
846 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
847 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
859 protected void outputText_actionPerformed(ActionEvent e)
861 String[] omitHidden = null;
863 if (viewport.hasHiddenColumns)
865 int reply = JOptionPane
866 .showInternalConfirmDialog(
868 "The Alignment contains hidden columns."
869 + "\nDo you want to output only the visible alignment?",
870 "Save / Omit Hidden Columns",
871 JOptionPane.YES_NO_OPTION,
872 JOptionPane.QUESTION_MESSAGE);
874 if (reply == JOptionPane.YES_OPTION)
876 omitHidden = viewport.getViewAsString(false);
880 CutAndPasteTransfer cap = new CutAndPasteTransfer();
881 cap.setForInput(null);
882 Desktop.addInternalFrame(cap, "Alignment output - "
883 + e.getActionCommand(), 600, 500);
885 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
886 viewport.alignment, omitHidden, viewport.colSel));
895 protected void htmlMenuItem_actionPerformed(ActionEvent e)
897 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
898 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
899 .getFeatureRenderer());
902 public void createImageMap(File file, String image)
904 alignPanel.makePNGImageMap(file, image);
913 public void createPNG(File f)
915 alignPanel.makePNG(f);
924 public void createEPS(File f)
926 alignPanel.makeEPS(f);
929 public void pageSetup_actionPerformed(ActionEvent e)
931 PrinterJob printJob = PrinterJob.getPrinterJob();
932 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
941 public void printMenuItem_actionPerformed(ActionEvent e)
943 // Putting in a thread avoids Swing painting problems
944 PrintThread thread = new PrintThread(alignPanel);
948 public void exportFeatures_actionPerformed(ActionEvent e)
950 new AnnotationExporter().exportFeatures(alignPanel);
953 public void exportAnnotations_actionPerformed(ActionEvent e)
955 new AnnotationExporter().exportAnnotations(alignPanel,
956 viewport.showAnnotation ? viewport.alignment
957 .getAlignmentAnnotation() : null, viewport.alignment
959 ((Alignment) viewport.alignment).alignmentProperties);
962 public void associatedData_actionPerformed(ActionEvent e)
964 // Pick the tree file
965 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
966 .getProperty("LAST_DIRECTORY"));
967 chooser.setFileView(new JalviewFileView());
968 chooser.setDialogTitle("Load Jalview Annotations or Features File");
969 chooser.setToolTipText("Load Jalview Annotations / Features file");
971 int value = chooser.showOpenDialog(null);
973 if (value == JalviewFileChooser.APPROVE_OPTION)
975 String choice = chooser.getSelectedFile().getPath();
976 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
977 loadJalviewDataFile(choice);
988 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
990 if (alignPanels != null && alignPanels.size() < 2)
997 if (alignPanels != null)
1001 for (int i = 0; i < alignPanels.size(); i++)
1003 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1004 jalview.structure.StructureSelectionManager
1005 .getStructureSelectionManager()
1006 .removeStructureViewerListener(ap.seqPanel, null);
1007 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
1008 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
1009 PaintRefresher.RemoveComponent(ap);
1010 ap.av.alignment = null;
1015 int index = tabbedPane.getSelectedIndex();
1017 alignPanels.removeElement(alignPanel);
1018 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
1019 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
1020 PaintRefresher.RemoveComponent(alignPanel);
1021 viewport.alignment = null;
1025 tabbedPane.removeTabAt(index);
1026 tabbedPane.validate();
1028 if (index == tabbedPane.getTabCount())
1033 this.tabSelectionChanged(index);
1039 this.setClosed(true);
1041 } catch (Exception ex)
1043 ex.printStackTrace();
1050 void updateEditMenuBar()
1053 if (viewport.historyList.size() > 0)
1055 undoMenuItem.setEnabled(true);
1056 CommandI command = (CommandI) viewport.historyList.peek();
1057 undoMenuItem.setText("Undo " + command.getDescription());
1061 undoMenuItem.setEnabled(false);
1062 undoMenuItem.setText("Undo");
1065 if (viewport.redoList.size() > 0)
1067 redoMenuItem.setEnabled(true);
1069 CommandI command = (CommandI) viewport.redoList.peek();
1070 redoMenuItem.setText("Redo " + command.getDescription());
1074 redoMenuItem.setEnabled(false);
1075 redoMenuItem.setText("Redo");
1079 public void addHistoryItem(CommandI command)
1081 if (command.getSize() > 0)
1083 viewport.historyList.push(command);
1084 viewport.redoList.clear();
1085 updateEditMenuBar();
1086 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1092 * @return alignment objects for all views
1094 AlignmentI[] getViewAlignments()
1096 if (alignPanels != null)
1098 Enumeration e = alignPanels.elements();
1099 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1100 for (int i = 0; e.hasMoreElements(); i++)
1102 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1106 if (viewport != null)
1108 return new AlignmentI[]
1109 { viewport.alignment };
1120 protected void undoMenuItem_actionPerformed(ActionEvent e)
1122 if (viewport.historyList.empty())
1124 CommandI command = (CommandI) viewport.historyList.pop();
1125 viewport.redoList.push(command);
1126 command.undoCommand(getViewAlignments());
1128 AlignViewport originalSource = getOriginatingSource(command);
1129 updateEditMenuBar();
1131 if (originalSource != null)
1133 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1134 originalSource.firePropertyChange("alignment", null,
1135 originalSource.alignment.getSequences());
1145 protected void redoMenuItem_actionPerformed(ActionEvent e)
1147 if (viewport.redoList.size() < 1)
1152 CommandI command = (CommandI) viewport.redoList.pop();
1153 viewport.historyList.push(command);
1154 command.doCommand(getViewAlignments());
1156 AlignViewport originalSource = getOriginatingSource(command);
1157 updateEditMenuBar();
1159 if (originalSource != null)
1161 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1162 originalSource.firePropertyChange("alignment", null,
1163 originalSource.alignment.getSequences());
1167 AlignViewport getOriginatingSource(CommandI command)
1169 AlignViewport originalSource = null;
1170 // For sequence removal and addition, we need to fire
1171 // the property change event FROM the viewport where the
1172 // original alignment was altered
1173 AlignmentI al = null;
1174 if (command instanceof EditCommand)
1176 EditCommand editCommand = (EditCommand) command;
1177 al = editCommand.getAlignment();
1178 Vector comps = (Vector) PaintRefresher.components.get(viewport
1179 .getSequenceSetId());
1181 for (int i = 0; i < comps.size(); i++)
1183 if (comps.elementAt(i) instanceof AlignmentPanel)
1185 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1187 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1194 if (originalSource == null)
1196 // The original view is closed, we must validate
1197 // the current view against the closed view first
1200 PaintRefresher.validateSequences(al, viewport.alignment);
1203 originalSource = viewport;
1206 return originalSource;
1215 public void moveSelectedSequences(boolean up)
1217 SequenceGroup sg = viewport.getSelectionGroup();
1226 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1228 SequenceI seq = viewport.alignment.getSequenceAt(i);
1230 if (!sg.getSequences(null).contains(seq))
1235 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1237 if (sg.getSequences(null).contains(temp))
1242 viewport.alignment.getSequences().setElementAt(temp, i);
1243 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1248 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1250 SequenceI seq = viewport.alignment.getSequenceAt(i);
1252 if (!sg.getSequences(null).contains(seq))
1257 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1259 if (sg.getSequences(null).contains(temp))
1264 viewport.alignment.getSequences().setElementAt(temp, i);
1265 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1269 alignPanel.paintAlignment(true);
1272 synchronized void slideSequences(boolean right, int size)
1274 Vector sg = new Vector();
1275 if (viewport.cursorMode)
1277 sg.addElement(viewport.alignment
1278 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1280 else if (viewport.getSelectionGroup() != null
1281 && viewport.getSelectionGroup().getSize() != viewport.alignment
1284 sg = viewport.getSelectionGroup().getSequences(
1285 viewport.hiddenRepSequences);
1293 Vector invertGroup = new Vector();
1295 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1297 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1298 invertGroup.add(viewport.alignment.getSequenceAt(i));
1301 SequenceI[] seqs1 = new SequenceI[sg.size()];
1302 for (int i = 0; i < sg.size(); i++)
1303 seqs1[i] = (SequenceI) sg.elementAt(i);
1305 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1306 for (int i = 0; i < invertGroup.size(); i++)
1307 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1309 SlideSequencesCommand ssc;
1311 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1312 size, viewport.getGapCharacter());
1314 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1315 size, viewport.getGapCharacter());
1317 int groupAdjustment = 0;
1318 if (ssc.getGapsInsertedBegin() && right)
1320 if (viewport.cursorMode)
1321 alignPanel.seqPanel.moveCursor(size, 0);
1323 groupAdjustment = size;
1325 else if (!ssc.getGapsInsertedBegin() && !right)
1327 if (viewport.cursorMode)
1328 alignPanel.seqPanel.moveCursor(-size, 0);
1330 groupAdjustment = -size;
1333 if (groupAdjustment != 0)
1335 viewport.getSelectionGroup().setStartRes(
1336 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1337 viewport.getSelectionGroup().setEndRes(
1338 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1341 boolean appendHistoryItem = false;
1342 if (viewport.historyList != null && viewport.historyList.size() > 0
1343 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1345 appendHistoryItem = ssc
1346 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1350 if (!appendHistoryItem)
1351 addHistoryItem(ssc);
1362 protected void copy_actionPerformed(ActionEvent e)
1365 if (viewport.getSelectionGroup() == null)
1369 // TODO: preserve the ordering of displayed alignment annotation in any
1370 // internal paste (particularly sequence associated annotation)
1371 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1372 String[] omitHidden = null;
1374 if (viewport.hasHiddenColumns)
1376 omitHidden = viewport.getViewAsString(true);
1379 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1382 StringSelection ss = new StringSelection(output);
1386 jalview.gui.Desktop.internalCopy = true;
1387 // Its really worth setting the clipboard contents
1388 // to empty before setting the large StringSelection!!
1389 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1390 new StringSelection(""), null);
1392 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1394 } catch (OutOfMemoryError er)
1396 new OOMWarning("copying region", er);
1400 Vector hiddenColumns = null;
1401 if (viewport.hasHiddenColumns)
1403 hiddenColumns = new Vector();
1404 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1405 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1408 int[] region = (int[]) viewport.getColumnSelection()
1409 .getHiddenColumns().elementAt(i);
1411 hiddenColumns.addElement(new int[]
1412 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1416 Desktop.jalviewClipboard = new Object[]
1417 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1418 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1427 protected void pasteNew_actionPerformed(ActionEvent e)
1438 protected void pasteThis_actionPerformed(ActionEvent e)
1444 * Paste contents of Jalview clipboard
1446 * @param newAlignment
1447 * true to paste to a new alignment, otherwise add to this.
1449 void paste(boolean newAlignment)
1451 boolean externalPaste = true;
1454 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1455 Transferable contents = c.getContents(this);
1457 if (contents == null)
1465 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1466 if (str.length() < 1)
1471 format = new IdentifyFile().Identify(str, "Paste");
1473 } catch (OutOfMemoryError er)
1475 new OOMWarning("Out of memory pasting sequences!!", er);
1479 SequenceI[] sequences;
1480 boolean annotationAdded = false;
1481 AlignmentI alignment = null;
1483 if (Desktop.jalviewClipboard != null)
1485 // The clipboard was filled from within Jalview, we must use the
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++)
1493 sequences[i] = new Sequence(newseq[i]);
1495 alignment = new Alignment(sequences);
1496 externalPaste = false;
1500 // parse the clipboard as an alignment.
1501 alignment = new FormatAdapter().readFile(str, "Paste", format);
1502 sequences = alignment.getSequencesArray();
1510 if (Desktop.jalviewClipboard != null)
1512 // dataset is inherited
1513 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1517 // new dataset is constructed
1518 alignment.setDataset(null);
1520 alwidth = alignment.getWidth() + 1;
1524 AlignmentI pastedal = alignment; // preserve pasted alignment object
1525 // Add pasted sequences and dataset into existing alignment.
1526 alignment = viewport.getAlignment();
1527 alwidth = alignment.getWidth() + 1;
1528 // decide if we need to import sequences from an existing dataset
1529 boolean importDs = Desktop.jalviewClipboard != null
1530 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1531 // importDs==true instructs us to copy over new dataset sequences from
1532 // an existing alignment
1533 Vector newDs = (importDs) ? new Vector() : null; // used to create
1534 // minimum dataset set
1536 for (int i = 0; i < sequences.length; i++)
1540 newDs.addElement(null);
1542 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1544 if (importDs && ds != null)
1546 if (!newDs.contains(ds))
1548 newDs.setElementAt(ds, i);
1549 ds = new Sequence(ds);
1550 // update with new dataset sequence
1551 sequences[i].setDatasetSequence(ds);
1555 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1560 // copy and derive new dataset sequence
1561 sequences[i] = sequences[i].deriveSequence();
1562 alignment.getDataset().addSequence(
1563 sequences[i].getDatasetSequence());
1564 // TODO: avoid creation of duplicate dataset sequences with a
1565 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1567 alignment.addSequence(sequences[i]); // merges dataset
1571 newDs.clear(); // tidy up
1573 if (pastedal.getAlignmentAnnotation() != null)
1575 // Add any annotation attached to alignment.
1576 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1577 for (int i = 0; i < alann.length; i++)
1579 annotationAdded = true;
1580 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1582 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1583 newann.padAnnotation(alwidth);
1584 alignment.addAnnotation(newann);
1594 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1595 sequences, 0, alignment.getWidth(), alignment));
1597 // Add any annotations attached to sequences
1598 for (int i = 0; i < sequences.length; i++)
1600 if (sequences[i].getAnnotation() != null)
1602 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1604 annotationAdded = true;
1605 sequences[i].getAnnotation()[a].adjustForAlignment();
1606 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1607 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1612 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1619 // propagate alignment changed.
1620 viewport.setEndSeq(alignment.getHeight());
1621 if (annotationAdded)
1623 // Duplicate sequence annotation in all views.
1624 AlignmentI[] alview = this.getViewAlignments();
1625 for (int i = 0; i < sequences.length; i++)
1627 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1630 for (int avnum = 0; avnum < alview.length; avnum++)
1632 if (alview[avnum] != alignment)
1634 // duplicate in a view other than the one with input focus
1635 int avwidth = alview[avnum].getWidth() + 1;
1636 // this relies on sann being preserved after we
1637 // modify the sequence's annotation array for each duplication
1638 for (int a = 0; a < sann.length; a++)
1640 AlignmentAnnotation newann = new AlignmentAnnotation(
1642 sequences[i].addAlignmentAnnotation(newann);
1643 newann.padAnnotation(avwidth);
1644 alview[avnum].addAnnotation(newann); // annotation was
1645 // duplicated earlier
1646 alview[avnum].setAnnotationIndex(newann, a);
1651 buildSortByAnnotationScoresMenu();
1653 viewport.firePropertyChange("alignment", null, alignment
1659 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1661 String newtitle = new String("Copied sequences");
1663 if (Desktop.jalviewClipboard != null
1664 && Desktop.jalviewClipboard[2] != null)
1666 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1667 for (int i = 0; i < hc.size(); i++)
1669 int[] region = (int[]) hc.elementAt(i);
1670 af.viewport.hideColumns(region[0], region[1]);
1674 // >>>This is a fix for the moment, until a better solution is
1676 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1678 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1680 // TODO: maintain provenance of an alignment, rather than just make the
1681 // title a concatenation of operations.
1684 if (title.startsWith("Copied sequences"))
1690 newtitle = newtitle.concat("- from " + title);
1695 newtitle = new String("Pasted sequences");
1698 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1703 } catch (Exception ex)
1705 ex.printStackTrace();
1706 System.out.println("Exception whilst pasting: " + ex);
1707 // could be anything being pasted in here
1718 protected void cut_actionPerformed(ActionEvent e)
1720 copy_actionPerformed(null);
1721 delete_actionPerformed(null);
1730 protected void delete_actionPerformed(ActionEvent evt)
1733 SequenceGroup sg = viewport.getSelectionGroup();
1739 Vector seqs = new Vector();
1741 for (int i = 0; i < sg.getSize(); i++)
1743 seq = sg.getSequenceAt(i);
1744 seqs.addElement(seq);
1747 // If the cut affects all sequences, remove highlighted columns
1748 if (sg.getSize() == viewport.alignment.getHeight())
1750 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1751 sg.getEndRes() + 1);
1754 SequenceI[] cut = new SequenceI[seqs.size()];
1755 for (int i = 0; i < seqs.size(); i++)
1757 cut[i] = (SequenceI) seqs.elementAt(i);
1761 * //ADD HISTORY ITEM
1763 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1764 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1765 viewport.alignment));
1767 viewport.setSelectionGroup(null);
1768 viewport.alignment.deleteGroup(sg);
1770 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1773 if (viewport.getAlignment().getHeight() < 1)
1777 this.setClosed(true);
1778 } catch (Exception ex)
1790 protected void deleteGroups_actionPerformed(ActionEvent e)
1792 viewport.alignment.deleteAllGroups();
1793 viewport.sequenceColours = null;
1794 viewport.setSelectionGroup(null);
1795 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1796 alignPanel.paintAlignment(true);
1805 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1807 SequenceGroup sg = new SequenceGroup();
1809 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1811 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1814 sg.setEndRes(viewport.alignment.getWidth() - 1);
1815 viewport.setSelectionGroup(sg);
1816 alignPanel.paintAlignment(true);
1817 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1826 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1828 if (viewport.cursorMode)
1830 alignPanel.seqPanel.keyboardNo1 = null;
1831 alignPanel.seqPanel.keyboardNo2 = null;
1833 viewport.setSelectionGroup(null);
1834 viewport.getColumnSelection().clear();
1835 viewport.setSelectionGroup(null);
1836 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1837 alignPanel.idPanel.idCanvas.searchResults = null;
1838 alignPanel.paintAlignment(true);
1839 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1848 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1850 SequenceGroup sg = viewport.getSelectionGroup();
1854 selectAllSequenceMenuItem_actionPerformed(null);
1859 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1861 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1864 alignPanel.paintAlignment(true);
1866 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1869 public void invertColSel_actionPerformed(ActionEvent e)
1871 viewport.invertColumnSelection();
1872 alignPanel.paintAlignment(true);
1881 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1883 trimAlignment(true);
1892 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1894 trimAlignment(false);
1897 void trimAlignment(boolean trimLeft)
1899 ColumnSelection colSel = viewport.getColumnSelection();
1902 if (colSel.size() > 0)
1906 column = colSel.getMin();
1910 column = colSel.getMax();
1914 if (viewport.getSelectionGroup() != null)
1916 seqs = viewport.getSelectionGroup().getSequencesAsArray(
1917 viewport.hiddenRepSequences);
1921 seqs = viewport.alignment.getSequencesArray();
1924 TrimRegionCommand trimRegion;
1927 trimRegion = new TrimRegionCommand("Remove Left",
1928 TrimRegionCommand.TRIM_LEFT, seqs, column,
1929 viewport.alignment, viewport.colSel,
1930 viewport.selectionGroup);
1931 viewport.setStartRes(0);
1935 trimRegion = new TrimRegionCommand("Remove Right",
1936 TrimRegionCommand.TRIM_RIGHT, seqs, column,
1937 viewport.alignment, viewport.colSel,
1938 viewport.selectionGroup);
1941 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
1943 addHistoryItem(trimRegion);
1945 Vector groups = viewport.alignment.getGroups();
1947 for (int i = 0; i < groups.size(); i++)
1949 SequenceGroup sg = (SequenceGroup) groups.get(i);
1951 if ((trimLeft && !sg.adjustForRemoveLeft(column))
1952 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1954 viewport.alignment.deleteGroup(sg);
1958 viewport.firePropertyChange("alignment", null, viewport
1959 .getAlignment().getSequences());
1969 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1971 int start = 0, end = viewport.alignment.getWidth() - 1;
1974 if (viewport.getSelectionGroup() != null)
1976 seqs = viewport.getSelectionGroup().getSequencesAsArray(
1977 viewport.hiddenRepSequences);
1978 start = viewport.getSelectionGroup().getStartRes();
1979 end = viewport.getSelectionGroup().getEndRes();
1983 seqs = viewport.alignment.getSequencesArray();
1986 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
1987 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
1989 addHistoryItem(removeGapCols);
1991 statusBar.setText("Removed " + removeGapCols.getSize()
1992 + " empty columns.");
1994 // This is to maintain viewport position on first residue
1995 // of first sequence
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, viewport.getAlignment()
2015 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2017 int start = 0, end = viewport.alignment.getWidth() - 1;
2020 if (viewport.getSelectionGroup() != null)
2022 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2023 viewport.hiddenRepSequences);
2024 start = viewport.getSelectionGroup().getStartRes();
2025 end = viewport.getSelectionGroup().getEndRes();
2029 seqs = viewport.alignment.getSequencesArray();
2032 // This is to maintain viewport position on first residue
2033 // of first sequence
2034 SequenceI seq = viewport.alignment.getSequenceAt(0);
2035 int startRes = seq.findPosition(viewport.startRes);
2037 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2038 viewport.alignment));
2040 viewport.setStartRes(seq.findIndex(startRes) - 1);
2042 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2053 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2055 viewport.padGaps = padGapsMenuitem.isSelected();
2057 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2067 public void findMenuItem_actionPerformed(ActionEvent e)
2072 public void newView_actionPerformed(ActionEvent e)
2074 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
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);
2137 public void font_actionPerformed(ActionEvent e)
2139 new FontChooser(alignPanel);
2148 protected void seqLimit_actionPerformed(ActionEvent e)
2150 viewport.setShowJVSuffix(seqLimits.isSelected());
2152 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2153 .calculateIdWidth());
2154 alignPanel.paintAlignment(true);
2157 public void idRightAlign_actionPerformed(ActionEvent e)
2159 viewport.rightAlignIds = idRightAlign.isSelected();
2160 alignPanel.paintAlignment(true);
2163 public void centreColumnLabels_actionPerformed(ActionEvent e)
2165 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2166 alignPanel.paintAlignment(true);
2175 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2177 viewport.setColourText(colourTextMenuItem.isSelected());
2178 alignPanel.paintAlignment(true);
2187 public void wrapMenuItem_actionPerformed(ActionEvent e)
2189 scaleAbove.setVisible(wrapMenuItem.isSelected());
2190 scaleLeft.setVisible(wrapMenuItem.isSelected());
2191 scaleRight.setVisible(wrapMenuItem.isSelected());
2192 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2193 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2196 public void showAllSeqs_actionPerformed(ActionEvent e)
2198 viewport.showAllHiddenSeqs();
2201 public void showAllColumns_actionPerformed(ActionEvent e)
2203 viewport.showAllHiddenColumns();
2207 public void hideSelSequences_actionPerformed(ActionEvent e)
2209 viewport.hideAllSelectedSeqs();
2210 alignPanel.paintAlignment(true);
2213 public void hideSelColumns_actionPerformed(ActionEvent e)
2215 viewport.hideSelectedColumns();
2216 alignPanel.paintAlignment(true);
2219 public void hiddenMarkers_actionPerformed(ActionEvent e)
2221 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2231 protected void scaleAbove_actionPerformed(ActionEvent e)
2233 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2234 alignPanel.paintAlignment(true);
2243 protected void scaleLeft_actionPerformed(ActionEvent e)
2245 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2246 alignPanel.paintAlignment(true);
2255 protected void scaleRight_actionPerformed(ActionEvent e)
2257 viewport.setScaleRightWrapped(scaleRight.isSelected());
2258 alignPanel.paintAlignment(true);
2267 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2269 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2270 alignPanel.paintAlignment(true);
2279 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2281 viewport.setShowText(viewTextMenuItem.isSelected());
2282 alignPanel.paintAlignment(true);
2291 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2293 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2294 alignPanel.paintAlignment(true);
2297 public FeatureSettings featureSettings;
2299 public void featureSettings_actionPerformed(ActionEvent e)
2301 if (featureSettings != null)
2303 featureSettings.close();
2304 featureSettings = null;
2306 featureSettings = new FeatureSettings(this);
2315 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2317 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2318 alignPanel.paintAlignment(true);
2319 if (alignPanel.getOverviewPanel() != null)
2321 alignPanel.getOverviewPanel().updateOverviewImage();
2331 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2333 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2334 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2337 public void alignmentProperties()
2339 JEditorPane editPane = new JEditorPane("text/html", "");
2340 editPane.setEditable(false);
2341 StringBuffer contents = new StringBuffer("<html>");
2344 int min = Integer.MAX_VALUE, max = 0;
2345 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2347 int size = viewport.alignment.getSequenceAt(i).getEnd()
2348 - viewport.alignment.getSequenceAt(i).getStart();
2355 avg = avg / (float) viewport.alignment.getHeight();
2357 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2358 contents.append("<br>Minimum Sequence Length: " + min);
2359 contents.append("<br>Maximum Sequence Length: " + max);
2360 contents.append("<br>Average Length: " + (int) avg);
2362 if (((Alignment) viewport.alignment).getProperties() != null)
2364 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2365 Enumeration en = props.keys();
2366 contents.append("<br><br><table border=\"1\">");
2367 while (en.hasMoreElements())
2369 String key = en.nextElement().toString();
2370 StringBuffer val = new StringBuffer();
2371 String vals = props.get(key).toString();
2375 npos = vals.indexOf("\n", pos);
2378 val.append(vals.substring(pos));
2382 val.append(vals.substring(pos, npos));
2386 } while (npos != -1);
2388 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2390 contents.append("</table>");
2392 editPane.setText(contents.toString() + "</html>");
2393 JInternalFrame frame = new JInternalFrame();
2394 frame.getContentPane().add(new JScrollPane(editPane));
2396 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2397 + getTitle(), 500, 400);
2406 public void overviewMenuItem_actionPerformed(ActionEvent e)
2408 if (alignPanel.overviewPanel != null)
2413 JInternalFrame frame = new JInternalFrame();
2414 OverviewPanel overview = new OverviewPanel(alignPanel);
2415 frame.setContentPane(overview);
2416 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2417 .getWidth(), frame.getHeight());
2419 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2421 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2423 public void internalFrameClosed(
2424 javax.swing.event.InternalFrameEvent evt)
2426 alignPanel.setOverviewPanel(null);
2430 alignPanel.setOverviewPanel(overview);
2433 public void textColour_actionPerformed(ActionEvent e)
2435 new TextColourChooser().chooseColour(alignPanel, null);
2444 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2455 public void clustalColour_actionPerformed(ActionEvent e)
2457 changeColour(new ClustalxColourScheme(
2458 viewport.alignment.getSequences(), viewport.alignment
2468 public void zappoColour_actionPerformed(ActionEvent e)
2470 changeColour(new ZappoColourScheme());
2479 public void taylorColour_actionPerformed(ActionEvent e)
2481 changeColour(new TaylorColourScheme());
2490 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2492 changeColour(new HydrophobicColourScheme());
2501 public void helixColour_actionPerformed(ActionEvent e)
2503 changeColour(new HelixColourScheme());
2512 public void strandColour_actionPerformed(ActionEvent e)
2514 changeColour(new StrandColourScheme());
2523 public void turnColour_actionPerformed(ActionEvent e)
2525 changeColour(new TurnColourScheme());
2534 public void buriedColour_actionPerformed(ActionEvent e)
2536 changeColour(new BuriedColourScheme());
2545 public void nucleotideColour_actionPerformed(ActionEvent e)
2547 changeColour(new NucleotideColourScheme());
2550 public void annotationColour_actionPerformed(ActionEvent e)
2552 new AnnotationColourChooser(viewport, alignPanel);
2561 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2563 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2572 public void changeColour(ColourSchemeI cs)
2578 if (viewport.getAbovePIDThreshold())
2580 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2583 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2585 viewport.setGlobalColourScheme(cs);
2589 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2592 if (viewport.getConservationSelected())
2595 Alignment al = (Alignment) viewport.alignment;
2596 Conservation c = new Conservation("All",
2597 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2601 c.verdict(false, viewport.ConsPercGaps);
2603 cs.setConservation(c);
2605 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2610 cs.setConservation(null);
2613 cs.setConsensus(viewport.hconsensus);
2616 viewport.setGlobalColourScheme(cs);
2618 if (viewport.getColourAppliesToAllGroups())
2620 Vector groups = viewport.alignment.getGroups();
2622 for (int i = 0; i < groups.size(); i++)
2624 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2632 if (cs instanceof ClustalxColourScheme)
2634 sg.cs = new ClustalxColourScheme(sg
2635 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2637 else if (cs instanceof UserColourScheme)
2639 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2645 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2646 } catch (Exception ex)
2651 if (viewport.getAbovePIDThreshold()
2652 || cs instanceof PIDColourScheme
2653 || cs instanceof Blosum62ColourScheme)
2655 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2657 sg.cs.setConsensus(AAFrequency.calculate(sg
2658 .getSequences(viewport.hiddenRepSequences), sg
2659 .getStartRes(), sg.getEndRes() + 1));
2663 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2666 if (viewport.getConservationSelected())
2668 Conservation c = new Conservation("Group",
2669 ResidueProperties.propHash, 3, sg
2670 .getSequences(viewport.hiddenRepSequences), sg
2671 .getStartRes(), sg.getEndRes() + 1);
2673 c.verdict(false, viewport.ConsPercGaps);
2674 sg.cs.setConservation(c);
2678 sg.cs.setConservation(null);
2683 if (alignPanel.getOverviewPanel() != null)
2685 alignPanel.getOverviewPanel().updateOverviewImage();
2688 alignPanel.paintAlignment(true);
2697 protected void modifyPID_actionPerformed(ActionEvent e)
2699 if (viewport.getAbovePIDThreshold()
2700 && viewport.globalColourScheme != null)
2702 SliderPanel.setPIDSliderSource(alignPanel, viewport
2703 .getGlobalColourScheme(), "Background");
2704 SliderPanel.showPIDSlider();
2714 protected void modifyConservation_actionPerformed(ActionEvent e)
2716 if (viewport.getConservationSelected()
2717 && viewport.globalColourScheme != null)
2719 SliderPanel.setConservationSlider(alignPanel,
2720 viewport.globalColourScheme, "Background");
2721 SliderPanel.showConservationSlider();
2731 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2733 viewport.setConservationSelected(conservationMenuItem.isSelected());
2735 viewport.setAbovePIDThreshold(false);
2736 abovePIDThreshold.setSelected(false);
2738 changeColour(viewport.getGlobalColourScheme());
2740 modifyConservation_actionPerformed(null);
2749 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2751 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2753 conservationMenuItem.setSelected(false);
2754 viewport.setConservationSelected(false);
2756 changeColour(viewport.getGlobalColourScheme());
2758 modifyPID_actionPerformed(null);
2767 public void userDefinedColour_actionPerformed(ActionEvent e)
2769 if (e.getActionCommand().equals("User Defined..."))
2771 new UserDefinedColours(alignPanel, null);
2775 UserColourScheme udc = (UserColourScheme) UserDefinedColours
2776 .getUserColourSchemes().get(e.getActionCommand());
2782 public void updateUserColourMenu()
2785 Component[] menuItems = colourMenu.getMenuComponents();
2786 int i, iSize = menuItems.length;
2787 for (i = 0; i < iSize; i++)
2789 if (menuItems[i].getName() != null
2790 && menuItems[i].getName().equals("USER_DEFINED"))
2792 colourMenu.remove(menuItems[i]);
2796 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2798 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
2799 .getUserColourSchemes().keys();
2801 while (userColours.hasMoreElements())
2803 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2804 userColours.nextElement().toString());
2805 radioItem.setName("USER_DEFINED");
2806 radioItem.addMouseListener(new MouseAdapter()
2808 public void mousePressed(MouseEvent evt)
2810 if (evt.isControlDown()
2811 || SwingUtilities.isRightMouseButton(evt))
2814 .removeActionListener(radioItem.getActionListeners()[0]);
2816 int option = JOptionPane.showInternalConfirmDialog(
2817 jalview.gui.Desktop.desktop,
2818 "Remove from default list?",
2819 "Remove user defined colour",
2820 JOptionPane.YES_NO_OPTION);
2821 if (option == JOptionPane.YES_OPTION)
2823 jalview.gui.UserDefinedColours
2824 .removeColourFromDefaults(radioItem.getText());
2825 colourMenu.remove(radioItem);
2829 radioItem.addActionListener(new ActionListener()
2831 public void actionPerformed(ActionEvent evt)
2833 userDefinedColour_actionPerformed(evt);
2840 radioItem.addActionListener(new ActionListener()
2842 public void actionPerformed(ActionEvent evt)
2844 userDefinedColour_actionPerformed(evt);
2848 colourMenu.insert(radioItem, 15);
2849 colours.add(radioItem);
2860 public void PIDColour_actionPerformed(ActionEvent e)
2862 changeColour(new PIDColourScheme());
2871 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2873 changeColour(new Blosum62ColourScheme());
2882 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2884 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2885 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
2886 .getAlignment().getSequenceAt(0), null);
2887 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2888 viewport.alignment));
2889 alignPanel.paintAlignment(true);
2898 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2900 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2901 AlignmentSorter.sortByID(viewport.getAlignment());
2902 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2903 alignPanel.paintAlignment(true);
2912 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2914 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2915 AlignmentSorter.sortByGroup(viewport.getAlignment());
2916 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
2917 viewport.alignment));
2919 alignPanel.paintAlignment(true);
2928 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2930 new RedundancyPanel(alignPanel, this);
2939 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2941 if ((viewport.getSelectionGroup() == null)
2942 || (viewport.getSelectionGroup().getSize() < 2))
2944 JOptionPane.showInternalMessageDialog(this,
2945 "You must select at least 2 sequences.", "Invalid Selection",
2946 JOptionPane.WARNING_MESSAGE);
2950 JInternalFrame frame = new JInternalFrame();
2951 frame.setContentPane(new PairwiseAlignPanel(viewport));
2952 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2962 public void PCAMenuItem_actionPerformed(ActionEvent e)
2964 if (((viewport.getSelectionGroup() != null)
2965 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
2966 .getSelectionGroup().getSize() > 0))
2967 || (viewport.getAlignment().getHeight() < 4))
2969 JOptionPane.showInternalMessageDialog(this,
2970 "Principal component analysis must take\n"
2971 + "at least 4 input sequences.",
2972 "Sequence selection insufficient",
2973 JOptionPane.WARNING_MESSAGE);
2978 new PCAPanel(alignPanel);
2981 public void autoCalculate_actionPerformed(ActionEvent e)
2983 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2984 if (viewport.autoCalculateConsensus)
2986 viewport.firePropertyChange("alignment", null, viewport
2987 .getAlignment().getSequences());
2997 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2999 NewTreePanel("AV", "PID", "Average distance tree using PID");
3008 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3010 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3019 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3021 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3030 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3032 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3045 void NewTreePanel(String type, String pwType, String title)
3049 if (viewport.getSelectionGroup() != null)
3051 if (viewport.getSelectionGroup().getSize() < 3)
3056 "You need to have more than two sequences selected to build a tree!",
3057 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3062 SequenceGroup sg = viewport.getSelectionGroup();
3064 /* Decide if the selection is a column region */
3065 while (s < sg.getSize())
3067 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3073 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3074 + "Try using the Pad function in the edit menu,\n"
3075 + "or one of the multiple sequence alignment web services.",
3076 "Sequences in selection are not aligned",
3077 JOptionPane.WARNING_MESSAGE);
3083 title = title + " on region";
3084 tp = new TreePanel(alignPanel, type, pwType);
3088 // are the sequences aligned?
3089 if (!viewport.alignment.isAligned())
3094 "The sequences must be aligned before creating a tree.\n"
3095 + "Try using the Pad function in the edit menu,\n"
3096 + "or one of the multiple sequence alignment web services.",
3097 "Sequences not aligned",
3098 JOptionPane.WARNING_MESSAGE);
3103 if (viewport.alignment.getHeight() < 2)
3108 tp = new TreePanel(alignPanel, type, pwType);
3113 if (viewport.viewName != null)
3115 title += viewport.viewName + " of ";
3118 title += this.title;
3120 Desktop.addInternalFrame(tp, title, 600, 500);
3131 public void addSortByOrderMenuItem(String title,
3132 final AlignmentOrder order)
3134 final JMenuItem item = new JMenuItem("by " + title);
3136 item.addActionListener(new java.awt.event.ActionListener()
3138 public void actionPerformed(ActionEvent e)
3140 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3142 // TODO: JBPNote - have to map order entries to curent SequenceI
3144 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3146 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3147 viewport.alignment));
3149 alignPanel.paintAlignment(true);
3155 * Add a new sort by annotation score menu item
3158 * the menu to add the option to
3160 * the label used to retrieve scores for each sequence on the
3163 public void addSortByAnnotScoreMenuItem(JMenu sort,
3164 final String scoreLabel)
3166 final JMenuItem item = new JMenuItem(scoreLabel);
3168 item.addActionListener(new java.awt.event.ActionListener()
3170 public void actionPerformed(ActionEvent e)
3172 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3173 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3174 .getAlignment());// ,viewport.getSelectionGroup());
3175 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3176 viewport.alignment));
3177 alignPanel.paintAlignment(true);
3183 * last hash for alignment's annotation array - used to minimise cost of
3186 protected int _annotationScoreVectorHash;
3189 * search the alignment and rebuild the sort by annotation score submenu the
3190 * last alignment annotation vector hash is stored to minimize cost of
3191 * rebuilding in subsequence calls.
3194 public void buildSortByAnnotationScoresMenu()
3196 if (viewport.alignment.getAlignmentAnnotation() == null)
3201 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3203 sortByAnnotScore.removeAll();
3204 // almost certainly a quicker way to do this - but we keep it simple
3205 Hashtable scoreSorts = new Hashtable();
3206 AlignmentAnnotation aann[];
3207 Enumeration sq = viewport.alignment.getSequences().elements();
3208 while (sq.hasMoreElements())
3210 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3211 for (int i = 0; aann != null && i < aann.length; i++)
3213 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3215 scoreSorts.put(aann[i].label, aann[i].label);
3219 Enumeration labels = scoreSorts.keys();
3220 while (labels.hasMoreElements())
3222 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3225 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3228 _annotationScoreVectorHash = viewport.alignment
3229 .getAlignmentAnnotation().hashCode();
3234 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3235 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3236 * call. Listeners are added to remove the menu item when the treePanel is
3237 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3241 * Displayed tree window.
3243 * SortBy menu item title.
3245 public void buildTreeMenu()
3247 sortByTreeMenu.removeAll();
3249 Vector comps = (Vector) PaintRefresher.components.get(viewport
3250 .getSequenceSetId());
3251 Vector treePanels = new Vector();
3252 int i, iSize = comps.size();
3253 for (i = 0; i < iSize; i++)
3255 if (comps.elementAt(i) instanceof TreePanel)
3257 treePanels.add(comps.elementAt(i));
3261 iSize = treePanels.size();
3265 sortByTreeMenu.setVisible(false);
3269 sortByTreeMenu.setVisible(true);
3271 for (i = 0; i < treePanels.size(); i++)
3273 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3274 final JMenuItem item = new JMenuItem(tp.getTitle());
3275 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3276 item.addActionListener(new java.awt.event.ActionListener()
3278 public void actionPerformed(ActionEvent e)
3280 SequenceI[] oldOrder = viewport.getAlignment()
3281 .getSequencesArray();
3282 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3284 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3285 viewport.alignment));
3287 alignPanel.paintAlignment(true);
3291 sortByTreeMenu.add(item);
3296 * Work out whether the whole set of sequences or just the selected set will
3297 * be submitted for multiple alignment.
3300 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3302 // Now, check we have enough sequences
3303 AlignmentView msa = null;
3305 if ((viewport.getSelectionGroup() != null)
3306 && (viewport.getSelectionGroup().getSize() > 1))
3308 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3309 // some common interface!
3311 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3312 * SequenceI[sz = seqs.getSize(false)];
3314 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3315 * seqs.getSequenceAt(i); }
3317 msa = viewport.getAlignmentView(true);
3322 * Vector seqs = viewport.getAlignment().getSequences();
3324 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3326 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3327 * seqs.elementAt(i); } }
3329 msa = viewport.getAlignmentView(false);
3335 * Decides what is submitted to a secondary structure prediction service: the
3336 * first sequence in the alignment, or in the current selection, or, if the
3337 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3338 * region or the whole alignment. (where the first sequence in the set is the
3339 * one that the prediction will be for).
3341 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3343 AlignmentView seqs = null;
3345 if ((viewport.getSelectionGroup() != null)
3346 && (viewport.getSelectionGroup().getSize() > 0))
3348 seqs = viewport.getAlignmentView(true);
3352 seqs = viewport.getAlignmentView(false);
3354 // limit sequences - JBPNote in future - could spawn multiple prediction
3356 // TODO: viewport.alignment.isAligned is a global state - the local
3357 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3358 if (!viewport.alignment.isAligned())
3360 seqs.setSequences(new SeqCigar[]
3361 { seqs.getSequences()[0] });
3372 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3374 // Pick the tree file
3375 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3376 .getProperty("LAST_DIRECTORY"));
3377 chooser.setFileView(new JalviewFileView());
3378 chooser.setDialogTitle("Select a newick-like tree file");
3379 chooser.setToolTipText("Load a tree file");
3381 int value = chooser.showOpenDialog(null);
3383 if (value == JalviewFileChooser.APPROVE_OPTION)
3385 String choice = chooser.getSelectedFile().getPath();
3386 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3387 jalview.io.NewickFile fin = null;
3390 fin = new jalview.io.NewickFile(choice, "File");
3391 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3392 } catch (Exception ex)
3394 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3395 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3396 ex.printStackTrace();
3398 if (fin != null && fin.hasWarningMessage())
3400 JOptionPane.showMessageDialog(Desktop.desktop, fin
3401 .getWarningMessage(), "Possible problem with tree file",
3402 JOptionPane.WARNING_MESSAGE);
3407 public TreePanel ShowNewickTree(NewickFile nf, String title)
3409 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3412 public TreePanel ShowNewickTree(NewickFile nf, String title,
3413 AlignmentView input)
3415 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3418 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3419 int h, int x, int y)
3421 return ShowNewickTree(nf, title, null, w, h, x, y);
3425 * Add a treeviewer for the tree extracted from a newick file object to the
3426 * current alignment view
3433 * Associated alignment input data (or null)
3442 * @return TreePanel handle
3444 public TreePanel ShowNewickTree(NewickFile nf, String title,
3445 AlignmentView input, int w, int h, int x, int y)
3447 TreePanel tp = null;
3453 if (nf.getTree() != null)
3455 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3461 tp.setLocation(x, y);
3464 Desktop.addInternalFrame(tp, title, w, h);
3466 } catch (Exception ex)
3468 ex.printStackTrace();
3475 * Generates menu items and listener event actions for web service clients
3478 public void BuildWebServiceMenu()
3480 // TODO: add support for context dependent disabling of services based on
3481 // alignment and current selection
3482 // TODO: add additional serviceHandle parameter to specify abstract handler
3483 // class independently of AbstractName
3484 // TODO: add in rediscovery GUI function to restart discoverer
3485 // TODO: group services by location as well as function and/or introduce
3486 // object broker mechanism.
3487 if ((Discoverer.services != null) && (Discoverer.services.size() > 0))
3489 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3490 // stored or retrieved from elsewhere
3491 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3492 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3493 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3494 // TODO: move GUI generation code onto service implementation - so a
3495 // client instance attaches itself to the GUI with method call like
3496 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3498 Vector wsmenu = new Vector();
3499 final IProgressIndicator af = this;
3502 // Add any Multiple Sequence Alignment Services
3503 final JMenu msawsmenu = new JMenu("Alignment");
3504 for (int i = 0, j = msaws.size(); i < j; i++)
3506 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3508 jalview.ws.WSClient impl = jalview.ws.Discoverer
3509 .getServiceClient(sh);
3510 impl.attachWSMenuEntry(msawsmenu, this);
3513 wsmenu.add(msawsmenu);
3515 if (secstrpr != null)
3517 // Add any secondary structure prediction services
3518 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3519 for (int i = 0, j = secstrpr.size(); i < j; i++)
3521 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3523 jalview.ws.WSClient impl = jalview.ws.Discoverer
3524 .getServiceClient(sh);
3525 impl.attachWSMenuEntry(secstrmenu, this);
3527 wsmenu.add(secstrmenu);
3529 if (seqsrch != null)
3531 // Add any sequence search services
3532 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3533 for (int i = 0, j = seqsrch.size(); i < j; i++)
3535 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3537 jalview.ws.WSClient impl = jalview.ws.Discoverer
3538 .getServiceClient(sh);
3539 impl.attachWSMenuEntry(seqsrchmenu, this);
3541 // finally, add the whole shebang onto the webservices menu
3542 wsmenu.add(seqsrchmenu);
3544 resetWebServiceMenu();
3545 for (int i = 0, j = wsmenu.size(); i < j; i++)
3547 webService.add((JMenu) wsmenu.get(i));
3552 resetWebServiceMenu();
3553 this.webService.add(this.webServiceNoServices);
3558 * empty the web service menu and add any ad-hoc functions not dynamically
3562 private void resetWebServiceMenu()
3564 webService.removeAll();
3565 // Temporary hack - DBRef Fetcher always top level ws entry.
3566 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3568 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
3569 webService.add(rfetch);
3570 rfetch.addActionListener(new ActionListener()
3573 public void actionPerformed(ActionEvent e)
3575 new Thread(new Runnable()
3580 new jalview.ws.DBRefFetcher(alignPanel.av
3581 .getSequenceSelection(), alignPanel.alignFrame)
3582 .fetchDBRefs(false);
3592 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3593 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3594 * getProperty("LAST_DIRECTORY"));
3596 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3597 * to Vamsas file"); chooser.setToolTipText("Export");
3599 * int value = chooser.showSaveDialog(this);
3601 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3602 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3603 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3604 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3607 * prototype of an automatically enabled/disabled analysis function
3610 protected void setShowProductsEnabled()
3612 SequenceI[] selection = viewport.getSequenceSelection();
3613 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3614 viewport.getAlignment().getDataset()))
3616 showProducts.setEnabled(true);
3621 showProducts.setEnabled(false);
3626 * search selection for sequence xRef products and build the show products
3631 * @return true if showProducts menu should be enabled.
3633 public boolean canShowProducts(SequenceI[] selection,
3634 boolean isRegionSelection, Alignment dataset)
3636 boolean showp = false;
3639 showProducts.removeAll();
3640 final boolean dna = viewport.getAlignment().isNucleotide();
3641 final Alignment ds = dataset;
3642 String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection,
3645 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
3646 // selection, dataset, true);
3647 final SequenceI[] sel = selection;
3648 for (int t = 0; ptypes != null && t < ptypes.length; t++)
3651 final boolean isRegSel = isRegionSelection;
3652 final AlignFrame af = this;
3653 final String source = ptypes[t];
3654 JMenuItem xtype = new JMenuItem(ptypes[t]);
3655 xtype.addActionListener(new ActionListener()
3658 public void actionPerformed(ActionEvent e)
3660 // TODO: new thread for this call with vis-delay
3661 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
3662 isRegSel, dna, source);
3666 showProducts.add(xtype);
3668 showProducts.setVisible(showp);
3669 showProducts.setEnabled(showp);
3670 } catch (Exception e)
3672 jalview.bin.Cache.log
3674 "canTranslate threw an exception - please report to help@jalview.org",
3681 protected void showProductsFor(SequenceI[] sel, Alignment ds,
3682 boolean isRegSel, boolean dna, String source)
3684 final boolean fisRegSel = isRegSel;
3685 final boolean fdna = dna;
3686 final String fsrc = source;
3687 final AlignFrame ths = this;
3688 final SequenceI[] fsel = sel;
3689 Runnable foo = new Runnable()
3694 final long sttime = System.currentTimeMillis();
3695 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
3698 Alignment ds = ths.getViewport().alignment.getDataset(); // update
3702 Alignment prods = CrossRef
3703 .findXrefSequences(fsel, fdna, fsrc, ds);
3706 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3707 for (int s = 0; s < sprods.length; s++)
3709 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3710 if (ds.getSequences() == null
3711 || !ds.getSequences().contains(
3712 sprods[s].getDatasetSequence()))
3713 ds.addSequence(sprods[s].getDatasetSequence());
3714 sprods[s].updatePDBIds();
3716 Alignment al = new Alignment(sprods);
3717 AlignedCodonFrame[] cf = prods.getCodonFrames();
3718 for (int s = 0; cf != null && s < cf.length; s++)
3720 al.addCodonFrame(cf[s]);
3724 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
3726 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
3727 + " for " + ((fisRegSel) ? "selected region of " : "")
3729 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3734 System.err.println("No Sequences generated for xRef type "
3737 } catch (Exception e)
3739 jalview.bin.Cache.log.error(
3740 "Exception when finding crossreferences", e);
3741 } catch (OutOfMemoryError e)
3743 new OOMWarning("whilst fetching crossreferences", e);
3746 jalview.bin.Cache.log.error("Error when finding crossreferences",
3749 ths.setProgressBar("Finished searching for sequences from " + fsrc,
3754 Thread frunner = new Thread(foo);
3758 public boolean canShowTranslationProducts(SequenceI[] selection,
3759 AlignmentI alignment)
3764 return (jalview.analysis.Dna.canTranslate(selection, viewport
3765 .getViewAsVisibleContigs(true)));
3766 } catch (Exception e)
3768 jalview.bin.Cache.log
3770 "canTranslate threw an exception - please report to help@jalview.org",
3776 public void showProducts_actionPerformed(ActionEvent e)
3778 // /////////////////////////////
3779 // Collect Data to be translated/transferred
3781 SequenceI[] selection = viewport.getSequenceSelection();
3782 AlignmentI al = null;
3785 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
3786 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
3787 viewport.getAlignment().getDataset());
3788 } catch (Exception ex)
3791 jalview.bin.Cache.log.debug("Exception during translation.", ex);
3798 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3799 "Translation Failed", JOptionPane.WARNING_MESSAGE);
3803 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3804 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
3805 DEFAULT_WIDTH, DEFAULT_HEIGHT);
3809 public void showTranslation_actionPerformed(ActionEvent e)
3811 // /////////////////////////////
3812 // Collect Data to be translated/transferred
3814 SequenceI[] selection = viewport.getSequenceSelection();
3815 String[] seqstring = viewport.getViewAsString(true);
3816 AlignmentI al = null;
3819 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
3820 viewport.getViewAsVisibleContigs(true), viewport
3821 .getGapCharacter(), viewport.alignment
3822 .getAlignmentAnnotation(), viewport.alignment
3823 .getWidth(), viewport.getAlignment().getDataset());
3824 } catch (Exception ex)
3827 jalview.bin.Cache.log.debug("Exception during translation.", ex);
3834 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3835 "Translation Failed", JOptionPane.WARNING_MESSAGE);
3839 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3840 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
3841 DEFAULT_WIDTH, DEFAULT_HEIGHT);
3846 * Try to load a features file onto the alignment.
3849 * contents or path to retrieve file
3851 * access mode of file (see jalview.io.AlignFile)
3852 * @return true if features file was parsed corectly.
3854 public boolean parseFeaturesFile(String file, String type)
3856 boolean featuresFile = false;
3859 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
3860 .getDataset(), alignPanel.seqPanel.seqCanvas
3861 .getFeatureRenderer().featureColours, false);
3862 } catch (Exception ex)
3864 ex.printStackTrace();
3869 viewport.showSequenceFeatures = true;
3870 showSeqFeatures.setSelected(true);
3871 alignPanel.paintAlignment(true);
3874 return featuresFile;
3877 public void dragEnter(DropTargetDragEvent evt)
3881 public void dragExit(DropTargetEvent evt)
3885 public void dragOver(DropTargetDragEvent evt)
3889 public void dropActionChanged(DropTargetDragEvent evt)
3893 public void drop(DropTargetDropEvent evt)
3895 Transferable t = evt.getTransferable();
3896 java.util.List files = null;
3900 DataFlavor uriListFlavor = new DataFlavor(
3901 "text/uri-list;class=java.lang.String");
3902 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3904 // Works on Windows and MacOSX
3905 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3906 files = (java.util.List) t
3907 .getTransferData(DataFlavor.javaFileListFlavor);
3909 else if (t.isDataFlavorSupported(uriListFlavor))
3911 // This is used by Unix drag system
3912 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3913 String data = (String) t.getTransferData(uriListFlavor);
3914 files = new java.util.ArrayList(1);
3915 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3916 data, "\r\n"); st.hasMoreTokens();)
3918 String s = st.nextToken();
3919 if (s.startsWith("#"))
3921 // the line is a comment (as per the RFC 2483)
3925 java.net.URI uri = new java.net.URI(s);
3926 java.io.File file = new java.io.File(uri);
3930 } catch (Exception e)
3932 e.printStackTrace();
3939 for (int i = 0; i < files.size(); i++)
3941 loadJalviewDataFile(files.get(i).toString());
3943 } catch (Exception ex)
3945 ex.printStackTrace();
3951 * Attempt to load a "dropped" file: First by testing whether it's and
3952 * Annotation file, then a JNet file, and finally a features file. If all are
3953 * false then the user may have dropped an alignment file onto this
3957 * either a filename or a URL string.
3959 public void loadJalviewDataFile(String file)
3963 String protocol = "File";
3965 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3970 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
3971 viewport.alignment, file, protocol);
3975 // try to see if its a JNet 'concise' style annotation file *before* we
3976 // try to parse it as a features file
3977 String format = new IdentifyFile().Identify(file, protocol);
3978 if (format.equalsIgnoreCase("JnetFile"))
3980 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
3982 new JnetAnnotationMaker().add_annotation(predictions, viewport
3983 .getAlignment(), 0, false);
3984 isAnnotation = true;
3988 // try to parse it as a features file
3989 boolean isGroupsFile = parseFeaturesFile(file, protocol);
3990 // if it wasn't a features file then we just treat it as a general
3991 // alignment file to load into the current view.
3994 new FileLoader().LoadFile(viewport, file, protocol, format);
3998 alignPanel.paintAlignment(true);
4005 alignPanel.adjustAnnotationHeight();
4006 viewport.updateSequenceIdColours();
4007 buildSortByAnnotationScoresMenu();
4008 alignPanel.paintAlignment(true);
4010 } catch (Exception ex)
4012 ex.printStackTrace();
4016 public void tabSelectionChanged(int index)
4020 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4021 viewport = alignPanel.av;
4022 setMenusFromViewport(viewport);
4026 public void tabbedPane_mousePressed(MouseEvent e)
4028 if (SwingUtilities.isRightMouseButton(e))
4030 String reply = JOptionPane.showInternalInputDialog(this,
4031 "Enter View Name", "Edit View Name",
4032 JOptionPane.QUESTION_MESSAGE);
4036 viewport.viewName = reply;
4037 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4042 public AlignViewport getCurrentView()
4048 * Open the dialog for regex description parsing.
4050 protected void extractScores_actionPerformed(ActionEvent e)
4052 ParseProperties pp = new jalview.analysis.ParseProperties(
4053 viewport.alignment);
4054 // TODO: verify regex and introduce GUI dialog for version 2.5
4055 // if (pp.getScoresFromDescription("col", "score column ",
4056 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4058 if (pp.getScoresFromDescription("description column",
4059 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4061 buildSortByAnnotationScoresMenu();
4066 * @see jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent)
4068 protected void showDbRefs_actionPerformed(ActionEvent e)
4070 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
4074 * @see jalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.ActionEvent)
4076 protected void showNpFeats_actionPerformed(ActionEvent e)
4078 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
4082 class PrintThread extends Thread
4086 public PrintThread(AlignmentPanel ap)
4091 static PageFormat pf;
4095 PrinterJob printJob = PrinterJob.getPrinterJob();
4099 printJob.setPrintable(ap, pf);
4103 printJob.setPrintable(ap);
4106 if (printJob.printDialog())
4111 } catch (Exception PrintException)
4113 PrintException.printStackTrace();