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);
555 setShowProductsEnabled();
560 Hashtable progressBars;
565 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
567 public void setProgressBar(String message, long id)
569 if (progressBars == null)
571 progressBars = new Hashtable();
574 JPanel progressPanel;
575 GridLayout layout = (GridLayout) statusPanel.getLayout();
576 if (progressBars.get(new Long(id)) != null)
578 progressPanel = (JPanel) progressBars.get(new Long(id));
579 statusPanel.remove(progressPanel);
580 progressBars.remove(progressPanel);
581 progressPanel = null;
584 statusBar.setText(message);
587 layout.setRows(layout.getRows() - 1);
591 progressPanel = new JPanel(new BorderLayout(10, 5));
593 JProgressBar progressBar = new JProgressBar();
594 progressBar.setIndeterminate(true);
596 progressPanel.add(new JLabel(message), BorderLayout.WEST);
597 progressPanel.add(progressBar, BorderLayout.CENTER);
599 layout.setRows(layout.getRows() + 1);
600 statusPanel.add(progressPanel);
602 progressBars.put(new Long(id), progressPanel);
605 setMenusForViewport();
611 * @return true if any progress bars are still active
613 public boolean operationInProgress()
615 if (progressBars != null && progressBars.size() > 0)
623 * Added so Castor Mapping file can obtain Jalview Version
625 public String getVersion()
627 return jalview.bin.Cache.getProperty("VERSION");
630 public FeatureRenderer getFeatureRenderer()
632 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
635 public void fetchSequence_actionPerformed(ActionEvent e)
637 new SequenceFetcher(this);
640 public void addFromFile_actionPerformed(ActionEvent e)
642 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
645 public void reload_actionPerformed(ActionEvent e)
647 if (fileName != null)
649 if (currentFileFormat.equals("Jalview"))
651 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
652 for (int i = 0; i < frames.length; i++)
654 if (frames[i] instanceof AlignFrame && frames[i] != this
655 && ((AlignFrame) frames[i]).fileName.equals(fileName))
659 frames[i].setSelected(true);
660 Desktop.instance.closeAssociatedWindows();
661 } catch (java.beans.PropertyVetoException ex)
667 Desktop.instance.closeAssociatedWindows();
669 FileLoader loader = new FileLoader();
670 String protocol = fileName.startsWith("http:") ? "URL" : "File";
671 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
675 Rectangle bounds = this.getBounds();
677 FileLoader loader = new FileLoader();
678 String protocol = fileName.startsWith("http:") ? "URL" : "File";
679 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
680 protocol, currentFileFormat);
682 newframe.setBounds(bounds);
684 this.closeMenuItem_actionPerformed(true);
689 public void addFromText_actionPerformed(ActionEvent e)
691 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
694 public void addFromURL_actionPerformed(ActionEvent e)
696 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
699 public void save_actionPerformed(ActionEvent e)
702 || (currentFileFormat == null
703 || !jalview.io.FormatAdapter.isValidIOFormat(currentFileFormat, true))
704 || fileName.startsWith("http"))
706 saveAs_actionPerformed(null);
710 saveAlignment(fileName, currentFileFormat);
720 public void saveAs_actionPerformed(ActionEvent e)
722 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
723 .getProperty("LAST_DIRECTORY"),
724 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
725 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
726 currentFileFormat, false);
728 chooser.setFileView(new JalviewFileView());
729 chooser.setDialogTitle("Save Alignment to file");
730 chooser.setToolTipText("Save");
732 int value = chooser.showSaveDialog(this);
734 if (value == JalviewFileChooser.APPROVE_OPTION)
736 currentFileFormat = chooser.getSelectedFormat();
737 if (currentFileFormat == null)
739 JOptionPane.showInternalMessageDialog(Desktop.desktop,
740 "You must select a file format before saving!",
741 "File format not specified", JOptionPane.WARNING_MESSAGE);
742 value = chooser.showSaveDialog(this);
746 fileName = chooser.getSelectedFile().getPath();
748 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
751 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
752 if (currentFileFormat.indexOf(" ") > -1)
754 currentFileFormat = currentFileFormat.substring(0,
755 currentFileFormat.indexOf(" "));
757 saveAlignment(fileName, currentFileFormat);
761 public boolean saveAlignment(String file, String format)
763 boolean success = true;
765 if (format.equalsIgnoreCase("Jalview"))
767 String shortName = title;
769 if (shortName.indexOf(java.io.File.separatorChar) > -1)
771 shortName = shortName.substring(shortName
772 .lastIndexOf(java.io.File.separatorChar) + 1);
775 success = new Jalview2XML().SaveAlignment(this, file, shortName);
777 statusBar.setText("Successfully saved to file: " + fileName + " in "
778 + format + " format.");
783 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
785 // JBPNote need to have a raise_gui flag here
786 JOptionPane.showInternalMessageDialog(this, "Cannot save file "
787 + fileName + " using format " + format,
788 "Alignment output format not supported",
789 JOptionPane.WARNING_MESSAGE);
790 saveAs_actionPerformed(null);
794 String[] omitHidden = null;
796 if (viewport.hasHiddenColumns)
798 int reply = JOptionPane
799 .showInternalConfirmDialog(
801 "The Alignment contains hidden columns."
802 + "\nDo you want to save only the visible alignment?",
803 "Save / Omit Hidden Columns",
804 JOptionPane.YES_NO_OPTION,
805 JOptionPane.QUESTION_MESSAGE);
807 if (reply == JOptionPane.YES_OPTION)
809 omitHidden = viewport.getViewAsString(false);
812 FormatAdapter f = new FormatAdapter();
813 String output = f.formatSequences(format,
814 (Alignment) viewport.alignment, // class cast exceptions will
815 // occur in the distant future
816 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
826 java.io.PrintWriter out = new java.io.PrintWriter(
827 new java.io.FileWriter(file));
832 statusBar.setText("Successfully saved to file: " + fileName
833 + " in " + format + " format.");
834 } catch (Exception ex)
837 ex.printStackTrace();
844 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
845 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
857 protected void outputText_actionPerformed(ActionEvent e)
859 String[] omitHidden = null;
861 if (viewport.hasHiddenColumns)
863 int reply = JOptionPane
864 .showInternalConfirmDialog(
866 "The Alignment contains hidden columns."
867 + "\nDo you want to output only the visible alignment?",
868 "Save / Omit Hidden Columns",
869 JOptionPane.YES_NO_OPTION,
870 JOptionPane.QUESTION_MESSAGE);
872 if (reply == JOptionPane.YES_OPTION)
874 omitHidden = viewport.getViewAsString(false);
878 CutAndPasteTransfer cap = new CutAndPasteTransfer();
879 cap.setForInput(null);
880 Desktop.addInternalFrame(cap, "Alignment output - "
881 + e.getActionCommand(), 600, 500);
883 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
884 viewport.alignment, omitHidden, viewport.colSel));
893 protected void htmlMenuItem_actionPerformed(ActionEvent e)
895 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
896 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
897 .getFeatureRenderer());
900 public void createImageMap(File file, String image)
902 alignPanel.makePNGImageMap(file, image);
911 public void createPNG(File f)
913 alignPanel.makePNG(f);
922 public void createEPS(File f)
924 alignPanel.makeEPS(f);
927 public void pageSetup_actionPerformed(ActionEvent e)
929 PrinterJob printJob = PrinterJob.getPrinterJob();
930 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
939 public void printMenuItem_actionPerformed(ActionEvent e)
941 // Putting in a thread avoids Swing painting problems
942 PrintThread thread = new PrintThread(alignPanel);
946 public void exportFeatures_actionPerformed(ActionEvent e)
948 new AnnotationExporter().exportFeatures(alignPanel);
951 public void exportAnnotations_actionPerformed(ActionEvent e)
953 new AnnotationExporter().exportAnnotations(alignPanel,
954 viewport.showAnnotation ? viewport.alignment
955 .getAlignmentAnnotation() : null, viewport.alignment
957 ((Alignment) viewport.alignment).alignmentProperties);
960 public void associatedData_actionPerformed(ActionEvent e)
962 // Pick the tree file
963 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
964 .getProperty("LAST_DIRECTORY"));
965 chooser.setFileView(new JalviewFileView());
966 chooser.setDialogTitle("Load Jalview Annotations or Features File");
967 chooser.setToolTipText("Load Jalview Annotations / Features file");
969 int value = chooser.showOpenDialog(null);
971 if (value == JalviewFileChooser.APPROVE_OPTION)
973 String choice = chooser.getSelectedFile().getPath();
974 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
975 loadJalviewDataFile(choice);
986 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
988 if (alignPanels != null && alignPanels.size() < 2)
995 if (alignPanels != null)
999 for (int i = 0; i < alignPanels.size(); i++)
1001 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1002 jalview.structure.StructureSelectionManager
1003 .getStructureSelectionManager()
1004 .removeStructureViewerListener(ap.seqPanel, null);
1005 PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
1006 PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
1007 PaintRefresher.RemoveComponent(ap);
1008 ap.av.alignment = null;
1013 int index = tabbedPane.getSelectedIndex();
1015 alignPanels.removeElement(alignPanel);
1016 PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
1017 PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
1018 PaintRefresher.RemoveComponent(alignPanel);
1019 viewport.alignment = null;
1023 tabbedPane.removeTabAt(index);
1024 tabbedPane.validate();
1026 if (index == tabbedPane.getTabCount())
1031 this.tabSelectionChanged(index);
1037 this.setClosed(true);
1039 } catch (Exception ex)
1041 ex.printStackTrace();
1048 void updateEditMenuBar()
1051 if (viewport.historyList.size() > 0)
1053 undoMenuItem.setEnabled(true);
1054 CommandI command = (CommandI) viewport.historyList.peek();
1055 undoMenuItem.setText("Undo " + command.getDescription());
1059 undoMenuItem.setEnabled(false);
1060 undoMenuItem.setText("Undo");
1063 if (viewport.redoList.size() > 0)
1065 redoMenuItem.setEnabled(true);
1067 CommandI command = (CommandI) viewport.redoList.peek();
1068 redoMenuItem.setText("Redo " + command.getDescription());
1072 redoMenuItem.setEnabled(false);
1073 redoMenuItem.setText("Redo");
1077 public void addHistoryItem(CommandI command)
1079 if (command.getSize() > 0)
1081 viewport.historyList.push(command);
1082 viewport.redoList.clear();
1083 updateEditMenuBar();
1084 viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1090 * @return alignment objects for all views
1092 AlignmentI[] getViewAlignments()
1094 if (alignPanels != null)
1096 Enumeration e = alignPanels.elements();
1097 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1098 for (int i = 0; e.hasMoreElements(); i++)
1100 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1104 if (viewport != null)
1106 return new AlignmentI[]
1107 { viewport.alignment };
1118 protected void undoMenuItem_actionPerformed(ActionEvent e)
1120 if (viewport.historyList.empty())
1122 CommandI command = (CommandI) viewport.historyList.pop();
1123 viewport.redoList.push(command);
1124 command.undoCommand(getViewAlignments());
1126 AlignViewport originalSource = getOriginatingSource(command);
1127 updateEditMenuBar();
1129 if (originalSource != null)
1131 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1132 originalSource.firePropertyChange("alignment", null,
1133 originalSource.alignment.getSequences());
1143 protected void redoMenuItem_actionPerformed(ActionEvent e)
1145 if (viewport.redoList.size() < 1)
1150 CommandI command = (CommandI) viewport.redoList.pop();
1151 viewport.historyList.push(command);
1152 command.doCommand(getViewAlignments());
1154 AlignViewport originalSource = getOriginatingSource(command);
1155 updateEditMenuBar();
1157 if (originalSource != null)
1159 originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
1160 originalSource.firePropertyChange("alignment", null,
1161 originalSource.alignment.getSequences());
1165 AlignViewport getOriginatingSource(CommandI command)
1167 AlignViewport originalSource = null;
1168 // For sequence removal and addition, we need to fire
1169 // the property change event FROM the viewport where the
1170 // original alignment was altered
1171 AlignmentI al = null;
1172 if (command instanceof EditCommand)
1174 EditCommand editCommand = (EditCommand) command;
1175 al = editCommand.getAlignment();
1176 Vector comps = (Vector) PaintRefresher.components.get(viewport
1177 .getSequenceSetId());
1179 for (int i = 0; i < comps.size(); i++)
1181 if (comps.elementAt(i) instanceof AlignmentPanel)
1183 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1185 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1192 if (originalSource == null)
1194 // The original view is closed, we must validate
1195 // the current view against the closed view first
1198 PaintRefresher.validateSequences(al, viewport.alignment);
1201 originalSource = viewport;
1204 return originalSource;
1213 public void moveSelectedSequences(boolean up)
1215 SequenceGroup sg = viewport.getSelectionGroup();
1224 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1226 SequenceI seq = viewport.alignment.getSequenceAt(i);
1228 if (!sg.getSequences(null).contains(seq))
1233 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1235 if (sg.getSequences(null).contains(temp))
1240 viewport.alignment.getSequences().setElementAt(temp, i);
1241 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1246 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1248 SequenceI seq = viewport.alignment.getSequenceAt(i);
1250 if (!sg.getSequences(null).contains(seq))
1255 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1257 if (sg.getSequences(null).contains(temp))
1262 viewport.alignment.getSequences().setElementAt(temp, i);
1263 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1267 alignPanel.paintAlignment(true);
1270 synchronized void slideSequences(boolean right, int size)
1272 Vector sg = new Vector();
1273 if (viewport.cursorMode)
1275 sg.addElement(viewport.alignment
1276 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1278 else if (viewport.getSelectionGroup() != null
1279 && viewport.getSelectionGroup().getSize() != viewport.alignment
1282 sg = viewport.getSelectionGroup().getSequences(
1283 viewport.hiddenRepSequences);
1291 Vector invertGroup = new Vector();
1293 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1295 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1296 invertGroup.add(viewport.alignment.getSequenceAt(i));
1299 SequenceI[] seqs1 = new SequenceI[sg.size()];
1300 for (int i = 0; i < sg.size(); i++)
1301 seqs1[i] = (SequenceI) sg.elementAt(i);
1303 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1304 for (int i = 0; i < invertGroup.size(); i++)
1305 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1307 SlideSequencesCommand ssc;
1309 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1310 size, viewport.getGapCharacter());
1312 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1313 size, viewport.getGapCharacter());
1315 int groupAdjustment = 0;
1316 if (ssc.getGapsInsertedBegin() && right)
1318 if (viewport.cursorMode)
1319 alignPanel.seqPanel.moveCursor(size, 0);
1321 groupAdjustment = size;
1323 else if (!ssc.getGapsInsertedBegin() && !right)
1325 if (viewport.cursorMode)
1326 alignPanel.seqPanel.moveCursor(-size, 0);
1328 groupAdjustment = -size;
1331 if (groupAdjustment != 0)
1333 viewport.getSelectionGroup().setStartRes(
1334 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1335 viewport.getSelectionGroup().setEndRes(
1336 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1339 boolean appendHistoryItem = false;
1340 if (viewport.historyList != null && viewport.historyList.size() > 0
1341 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1343 appendHistoryItem = ssc
1344 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1348 if (!appendHistoryItem)
1349 addHistoryItem(ssc);
1360 protected void copy_actionPerformed(ActionEvent e)
1363 if (viewport.getSelectionGroup() == null)
1367 // TODO: preserve the ordering of displayed alignment annotation in any
1368 // internal paste (particularly sequence associated annotation)
1369 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1370 String[] omitHidden = null;
1372 if (viewport.hasHiddenColumns)
1374 omitHidden = viewport.getViewAsString(true);
1377 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1380 StringSelection ss = new StringSelection(output);
1384 jalview.gui.Desktop.internalCopy = true;
1385 // Its really worth setting the clipboard contents
1386 // to empty before setting the large StringSelection!!
1387 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1388 new StringSelection(""), null);
1390 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1392 } catch (OutOfMemoryError er)
1394 new OOMWarning("copying region", er);
1398 Vector hiddenColumns = null;
1399 if (viewport.hasHiddenColumns)
1401 hiddenColumns = new Vector();
1402 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1403 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1406 int[] region = (int[]) viewport.getColumnSelection()
1407 .getHiddenColumns().elementAt(i);
1409 hiddenColumns.addElement(new int[]
1410 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1414 Desktop.jalviewClipboard = new Object[]
1415 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1416 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1425 protected void pasteNew_actionPerformed(ActionEvent e)
1436 protected void pasteThis_actionPerformed(ActionEvent e)
1442 * Paste contents of Jalview clipboard
1444 * @param newAlignment
1445 * true to paste to a new alignment, otherwise add to this.
1447 void paste(boolean newAlignment)
1449 boolean externalPaste = true;
1452 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1453 Transferable contents = c.getContents(this);
1455 if (contents == null)
1463 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1464 if (str.length() < 1)
1469 format = new IdentifyFile().Identify(str, "Paste");
1471 } catch (OutOfMemoryError er)
1473 new OOMWarning("Out of memory pasting sequences!!", er);
1477 SequenceI[] sequences;
1478 boolean annotationAdded = false;
1479 AlignmentI alignment = null;
1481 if (Desktop.jalviewClipboard != null)
1483 // The clipboard was filled from within Jalview, we must use the
1485 // And dataset from the copied alignment
1486 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1487 // be doubly sure that we create *new* sequence objects.
1488 sequences = new SequenceI[newseq.length];
1489 for (int i = 0; i < newseq.length; i++)
1491 sequences[i] = new Sequence(newseq[i]);
1493 alignment = new Alignment(sequences);
1494 externalPaste = false;
1498 // parse the clipboard as an alignment.
1499 alignment = new FormatAdapter().readFile(str, "Paste", format);
1500 sequences = alignment.getSequencesArray();
1508 if (Desktop.jalviewClipboard != null)
1510 // dataset is inherited
1511 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1515 // new dataset is constructed
1516 alignment.setDataset(null);
1518 alwidth = alignment.getWidth() + 1;
1522 AlignmentI pastedal = alignment; // preserve pasted alignment object
1523 // Add pasted sequences and dataset into existing alignment.
1524 alignment = viewport.getAlignment();
1525 alwidth = alignment.getWidth() + 1;
1526 // decide if we need to import sequences from an existing dataset
1527 boolean importDs = Desktop.jalviewClipboard != null
1528 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1529 // importDs==true instructs us to copy over new dataset sequences from
1530 // an existing alignment
1531 Vector newDs = (importDs) ? new Vector() : null; // used to create
1532 // minimum dataset set
1534 for (int i = 0; i < sequences.length; i++)
1538 newDs.addElement(null);
1540 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1542 if (importDs && ds != null)
1544 if (!newDs.contains(ds))
1546 newDs.setElementAt(ds, i);
1547 ds = new Sequence(ds);
1548 // update with new dataset sequence
1549 sequences[i].setDatasetSequence(ds);
1553 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1558 // copy and derive new dataset sequence
1559 sequences[i] = sequences[i].deriveSequence();
1560 alignment.getDataset().addSequence(
1561 sequences[i].getDatasetSequence());
1562 // TODO: avoid creation of duplicate dataset sequences with a
1563 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1565 alignment.addSequence(sequences[i]); // merges dataset
1569 newDs.clear(); // tidy up
1571 if (pastedal.getAlignmentAnnotation() != null)
1573 // Add any annotation attached to alignment.
1574 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1575 for (int i = 0; i < alann.length; i++)
1577 annotationAdded = true;
1578 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1580 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1581 newann.padAnnotation(alwidth);
1582 alignment.addAnnotation(newann);
1592 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1593 sequences, 0, alignment.getWidth(), alignment));
1595 // Add any annotations attached to sequences
1596 for (int i = 0; i < sequences.length; i++)
1598 if (sequences[i].getAnnotation() != null)
1600 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1602 annotationAdded = true;
1603 sequences[i].getAnnotation()[a].adjustForAlignment();
1604 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1605 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1610 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1617 // propagate alignment changed.
1618 viewport.setEndSeq(alignment.getHeight());
1619 if (annotationAdded)
1621 // Duplicate sequence annotation in all views.
1622 AlignmentI[] alview = this.getViewAlignments();
1623 for (int i = 0; i < sequences.length; i++)
1625 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1628 for (int avnum = 0; avnum < alview.length; avnum++)
1630 if (alview[avnum] != alignment)
1632 // duplicate in a view other than the one with input focus
1633 int avwidth = alview[avnum].getWidth() + 1;
1634 // this relies on sann being preserved after we
1635 // modify the sequence's annotation array for each duplication
1636 for (int a = 0; a < sann.length; a++)
1638 AlignmentAnnotation newann = new AlignmentAnnotation(
1640 sequences[i].addAlignmentAnnotation(newann);
1641 newann.padAnnotation(avwidth);
1642 alview[avnum].addAnnotation(newann); // annotation was
1643 // duplicated earlier
1644 alview[avnum].setAnnotationIndex(newann, a);
1649 buildSortByAnnotationScoresMenu();
1651 viewport.firePropertyChange("alignment", null, alignment
1657 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1659 String newtitle = new String("Copied sequences");
1661 if (Desktop.jalviewClipboard != null
1662 && Desktop.jalviewClipboard[2] != null)
1664 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1665 for (int i = 0; i < hc.size(); i++)
1667 int[] region = (int[]) hc.elementAt(i);
1668 af.viewport.hideColumns(region[0], region[1]);
1672 // >>>This is a fix for the moment, until a better solution is
1674 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1676 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1678 // TODO: maintain provenance of an alignment, rather than just make the
1679 // title a concatenation of operations.
1682 if (title.startsWith("Copied sequences"))
1688 newtitle = newtitle.concat("- from " + title);
1693 newtitle = new String("Pasted sequences");
1696 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1701 } catch (Exception ex)
1703 ex.printStackTrace();
1704 System.out.println("Exception whilst pasting: " + ex);
1705 // could be anything being pasted in here
1716 protected void cut_actionPerformed(ActionEvent e)
1718 copy_actionPerformed(null);
1719 delete_actionPerformed(null);
1728 protected void delete_actionPerformed(ActionEvent evt)
1731 SequenceGroup sg = viewport.getSelectionGroup();
1737 Vector seqs = new Vector();
1739 for (int i = 0; i < sg.getSize(); i++)
1741 seq = sg.getSequenceAt(i);
1742 seqs.addElement(seq);
1745 // If the cut affects all sequences, remove highlighted columns
1746 if (sg.getSize() == viewport.alignment.getHeight())
1748 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1749 sg.getEndRes() + 1);
1752 SequenceI[] cut = new SequenceI[seqs.size()];
1753 for (int i = 0; i < seqs.size(); i++)
1755 cut[i] = (SequenceI) seqs.elementAt(i);
1759 * //ADD HISTORY ITEM
1761 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1762 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1763 viewport.alignment));
1765 viewport.setSelectionGroup(null);
1766 viewport.alignment.deleteGroup(sg);
1768 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1771 if (viewport.getAlignment().getHeight() < 1)
1775 this.setClosed(true);
1776 } catch (Exception ex)
1788 protected void deleteGroups_actionPerformed(ActionEvent e)
1790 viewport.alignment.deleteAllGroups();
1791 viewport.sequenceColours = null;
1792 viewport.setSelectionGroup(null);
1793 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1794 alignPanel.paintAlignment(true);
1803 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1805 SequenceGroup sg = new SequenceGroup();
1807 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1809 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1812 sg.setEndRes(viewport.alignment.getWidth() - 1);
1813 viewport.setSelectionGroup(sg);
1814 alignPanel.paintAlignment(true);
1815 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1824 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1826 if (viewport.cursorMode)
1828 alignPanel.seqPanel.keyboardNo1 = null;
1829 alignPanel.seqPanel.keyboardNo2 = null;
1831 viewport.setSelectionGroup(null);
1832 viewport.getColumnSelection().clear();
1833 viewport.setSelectionGroup(null);
1834 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1835 alignPanel.idPanel.idCanvas.searchResults = null;
1836 alignPanel.paintAlignment(true);
1837 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1846 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1848 SequenceGroup sg = viewport.getSelectionGroup();
1852 selectAllSequenceMenuItem_actionPerformed(null);
1857 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1859 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
1862 alignPanel.paintAlignment(true);
1864 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1867 public void invertColSel_actionPerformed(ActionEvent e)
1869 viewport.invertColumnSelection();
1870 alignPanel.paintAlignment(true);
1879 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
1881 trimAlignment(true);
1890 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
1892 trimAlignment(false);
1895 void trimAlignment(boolean trimLeft)
1897 ColumnSelection colSel = viewport.getColumnSelection();
1900 if (colSel.size() > 0)
1904 column = colSel.getMin();
1908 column = colSel.getMax();
1912 if (viewport.getSelectionGroup() != null)
1914 seqs = viewport.getSelectionGroup().getSequencesAsArray(
1915 viewport.hiddenRepSequences);
1919 seqs = viewport.alignment.getSequencesArray();
1922 TrimRegionCommand trimRegion;
1925 trimRegion = new TrimRegionCommand("Remove Left",
1926 TrimRegionCommand.TRIM_LEFT, seqs, column,
1927 viewport.alignment, viewport.colSel,
1928 viewport.selectionGroup);
1929 viewport.setStartRes(0);
1933 trimRegion = new TrimRegionCommand("Remove Right",
1934 TrimRegionCommand.TRIM_RIGHT, seqs, column,
1935 viewport.alignment, viewport.colSel,
1936 viewport.selectionGroup);
1939 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
1941 addHistoryItem(trimRegion);
1943 Vector groups = viewport.alignment.getGroups();
1945 for (int i = 0; i < groups.size(); i++)
1947 SequenceGroup sg = (SequenceGroup) groups.get(i);
1949 if ((trimLeft && !sg.adjustForRemoveLeft(column))
1950 || (!trimLeft && !sg.adjustForRemoveRight(column)))
1952 viewport.alignment.deleteGroup(sg);
1956 viewport.firePropertyChange("alignment", null, viewport
1957 .getAlignment().getSequences());
1967 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
1969 int start = 0, end = viewport.alignment.getWidth() - 1;
1972 if (viewport.getSelectionGroup() != null)
1974 seqs = viewport.getSelectionGroup().getSequencesAsArray(
1975 viewport.hiddenRepSequences);
1976 start = viewport.getSelectionGroup().getStartRes();
1977 end = viewport.getSelectionGroup().getEndRes();
1981 seqs = viewport.alignment.getSequencesArray();
1984 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
1985 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
1987 addHistoryItem(removeGapCols);
1989 statusBar.setText("Removed " + removeGapCols.getSize()
1990 + " empty columns.");
1992 // This is to maintain viewport position on first residue
1993 // of first sequence
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, viewport.getAlignment()
2013 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2015 int start = 0, end = viewport.alignment.getWidth() - 1;
2018 if (viewport.getSelectionGroup() != null)
2020 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2021 viewport.hiddenRepSequences);
2022 start = viewport.getSelectionGroup().getStartRes();
2023 end = viewport.getSelectionGroup().getEndRes();
2027 seqs = viewport.alignment.getSequencesArray();
2030 // This is to maintain viewport position on first residue
2031 // of first sequence
2032 SequenceI seq = viewport.alignment.getSequenceAt(0);
2033 int startRes = seq.findPosition(viewport.startRes);
2035 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2036 viewport.alignment));
2038 viewport.setStartRes(seq.findIndex(startRes) - 1);
2040 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2051 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2053 viewport.padGaps = padGapsMenuitem.isSelected();
2055 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2065 public void findMenuItem_actionPerformed(ActionEvent e)
2070 public void newView_actionPerformed(ActionEvent e)
2072 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
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);
2135 public void font_actionPerformed(ActionEvent e)
2137 new FontChooser(alignPanel);
2146 protected void seqLimit_actionPerformed(ActionEvent e)
2148 viewport.setShowJVSuffix(seqLimits.isSelected());
2150 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2151 .calculateIdWidth());
2152 alignPanel.paintAlignment(true);
2155 public void idRightAlign_actionPerformed(ActionEvent e)
2157 viewport.rightAlignIds = idRightAlign.isSelected();
2158 alignPanel.paintAlignment(true);
2161 public void centreColumnLabels_actionPerformed(ActionEvent e)
2163 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2164 alignPanel.paintAlignment(true);
2173 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2175 viewport.setColourText(colourTextMenuItem.isSelected());
2176 alignPanel.paintAlignment(true);
2185 public void wrapMenuItem_actionPerformed(ActionEvent e)
2187 scaleAbove.setVisible(wrapMenuItem.isSelected());
2188 scaleLeft.setVisible(wrapMenuItem.isSelected());
2189 scaleRight.setVisible(wrapMenuItem.isSelected());
2190 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2191 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2194 public void showAllSeqs_actionPerformed(ActionEvent e)
2196 viewport.showAllHiddenSeqs();
2199 public void showAllColumns_actionPerformed(ActionEvent e)
2201 viewport.showAllHiddenColumns();
2205 public void hideSelSequences_actionPerformed(ActionEvent e)
2207 viewport.hideAllSelectedSeqs();
2208 alignPanel.paintAlignment(true);
2211 public void hideSelColumns_actionPerformed(ActionEvent e)
2213 viewport.hideSelectedColumns();
2214 alignPanel.paintAlignment(true);
2217 public void hiddenMarkers_actionPerformed(ActionEvent e)
2219 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2229 protected void scaleAbove_actionPerformed(ActionEvent e)
2231 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2232 alignPanel.paintAlignment(true);
2241 protected void scaleLeft_actionPerformed(ActionEvent e)
2243 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2244 alignPanel.paintAlignment(true);
2253 protected void scaleRight_actionPerformed(ActionEvent e)
2255 viewport.setScaleRightWrapped(scaleRight.isSelected());
2256 alignPanel.paintAlignment(true);
2265 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2267 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2268 alignPanel.paintAlignment(true);
2277 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2279 viewport.setShowText(viewTextMenuItem.isSelected());
2280 alignPanel.paintAlignment(true);
2289 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2291 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2292 alignPanel.paintAlignment(true);
2295 public FeatureSettings featureSettings;
2297 public void featureSettings_actionPerformed(ActionEvent e)
2299 if (featureSettings != null)
2301 featureSettings.close();
2302 featureSettings = null;
2304 featureSettings = new FeatureSettings(this);
2313 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2315 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2316 alignPanel.paintAlignment(true);
2317 if (alignPanel.getOverviewPanel() != null)
2319 alignPanel.getOverviewPanel().updateOverviewImage();
2329 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2331 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2332 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2335 public void alignmentProperties()
2337 JEditorPane editPane = new JEditorPane("text/html", "");
2338 editPane.setEditable(false);
2339 StringBuffer contents = new StringBuffer("<html>");
2342 int min = Integer.MAX_VALUE, max = 0;
2343 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2345 int size = viewport.alignment.getSequenceAt(i).getEnd()
2346 - viewport.alignment.getSequenceAt(i).getStart();
2353 avg = avg / (float) viewport.alignment.getHeight();
2355 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2356 contents.append("<br>Minimum Sequence Length: " + min);
2357 contents.append("<br>Maximum Sequence Length: " + max);
2358 contents.append("<br>Average Length: " + (int) avg);
2360 if (((Alignment) viewport.alignment).getProperties() != null)
2362 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2363 Enumeration en = props.keys();
2364 contents.append("<br><br><table border=\"1\">");
2365 while (en.hasMoreElements())
2367 String key = en.nextElement().toString();
2368 StringBuffer val = new StringBuffer();
2369 String vals = props.get(key).toString();
2373 npos = vals.indexOf("\n", pos);
2376 val.append(vals.substring(pos));
2380 val.append(vals.substring(pos, npos));
2384 } while (npos != -1);
2386 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2388 contents.append("</table>");
2390 editPane.setText(contents.toString() + "</html>");
2391 JInternalFrame frame = new JInternalFrame();
2392 frame.getContentPane().add(new JScrollPane(editPane));
2394 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2395 + getTitle(), 500, 400);
2404 public void overviewMenuItem_actionPerformed(ActionEvent e)
2406 if (alignPanel.overviewPanel != null)
2411 JInternalFrame frame = new JInternalFrame();
2412 OverviewPanel overview = new OverviewPanel(alignPanel);
2413 frame.setContentPane(overview);
2414 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2415 .getWidth(), frame.getHeight());
2417 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2419 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2421 public void internalFrameClosed(
2422 javax.swing.event.InternalFrameEvent evt)
2424 alignPanel.setOverviewPanel(null);
2428 alignPanel.setOverviewPanel(overview);
2431 public void textColour_actionPerformed(ActionEvent e)
2433 new TextColourChooser().chooseColour(alignPanel, null);
2442 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2453 public void clustalColour_actionPerformed(ActionEvent e)
2455 changeColour(new ClustalxColourScheme(
2456 viewport.alignment.getSequences(), viewport.alignment
2466 public void zappoColour_actionPerformed(ActionEvent e)
2468 changeColour(new ZappoColourScheme());
2477 public void taylorColour_actionPerformed(ActionEvent e)
2479 changeColour(new TaylorColourScheme());
2488 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2490 changeColour(new HydrophobicColourScheme());
2499 public void helixColour_actionPerformed(ActionEvent e)
2501 changeColour(new HelixColourScheme());
2510 public void strandColour_actionPerformed(ActionEvent e)
2512 changeColour(new StrandColourScheme());
2521 public void turnColour_actionPerformed(ActionEvent e)
2523 changeColour(new TurnColourScheme());
2532 public void buriedColour_actionPerformed(ActionEvent e)
2534 changeColour(new BuriedColourScheme());
2543 public void nucleotideColour_actionPerformed(ActionEvent e)
2545 changeColour(new NucleotideColourScheme());
2548 public void annotationColour_actionPerformed(ActionEvent e)
2550 new AnnotationColourChooser(viewport, alignPanel);
2559 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2561 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2570 public void changeColour(ColourSchemeI cs)
2576 if (viewport.getAbovePIDThreshold())
2578 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2581 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2583 viewport.setGlobalColourScheme(cs);
2587 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2590 if (viewport.getConservationSelected())
2593 Alignment al = (Alignment) viewport.alignment;
2594 Conservation c = new Conservation("All",
2595 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2599 c.verdict(false, viewport.ConsPercGaps);
2601 cs.setConservation(c);
2603 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2608 cs.setConservation(null);
2611 cs.setConsensus(viewport.hconsensus);
2614 viewport.setGlobalColourScheme(cs);
2616 if (viewport.getColourAppliesToAllGroups())
2618 Vector groups = viewport.alignment.getGroups();
2620 for (int i = 0; i < groups.size(); i++)
2622 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2630 if (cs instanceof ClustalxColourScheme)
2632 sg.cs = new ClustalxColourScheme(sg
2633 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2635 else if (cs instanceof UserColourScheme)
2637 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2643 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2644 } catch (Exception ex)
2649 if (viewport.getAbovePIDThreshold()
2650 || cs instanceof PIDColourScheme
2651 || cs instanceof Blosum62ColourScheme)
2653 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2655 sg.cs.setConsensus(AAFrequency.calculate(sg
2656 .getSequences(viewport.hiddenRepSequences), sg
2657 .getStartRes(), sg.getEndRes() + 1));
2661 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2664 if (viewport.getConservationSelected())
2666 Conservation c = new Conservation("Group",
2667 ResidueProperties.propHash, 3, sg
2668 .getSequences(viewport.hiddenRepSequences), sg
2669 .getStartRes(), sg.getEndRes() + 1);
2671 c.verdict(false, viewport.ConsPercGaps);
2672 sg.cs.setConservation(c);
2676 sg.cs.setConservation(null);
2681 if (alignPanel.getOverviewPanel() != null)
2683 alignPanel.getOverviewPanel().updateOverviewImage();
2686 alignPanel.paintAlignment(true);
2695 protected void modifyPID_actionPerformed(ActionEvent e)
2697 if (viewport.getAbovePIDThreshold()
2698 && viewport.globalColourScheme != null)
2700 SliderPanel.setPIDSliderSource(alignPanel, viewport
2701 .getGlobalColourScheme(), "Background");
2702 SliderPanel.showPIDSlider();
2712 protected void modifyConservation_actionPerformed(ActionEvent e)
2714 if (viewport.getConservationSelected()
2715 && viewport.globalColourScheme != null)
2717 SliderPanel.setConservationSlider(alignPanel,
2718 viewport.globalColourScheme, "Background");
2719 SliderPanel.showConservationSlider();
2729 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2731 viewport.setConservationSelected(conservationMenuItem.isSelected());
2733 viewport.setAbovePIDThreshold(false);
2734 abovePIDThreshold.setSelected(false);
2736 changeColour(viewport.getGlobalColourScheme());
2738 modifyConservation_actionPerformed(null);
2747 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2749 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2751 conservationMenuItem.setSelected(false);
2752 viewport.setConservationSelected(false);
2754 changeColour(viewport.getGlobalColourScheme());
2756 modifyPID_actionPerformed(null);
2765 public void userDefinedColour_actionPerformed(ActionEvent e)
2767 if (e.getActionCommand().equals("User Defined..."))
2769 new UserDefinedColours(alignPanel, null);
2773 UserColourScheme udc = (UserColourScheme) UserDefinedColours
2774 .getUserColourSchemes().get(e.getActionCommand());
2780 public void updateUserColourMenu()
2783 Component[] menuItems = colourMenu.getMenuComponents();
2784 int i, iSize = menuItems.length;
2785 for (i = 0; i < iSize; i++)
2787 if (menuItems[i].getName() != null
2788 && menuItems[i].getName().equals("USER_DEFINED"))
2790 colourMenu.remove(menuItems[i]);
2794 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
2796 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
2797 .getUserColourSchemes().keys();
2799 while (userColours.hasMoreElements())
2801 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
2802 userColours.nextElement().toString());
2803 radioItem.setName("USER_DEFINED");
2804 radioItem.addMouseListener(new MouseAdapter()
2806 public void mousePressed(MouseEvent evt)
2808 if (evt.isControlDown()
2809 || SwingUtilities.isRightMouseButton(evt))
2812 .removeActionListener(radioItem.getActionListeners()[0]);
2814 int option = JOptionPane.showInternalConfirmDialog(
2815 jalview.gui.Desktop.desktop,
2816 "Remove from default list?",
2817 "Remove user defined colour",
2818 JOptionPane.YES_NO_OPTION);
2819 if (option == JOptionPane.YES_OPTION)
2821 jalview.gui.UserDefinedColours
2822 .removeColourFromDefaults(radioItem.getText());
2823 colourMenu.remove(radioItem);
2827 radioItem.addActionListener(new ActionListener()
2829 public void actionPerformed(ActionEvent evt)
2831 userDefinedColour_actionPerformed(evt);
2838 radioItem.addActionListener(new ActionListener()
2840 public void actionPerformed(ActionEvent evt)
2842 userDefinedColour_actionPerformed(evt);
2846 colourMenu.insert(radioItem, 15);
2847 colours.add(radioItem);
2858 public void PIDColour_actionPerformed(ActionEvent e)
2860 changeColour(new PIDColourScheme());
2869 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
2871 changeColour(new Blosum62ColourScheme());
2880 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
2882 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2883 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
2884 .getAlignment().getSequenceAt(0), null);
2885 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
2886 viewport.alignment));
2887 alignPanel.paintAlignment(true);
2896 public void sortIDMenuItem_actionPerformed(ActionEvent e)
2898 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2899 AlignmentSorter.sortByID(viewport.getAlignment());
2900 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
2901 alignPanel.paintAlignment(true);
2910 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
2912 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
2913 AlignmentSorter.sortByGroup(viewport.getAlignment());
2914 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
2915 viewport.alignment));
2917 alignPanel.paintAlignment(true);
2926 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
2928 new RedundancyPanel(alignPanel, this);
2937 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
2939 if ((viewport.getSelectionGroup() == null)
2940 || (viewport.getSelectionGroup().getSize() < 2))
2942 JOptionPane.showInternalMessageDialog(this,
2943 "You must select at least 2 sequences.", "Invalid Selection",
2944 JOptionPane.WARNING_MESSAGE);
2948 JInternalFrame frame = new JInternalFrame();
2949 frame.setContentPane(new PairwiseAlignPanel(viewport));
2950 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
2960 public void PCAMenuItem_actionPerformed(ActionEvent e)
2962 if (((viewport.getSelectionGroup() != null)
2963 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
2964 .getSelectionGroup().getSize() > 0))
2965 || (viewport.getAlignment().getHeight() < 4))
2967 JOptionPane.showInternalMessageDialog(this,
2968 "Principal component analysis must take\n"
2969 + "at least 4 input sequences.",
2970 "Sequence selection insufficient",
2971 JOptionPane.WARNING_MESSAGE);
2976 new PCAPanel(alignPanel);
2979 public void autoCalculate_actionPerformed(ActionEvent e)
2981 viewport.autoCalculateConsensus = autoCalculate.isSelected();
2982 if (viewport.autoCalculateConsensus)
2984 viewport.firePropertyChange("alignment", null, viewport
2985 .getAlignment().getSequences());
2995 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
2997 NewTreePanel("AV", "PID", "Average distance tree using PID");
3006 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3008 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3017 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3019 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3028 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3030 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3043 void NewTreePanel(String type, String pwType, String title)
3047 if (viewport.getSelectionGroup() != null)
3049 if (viewport.getSelectionGroup().getSize() < 3)
3054 "You need to have more than two sequences selected to build a tree!",
3055 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3060 SequenceGroup sg = viewport.getSelectionGroup();
3062 /* Decide if the selection is a column region */
3063 while (s < sg.getSize())
3065 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3071 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3072 + "Try using the Pad function in the edit menu,\n"
3073 + "or one of the multiple sequence alignment web services.",
3074 "Sequences in selection are not aligned",
3075 JOptionPane.WARNING_MESSAGE);
3081 title = title + " on region";
3082 tp = new TreePanel(alignPanel, type, pwType);
3086 // are the sequences aligned?
3087 if (!viewport.alignment.isAligned())
3092 "The sequences must be aligned before creating a tree.\n"
3093 + "Try using the Pad function in the edit menu,\n"
3094 + "or one of the multiple sequence alignment web services.",
3095 "Sequences not aligned",
3096 JOptionPane.WARNING_MESSAGE);
3101 if (viewport.alignment.getHeight() < 2)
3106 tp = new TreePanel(alignPanel, type, pwType);
3111 if (viewport.viewName != null)
3113 title += viewport.viewName + " of ";
3116 title += this.title;
3118 Desktop.addInternalFrame(tp, title, 600, 500);
3129 public void addSortByOrderMenuItem(String title,
3130 final AlignmentOrder order)
3132 final JMenuItem item = new JMenuItem("by " + title);
3134 item.addActionListener(new java.awt.event.ActionListener()
3136 public void actionPerformed(ActionEvent e)
3138 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3140 // TODO: JBPNote - have to map order entries to curent SequenceI
3142 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3144 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3145 viewport.alignment));
3147 alignPanel.paintAlignment(true);
3153 * Add a new sort by annotation score menu item
3156 * the menu to add the option to
3158 * the label used to retrieve scores for each sequence on the
3161 public void addSortByAnnotScoreMenuItem(JMenu sort,
3162 final String scoreLabel)
3164 final JMenuItem item = new JMenuItem(scoreLabel);
3166 item.addActionListener(new java.awt.event.ActionListener()
3168 public void actionPerformed(ActionEvent e)
3170 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3171 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3172 .getAlignment());// ,viewport.getSelectionGroup());
3173 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3174 viewport.alignment));
3175 alignPanel.paintAlignment(true);
3181 * last hash for alignment's annotation array - used to minimise cost of
3184 protected int _annotationScoreVectorHash;
3187 * search the alignment and rebuild the sort by annotation score submenu the
3188 * last alignment annotation vector hash is stored to minimize cost of
3189 * rebuilding in subsequence calls.
3192 public void buildSortByAnnotationScoresMenu()
3194 if (viewport.alignment.getAlignmentAnnotation() == null)
3199 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3201 sortByAnnotScore.removeAll();
3202 // almost certainly a quicker way to do this - but we keep it simple
3203 Hashtable scoreSorts = new Hashtable();
3204 AlignmentAnnotation aann[];
3205 Enumeration sq = viewport.alignment.getSequences().elements();
3206 while (sq.hasMoreElements())
3208 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3209 for (int i = 0; aann != null && i < aann.length; i++)
3211 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3213 scoreSorts.put(aann[i].label, aann[i].label);
3217 Enumeration labels = scoreSorts.keys();
3218 while (labels.hasMoreElements())
3220 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3223 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3226 _annotationScoreVectorHash = viewport.alignment
3227 .getAlignmentAnnotation().hashCode();
3232 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3233 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3234 * call. Listeners are added to remove the menu item when the treePanel is
3235 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3239 * Displayed tree window.
3241 * SortBy menu item title.
3243 public void buildTreeMenu()
3245 sortByTreeMenu.removeAll();
3247 Vector comps = (Vector) PaintRefresher.components.get(viewport
3248 .getSequenceSetId());
3249 Vector treePanels = new Vector();
3250 int i, iSize = comps.size();
3251 for (i = 0; i < iSize; i++)
3253 if (comps.elementAt(i) instanceof TreePanel)
3255 treePanels.add(comps.elementAt(i));
3259 iSize = treePanels.size();
3263 sortByTreeMenu.setVisible(false);
3267 sortByTreeMenu.setVisible(true);
3269 for (i = 0; i < treePanels.size(); i++)
3271 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3272 final JMenuItem item = new JMenuItem(tp.getTitle());
3273 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3274 item.addActionListener(new java.awt.event.ActionListener()
3276 public void actionPerformed(ActionEvent e)
3278 SequenceI[] oldOrder = viewport.getAlignment()
3279 .getSequencesArray();
3280 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3282 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3283 viewport.alignment));
3285 alignPanel.paintAlignment(true);
3289 sortByTreeMenu.add(item);
3294 * Work out whether the whole set of sequences or just the selected set will
3295 * be submitted for multiple alignment.
3298 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3300 // Now, check we have enough sequences
3301 AlignmentView msa = null;
3303 if ((viewport.getSelectionGroup() != null)
3304 && (viewport.getSelectionGroup().getSize() > 1))
3306 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3307 // some common interface!
3309 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3310 * SequenceI[sz = seqs.getSize(false)];
3312 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3313 * seqs.getSequenceAt(i); }
3315 msa = viewport.getAlignmentView(true);
3320 * Vector seqs = viewport.getAlignment().getSequences();
3322 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3324 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3325 * seqs.elementAt(i); } }
3327 msa = viewport.getAlignmentView(false);
3333 * Decides what is submitted to a secondary structure prediction service: the
3334 * first sequence in the alignment, or in the current selection, or, if the
3335 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3336 * region or the whole alignment. (where the first sequence in the set is the
3337 * one that the prediction will be for).
3339 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3341 AlignmentView seqs = null;
3343 if ((viewport.getSelectionGroup() != null)
3344 && (viewport.getSelectionGroup().getSize() > 0))
3346 seqs = viewport.getAlignmentView(true);
3350 seqs = viewport.getAlignmentView(false);
3352 // limit sequences - JBPNote in future - could spawn multiple prediction
3354 // TODO: viewport.alignment.isAligned is a global state - the local
3355 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3356 if (!viewport.alignment.isAligned())
3358 seqs.setSequences(new SeqCigar[]
3359 { seqs.getSequences()[0] });
3370 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3372 // Pick the tree file
3373 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3374 .getProperty("LAST_DIRECTORY"));
3375 chooser.setFileView(new JalviewFileView());
3376 chooser.setDialogTitle("Select a newick-like tree file");
3377 chooser.setToolTipText("Load a tree file");
3379 int value = chooser.showOpenDialog(null);
3381 if (value == JalviewFileChooser.APPROVE_OPTION)
3383 String choice = chooser.getSelectedFile().getPath();
3384 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3385 jalview.io.NewickFile fin = null;
3388 fin = new jalview.io.NewickFile(choice, "File");
3389 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3390 } catch (Exception ex)
3392 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3393 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3394 ex.printStackTrace();
3396 if (fin != null && fin.hasWarningMessage())
3398 JOptionPane.showMessageDialog(Desktop.desktop, fin
3399 .getWarningMessage(), "Possible problem with tree file",
3400 JOptionPane.WARNING_MESSAGE);
3405 public TreePanel ShowNewickTree(NewickFile nf, String title)
3407 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3410 public TreePanel ShowNewickTree(NewickFile nf, String title,
3411 AlignmentView input)
3413 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3416 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3417 int h, int x, int y)
3419 return ShowNewickTree(nf, title, null, w, h, x, y);
3423 * Add a treeviewer for the tree extracted from a newick file object to the
3424 * current alignment view
3431 * Associated alignment input data (or null)
3440 * @return TreePanel handle
3442 public TreePanel ShowNewickTree(NewickFile nf, String title,
3443 AlignmentView input, int w, int h, int x, int y)
3445 TreePanel tp = null;
3451 if (nf.getTree() != null)
3453 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3459 tp.setLocation(x, y);
3462 Desktop.addInternalFrame(tp, title, w, h);
3464 } catch (Exception ex)
3466 ex.printStackTrace();
3473 * Generates menu items and listener event actions for web service clients
3476 public void BuildWebServiceMenu()
3478 // TODO: add support for context dependent disabling of services based on
3479 // alignment and current selection
3480 // TODO: add additional serviceHandle parameter to specify abstract handler
3481 // class independently of AbstractName
3482 // TODO: add in rediscovery GUI function to restart discoverer
3483 // TODO: group services by location as well as function and/or introduce
3484 // object broker mechanism.
3485 if ((Discoverer.services != null) && (Discoverer.services.size() > 0))
3487 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3488 // stored or retrieved from elsewhere
3489 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3490 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3491 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3492 // TODO: move GUI generation code onto service implementation - so a
3493 // client instance attaches itself to the GUI with method call like
3494 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3496 Vector wsmenu = new Vector();
3497 final IProgressIndicator af = this;
3500 // Add any Multiple Sequence Alignment Services
3501 final JMenu msawsmenu = new JMenu("Alignment");
3502 for (int i = 0, j = msaws.size(); i < j; i++)
3504 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3506 jalview.ws.WSClient impl = jalview.ws.Discoverer
3507 .getServiceClient(sh);
3508 impl.attachWSMenuEntry(msawsmenu, this);
3511 wsmenu.add(msawsmenu);
3513 if (secstrpr != null)
3515 // Add any secondary structure prediction services
3516 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3517 for (int i = 0, j = secstrpr.size(); i < j; i++)
3519 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3521 jalview.ws.WSClient impl = jalview.ws.Discoverer
3522 .getServiceClient(sh);
3523 impl.attachWSMenuEntry(secstrmenu, this);
3525 wsmenu.add(secstrmenu);
3527 if (seqsrch != null)
3529 // Add any sequence search services
3530 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3531 for (int i = 0, j = seqsrch.size(); i < j; i++)
3533 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3535 jalview.ws.WSClient impl = jalview.ws.Discoverer
3536 .getServiceClient(sh);
3537 impl.attachWSMenuEntry(seqsrchmenu, this);
3539 // finally, add the whole shebang onto the webservices menu
3540 wsmenu.add(seqsrchmenu);
3542 resetWebServiceMenu();
3543 for (int i = 0, j = wsmenu.size(); i < j; i++)
3545 webService.add((JMenu) wsmenu.get(i));
3550 resetWebServiceMenu();
3551 this.webService.add(this.webServiceNoServices);
3556 * empty the web service menu and add any ad-hoc functions not dynamically
3560 private void resetWebServiceMenu()
3562 webService.removeAll();
3563 // Temporary hack - DBRef Fetcher always top level ws entry.
3564 JMenuItem rfetch = new JMenuItem("Fetch DB References");
3566 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
3567 webService.add(rfetch);
3568 rfetch.addActionListener(new ActionListener()
3571 public void actionPerformed(ActionEvent e)
3573 new Thread(new Runnable()
3578 new jalview.ws.DBRefFetcher(alignPanel.av
3579 .getSequenceSelection(), alignPanel.alignFrame)
3580 .fetchDBRefs(false);
3590 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3591 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3592 * getProperty("LAST_DIRECTORY"));
3594 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3595 * to Vamsas file"); chooser.setToolTipText("Export");
3597 * int value = chooser.showSaveDialog(this);
3599 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3600 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3601 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3602 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3605 * prototype of an automatically enabled/disabled analysis function
3608 protected void setShowProductsEnabled()
3610 SequenceI[] selection = viewport.getSequenceSelection();
3611 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3612 viewport.getAlignment().getDataset()))
3614 showProducts.setEnabled(true);
3619 showProducts.setEnabled(false);
3624 * search selection for sequence xRef products and build the show products
3629 * @return true if showProducts menu should be enabled.
3631 public boolean canShowProducts(SequenceI[] selection,
3632 boolean isRegionSelection, Alignment dataset)
3634 boolean showp = false;
3637 showProducts.removeAll();
3638 final boolean dna = viewport.getAlignment().isNucleotide();
3639 final Alignment ds = dataset;
3640 String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection,
3643 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
3644 // selection, dataset, true);
3645 final SequenceI[] sel = selection;
3646 for (int t = 0; ptypes != null && t < ptypes.length; t++)
3649 final boolean isRegSel = isRegionSelection;
3650 final AlignFrame af = this;
3651 final String source = ptypes[t];
3652 JMenuItem xtype = new JMenuItem(ptypes[t]);
3653 xtype.addActionListener(new ActionListener()
3656 public void actionPerformed(ActionEvent e)
3658 // TODO: new thread for this call with vis-delay
3659 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
3660 isRegSel, dna, source);
3664 showProducts.add(xtype);
3666 showProducts.setVisible(showp);
3667 showProducts.setEnabled(showp);
3668 } catch (Exception e)
3670 jalview.bin.Cache.log
3672 "canTranslate threw an exception - please report to help@jalview.org",
3679 protected void showProductsFor(SequenceI[] sel, Alignment ds,
3680 boolean isRegSel, boolean dna, String source)
3682 final boolean fisRegSel = isRegSel;
3683 final boolean fdna = dna;
3684 final String fsrc = source;
3685 final AlignFrame ths = this;
3686 final SequenceI[] fsel = sel;
3687 Runnable foo = new Runnable()
3692 final long sttime = System.currentTimeMillis();
3693 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
3696 Alignment ds = ths.getViewport().alignment.getDataset(); // update
3700 Alignment prods = CrossRef
3701 .findXrefSequences(fsel, fdna, fsrc, ds);
3704 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3705 for (int s = 0; s < sprods.length; s++)
3707 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3708 if (ds.getSequences() == null
3709 || !ds.getSequences().contains(
3710 sprods[s].getDatasetSequence()))
3711 ds.addSequence(sprods[s].getDatasetSequence());
3712 sprods[s].updatePDBIds();
3714 Alignment al = new Alignment(sprods);
3715 AlignedCodonFrame[] cf = prods.getCodonFrames();
3716 for (int s = 0; cf != null && s < cf.length; s++)
3718 al.addCodonFrame(cf[s]);
3722 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
3724 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
3725 + " for " + ((fisRegSel) ? "selected region of " : "")
3727 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3732 System.err.println("No Sequences generated for xRef type "
3735 } catch (Exception e)
3737 jalview.bin.Cache.log.error(
3738 "Exception when finding crossreferences", e);
3739 } catch (OutOfMemoryError e)
3741 new OOMWarning("whilst fetching crossreferences", e);
3744 jalview.bin.Cache.log.error("Error when finding crossreferences",
3747 ths.setProgressBar("Finished searching for sequences from " + fsrc,
3752 Thread frunner = new Thread(foo);
3756 public boolean canShowTranslationProducts(SequenceI[] selection,
3757 AlignmentI alignment)
3762 return (jalview.analysis.Dna.canTranslate(selection, viewport
3763 .getViewAsVisibleContigs(true)));
3764 } catch (Exception e)
3766 jalview.bin.Cache.log
3768 "canTranslate threw an exception - please report to help@jalview.org",
3774 public void showProducts_actionPerformed(ActionEvent e)
3776 // /////////////////////////////
3777 // Collect Data to be translated/transferred
3779 SequenceI[] selection = viewport.getSequenceSelection();
3780 AlignmentI al = null;
3783 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
3784 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
3785 viewport.getAlignment().getDataset());
3786 } catch (Exception ex)
3789 jalview.bin.Cache.log.debug("Exception during translation.", ex);
3796 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3797 "Translation Failed", JOptionPane.WARNING_MESSAGE);
3801 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3802 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
3803 DEFAULT_WIDTH, DEFAULT_HEIGHT);
3807 public void showTranslation_actionPerformed(ActionEvent e)
3809 // /////////////////////////////
3810 // Collect Data to be translated/transferred
3812 SequenceI[] selection = viewport.getSequenceSelection();
3813 String[] seqstring = viewport.getViewAsString(true);
3814 AlignmentI al = null;
3817 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
3818 viewport.getViewAsVisibleContigs(true), viewport
3819 .getGapCharacter(), viewport.alignment
3820 .getAlignmentAnnotation(), viewport.alignment
3821 .getWidth(), viewport.getAlignment().getDataset());
3822 } catch (Exception ex)
3825 jalview.bin.Cache.log.debug("Exception during translation.", ex);
3832 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
3833 "Translation Failed", JOptionPane.WARNING_MESSAGE);
3837 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
3838 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
3839 DEFAULT_WIDTH, DEFAULT_HEIGHT);
3844 * Try to load a features file onto the alignment.
3847 * contents or path to retrieve file
3849 * access mode of file (see jalview.io.AlignFile)
3850 * @return true if features file was parsed corectly.
3852 public boolean parseFeaturesFile(String file, String type)
3854 boolean featuresFile = false;
3857 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
3858 .getDataset(), alignPanel.seqPanel.seqCanvas
3859 .getFeatureRenderer().featureColours, false);
3860 } catch (Exception ex)
3862 ex.printStackTrace();
3867 viewport.showSequenceFeatures = true;
3868 showSeqFeatures.setSelected(true);
3869 alignPanel.paintAlignment(true);
3872 return featuresFile;
3875 public void dragEnter(DropTargetDragEvent evt)
3879 public void dragExit(DropTargetEvent evt)
3883 public void dragOver(DropTargetDragEvent evt)
3887 public void dropActionChanged(DropTargetDragEvent evt)
3891 public void drop(DropTargetDropEvent evt)
3893 Transferable t = evt.getTransferable();
3894 java.util.List files = null;
3898 DataFlavor uriListFlavor = new DataFlavor(
3899 "text/uri-list;class=java.lang.String");
3900 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3902 // Works on Windows and MacOSX
3903 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3904 files = (java.util.List) t
3905 .getTransferData(DataFlavor.javaFileListFlavor);
3907 else if (t.isDataFlavorSupported(uriListFlavor))
3909 // This is used by Unix drag system
3910 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
3911 String data = (String) t.getTransferData(uriListFlavor);
3912 files = new java.util.ArrayList(1);
3913 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3914 data, "\r\n"); st.hasMoreTokens();)
3916 String s = st.nextToken();
3917 if (s.startsWith("#"))
3919 // the line is a comment (as per the RFC 2483)
3923 java.net.URI uri = new java.net.URI(s);
3924 java.io.File file = new java.io.File(uri);
3928 } catch (Exception e)
3930 e.printStackTrace();
3937 for (int i = 0; i < files.size(); i++)
3939 loadJalviewDataFile(files.get(i).toString());
3941 } catch (Exception ex)
3943 ex.printStackTrace();
3949 * Attempt to load a "dropped" file: First by testing whether it's and
3950 * Annotation file, then a JNet file, and finally a features file. If all are
3951 * false then the user may have dropped an alignment file onto this
3955 * either a filename or a URL string.
3957 public void loadJalviewDataFile(String file)
3961 String protocol = "File";
3963 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
3968 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
3969 viewport.alignment, file, protocol);
3973 // try to see if its a JNet 'concise' style annotation file *before* we
3974 // try to parse it as a features file
3975 String format = new IdentifyFile().Identify(file, protocol);
3976 if (format.equalsIgnoreCase("JnetFile"))
3978 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
3980 new JnetAnnotationMaker().add_annotation(predictions, viewport
3981 .getAlignment(), 0, false);
3982 isAnnotation = true;
3986 // try to parse it as a features file
3987 boolean isGroupsFile = parseFeaturesFile(file, protocol);
3988 // if it wasn't a features file then we just treat it as a general
3989 // alignment file to load into the current view.
3992 new FileLoader().LoadFile(viewport, file, protocol, format);
3996 alignPanel.paintAlignment(true);
4003 alignPanel.adjustAnnotationHeight();
4004 viewport.updateSequenceIdColours();
4005 buildSortByAnnotationScoresMenu();
4006 alignPanel.paintAlignment(true);
4008 } catch (Exception ex)
4010 ex.printStackTrace();
4014 public void tabSelectionChanged(int index)
4018 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4019 viewport = alignPanel.av;
4020 setMenusFromViewport(viewport);
4024 public void tabbedPane_mousePressed(MouseEvent e)
4026 if (SwingUtilities.isRightMouseButton(e))
4028 String reply = JOptionPane.showInternalInputDialog(this,
4029 "Enter View Name", "Edit View Name",
4030 JOptionPane.QUESTION_MESSAGE);
4034 viewport.viewName = reply;
4035 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4040 public AlignViewport getCurrentView()
4046 * Open the dialog for regex description parsing.
4048 protected void extractScores_actionPerformed(ActionEvent e)
4050 ParseProperties pp = new jalview.analysis.ParseProperties(
4051 viewport.alignment);
4052 // TODO: verify regex and introduce GUI dialog for version 2.5
4053 // if (pp.getScoresFromDescription("col", "score column ",
4054 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4056 if (pp.getScoresFromDescription("description column",
4057 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4059 buildSortByAnnotationScoresMenu();
4064 class PrintThread extends Thread
4068 public PrintThread(AlignmentPanel ap)
4073 static PageFormat pf;
4077 PrinterJob printJob = PrinterJob.getPrinterJob();
4081 printJob.setPrintable(ap, pf);
4085 printJob.setPrintable(ap);
4088 if (printJob.printDialog())
4093 } catch (Exception PrintException)
4095 PrintException.printStackTrace();