2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
25 import java.awt.datatransfer.*;
26 import java.awt.dnd.*;
27 import java.awt.event.*;
28 import java.awt.print.*;
30 import javax.swing.event.MenuEvent;
32 import jalview.analysis.*;
33 import jalview.bin.Cache;
34 import jalview.commands.*;
35 import jalview.datamodel.*;
37 import jalview.jbgui.*;
38 import jalview.schemes.*;
40 import jalview.ws.jws1.Discoverer;
41 import jalview.ws.jws2.Jws2Discoverer;
49 public class AlignFrame extends GAlignFrame implements DropTargetListener,
54 public static final int DEFAULT_WIDTH = 700;
57 public static final int DEFAULT_HEIGHT = 500;
59 public AlignmentPanel alignPanel;
61 AlignViewport viewport;
63 Vector alignPanels = new Vector();
66 * Last format used to load or save alignments in this window
68 String currentFileFormat = null;
71 * Current filename for this alignment
73 String fileName = null;
76 * Creates a new AlignFrame object with specific width and height.
82 public AlignFrame(AlignmentI al, int width, int height)
84 this(al, null, width, height);
88 * Creates a new AlignFrame object with specific width, height and
94 * @param sequenceSetId
96 public AlignFrame(AlignmentI al, int width, int height,
99 this(al, null, width, height, sequenceSetId);
103 * Creates a new AlignFrame object with specific width, height and
109 * @param sequenceSetId
112 public AlignFrame(AlignmentI al, int width, int height,
113 String sequenceSetId, String viewId)
115 this(al, null, width, height, sequenceSetId, viewId);
119 * new alignment window with hidden columns
123 * @param hiddenColumns
124 * ColumnSelection or null
126 * Width of alignment frame
130 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
131 int width, int height)
133 this(al, hiddenColumns, width, height, null);
137 * Create alignment frame for al with hiddenColumns, a specific width and
138 * height, and specific sequenceId
141 * @param hiddenColumns
144 * @param sequenceSetId
147 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
148 int width, int height, String sequenceSetId)
150 this(al, hiddenColumns, width, height, sequenceSetId, null);
154 * Create alignment frame for al with hiddenColumns, a specific width and
155 * height, and specific sequenceId
158 * @param hiddenColumns
161 * @param sequenceSetId
166 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
167 int width, int height, String sequenceSetId, String viewId)
169 setSize(width, height);
170 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
172 alignPanel = new AlignmentPanel(this, viewport);
174 if (al.getDataset() == null)
179 addAlignmentPanel(alignPanel, true);
184 * Make a new AlignFrame from exisiting alignmentPanels
191 public AlignFrame(AlignmentPanel ap)
195 addAlignmentPanel(ap, false);
200 * initalise the alignframe from the underlying viewport data and the
205 if (viewport.conservation == null)
207 BLOSUM62Colour.setEnabled(false);
208 conservationMenuItem.setEnabled(false);
209 modifyConservation.setEnabled(false);
210 // PIDColour.setEnabled(false);
211 // abovePIDThreshold.setEnabled(false);
212 // modifyPID.setEnabled(false);
215 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
218 if (sortby.equals("Id"))
220 sortIDMenuItem_actionPerformed(null);
222 else if (sortby.equals("Pairwise Identity"))
224 sortPairwiseMenuItem_actionPerformed(null);
227 if (Desktop.desktop != null)
229 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
230 addServiceListeners();
231 setGUINucleotide(viewport.alignment.isNucleotide());
234 setMenusFromViewport(viewport);
235 buildSortByAnnotationScoresMenu();
236 if (viewport.wrapAlignment)
238 wrapMenuItem_actionPerformed(null);
241 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
243 this.overviewMenuItem_actionPerformed(null);
251 * Change the filename and format for the alignment, and enable the 'reload'
252 * button functionality.
259 public void setFileName(String file, String format)
262 currentFileFormat = format;
263 reload.setEnabled(true);
266 void addKeyListener()
268 addKeyListener(new KeyAdapter()
270 public void keyPressed(KeyEvent evt)
272 if (viewport.cursorMode
273 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
274 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
275 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
276 && Character.isDigit(evt.getKeyChar()))
277 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
279 switch (evt.getKeyCode())
282 case 27: // escape key
283 deselectAllSequenceMenuItem_actionPerformed(null);
287 case KeyEvent.VK_DOWN:
288 if (evt.isAltDown() || !viewport.cursorMode)
289 moveSelectedSequences(false);
290 if (viewport.cursorMode)
291 alignPanel.seqPanel.moveCursor(0, 1);
295 if (evt.isAltDown() || !viewport.cursorMode)
296 moveSelectedSequences(true);
297 if (viewport.cursorMode)
298 alignPanel.seqPanel.moveCursor(0, -1);
302 case KeyEvent.VK_LEFT:
303 if (evt.isAltDown() || !viewport.cursorMode)
304 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
306 alignPanel.seqPanel.moveCursor(-1, 0);
310 case KeyEvent.VK_RIGHT:
311 if (evt.isAltDown() || !viewport.cursorMode)
312 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
314 alignPanel.seqPanel.moveCursor(1, 0);
317 case KeyEvent.VK_SPACE:
318 if (viewport.cursorMode)
320 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
321 || evt.isShiftDown() || evt.isAltDown());
325 case KeyEvent.VK_DELETE:
326 case KeyEvent.VK_BACK_SPACE:
327 if (!viewport.cursorMode)
329 cut_actionPerformed(null);
333 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
334 || evt.isShiftDown() || evt.isAltDown());
340 if (viewport.cursorMode)
342 alignPanel.seqPanel.setCursorRow();
346 if (viewport.cursorMode && !evt.isControlDown())
348 alignPanel.seqPanel.setCursorColumn();
352 if (viewport.cursorMode)
354 alignPanel.seqPanel.setCursorPosition();
358 case KeyEvent.VK_ENTER:
359 case KeyEvent.VK_COMMA:
360 if (viewport.cursorMode)
362 alignPanel.seqPanel.setCursorRowAndColumn();
367 if (viewport.cursorMode)
369 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
373 if (viewport.cursorMode)
375 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
380 viewport.cursorMode = !viewport.cursorMode;
381 statusBar.setText("Keyboard editing mode is "
382 + (viewport.cursorMode ? "on" : "off"));
383 if (viewport.cursorMode)
385 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
386 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
388 alignPanel.seqPanel.seqCanvas.repaint();
394 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
395 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
397 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
399 javax.help.HelpBroker hb = hs.createHelpBroker();
400 hb.setCurrentID("home");
401 hb.setDisplayed(true);
402 } catch (Exception ex)
404 ex.printStackTrace();
409 boolean toggleSeqs = !evt.isControlDown();
410 boolean toggleCols = !evt.isShiftDown();
411 toggleHiddenRegions(toggleSeqs, toggleCols);
414 case KeyEvent.VK_PAGE_UP:
415 if (viewport.wrapAlignment)
417 alignPanel.scrollUp(true);
421 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
422 - viewport.endSeq + viewport.startSeq);
425 case KeyEvent.VK_PAGE_DOWN:
426 if (viewport.wrapAlignment)
428 alignPanel.scrollUp(false);
432 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
433 + viewport.endSeq - viewport.startSeq);
439 public void keyReleased(KeyEvent evt)
441 switch (evt.getKeyCode())
443 case KeyEvent.VK_LEFT:
444 if (evt.isAltDown() || !viewport.cursorMode)
445 viewport.firePropertyChange("alignment", null, viewport
446 .getAlignment().getSequences());
449 case KeyEvent.VK_RIGHT:
450 if (evt.isAltDown() || !viewport.cursorMode)
451 viewport.firePropertyChange("alignment", null, viewport
452 .getAlignment().getSequences());
459 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
461 ap.alignFrame = this;
463 alignPanels.addElement(ap);
465 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
467 int aSize = alignPanels.size();
469 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
471 if (aSize == 1 && ap.av.viewName == null)
473 this.getContentPane().add(ap, BorderLayout.CENTER);
479 setInitialTabVisible();
482 expandViews.setEnabled(true);
483 gatherViews.setEnabled(true);
484 tabbedPane.addTab(ap.av.viewName, ap);
486 ap.setVisible(false);
493 ap.av.alignment.padGaps();
495 ap.av.updateConservation(ap);
496 ap.av.updateConsensus(ap);
500 public void setInitialTabVisible()
502 expandViews.setEnabled(true);
503 gatherViews.setEnabled(true);
504 tabbedPane.setVisible(true);
505 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
506 tabbedPane.addTab(first.av.viewName, first);
507 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
510 public AlignViewport getViewport()
515 /* Set up intrinsic listeners for dynamically generated GUI bits. */
516 private void addServiceListeners()
518 final java.beans.PropertyChangeListener thisListener;
519 Desktop.instance.addJalviewPropertyChangeListener("services",
520 thisListener = new java.beans.PropertyChangeListener()
522 public void propertyChange(PropertyChangeEvent evt)
524 // // System.out.println("Discoverer property change.");
525 // if (evt.getPropertyName().equals("services"))
527 SwingUtilities.invokeLater(new Runnable()
533 .println("Rebuild WS Menu for service change");
534 BuildWebServiceMenu();
541 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
543 public void internalFrameClosed(
544 javax.swing.event.InternalFrameEvent evt)
546 System.out.println("deregistering discoverer listener");
547 Desktop.instance.removeJalviewPropertyChangeListener("services",
549 closeMenuItem_actionPerformed(true);
552 // Finally, build the menu once to get current service state
553 javax.swing.SwingUtilities.invokeLater(new Runnable() {
554 public void run() { BuildWebServiceMenu();}
558 public void setGUINucleotide(boolean nucleotide)
560 showTranslation.setVisible(nucleotide);
561 conservationMenuItem.setEnabled(!nucleotide);
562 modifyConservation.setEnabled(!nucleotide);
563 showGroupConservation.setEnabled(!nucleotide);
564 // Remember AlignFrame always starts as protein
567 calculateMenu.remove(calculateMenu.getItemCount() - 2);
572 * set up menus for the currently viewport. This may be called after any
573 * operation that affects the data in the current view (selection changed,
574 * etc) to update the menus to reflect the new state.
576 public void setMenusForViewport()
578 setMenusFromViewport(viewport);
582 * Need to call this method when tabs are selected for multiple views, or when
583 * loading from Jalview2XML.java
588 void setMenusFromViewport(AlignViewport av)
590 padGapsMenuitem.setSelected(av.padGaps);
591 colourTextMenuItem.setSelected(av.showColourText);
592 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
593 conservationMenuItem.setSelected(av.getConservationSelected());
594 seqLimits.setSelected(av.getShowJVSuffix());
595 idRightAlign.setSelected(av.rightAlignIds);
596 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
597 renderGapsMenuItem.setSelected(av.renderGaps);
598 wrapMenuItem.setSelected(av.wrapAlignment);
599 scaleAbove.setVisible(av.wrapAlignment);
600 scaleLeft.setVisible(av.wrapAlignment);
601 scaleRight.setVisible(av.wrapAlignment);
602 annotationPanelMenuItem.setState(av.showAnnotation);
603 viewBoxesMenuItem.setSelected(av.showBoxes);
604 viewTextMenuItem.setSelected(av.showText);
605 showNonconservedMenuItem.setSelected(av.showUnconserved);
606 showGroupConsensus.setSelected(av.showGroupConsensus);
607 showGroupConservation.setSelected(av.showGroupConservation);
608 showConsensusHistogram.setSelected(av.showConsensusHistogram);
609 showSequenceLogo.setSelected(av.showSequenceLogo);
610 setColourSelected(ColourSchemeProperty.getColourName(av
611 .getGlobalColourScheme()));
613 showSeqFeatures.setSelected(av.showSequenceFeatures);
614 hiddenMarkers.setState(av.showHiddenMarkers);
615 applyToAllGroups.setState(av.colourAppliesToAllGroups);
616 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
617 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
619 setShowProductsEnabled();
624 Hashtable progressBars, progressBarHandlers;
629 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
631 public void setProgressBar(String message, long id)
633 if (progressBars == null)
635 progressBars = new Hashtable();
636 progressBarHandlers = new Hashtable();
639 JPanel progressPanel;
640 Long lId = new Long(id);
641 GridLayout layout = (GridLayout) statusPanel.getLayout();
642 if (progressBars.get(lId) != null)
644 progressPanel = (JPanel) progressBars.get(new Long(id));
645 statusPanel.remove(progressPanel);
646 progressBars.remove(lId);
647 progressPanel = null;
650 statusBar.setText(message);
652 if (progressBarHandlers.contains(lId))
654 progressBarHandlers.remove(lId);
656 layout.setRows(layout.getRows() - 1);
660 progressPanel = new JPanel(new BorderLayout(10, 5));
662 JProgressBar progressBar = new JProgressBar();
663 progressBar.setIndeterminate(true);
665 progressPanel.add(new JLabel(message), BorderLayout.WEST);
666 progressPanel.add(progressBar, BorderLayout.CENTER);
668 layout.setRows(layout.getRows() + 1);
669 statusPanel.add(progressPanel);
671 progressBars.put(lId, progressPanel);
674 setMenusForViewport();
678 public void registerHandler(final long id,
679 final IProgressIndicatorHandler handler)
681 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
684 "call setProgressBar before registering the progress bar's handler.");
686 progressBarHandlers.put(new Long(id), handler);
687 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
688 if (handler.canCancel())
690 JButton cancel = new JButton("Cancel");
691 final IProgressIndicator us = this;
692 cancel.addActionListener(new ActionListener()
695 public void actionPerformed(ActionEvent e)
697 handler.cancelActivity(id);
698 us.setProgressBar("Cancelled "
699 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
702 progressPanel.add(cancel, BorderLayout.EAST);
708 * @return true if any progress bars are still active
710 public boolean operationInProgress()
712 if (progressBars != null && progressBars.size() > 0)
720 * Added so Castor Mapping file can obtain Jalview Version
722 public String getVersion()
724 return jalview.bin.Cache.getProperty("VERSION");
727 public FeatureRenderer getFeatureRenderer()
729 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
732 public void fetchSequence_actionPerformed(ActionEvent e)
734 new SequenceFetcher(this);
737 public void addFromFile_actionPerformed(ActionEvent e)
739 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
742 public void reload_actionPerformed(ActionEvent e)
744 if (fileName != null)
746 // TODO: work out how to recover feature settings for correct view(s) when
748 if (currentFileFormat.equals("Jalview"))
750 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
751 for (int i = 0; i < frames.length; i++)
753 if (frames[i] instanceof AlignFrame && frames[i] != this
754 && ((AlignFrame) frames[i]).fileName.equals(fileName))
758 frames[i].setSelected(true);
759 Desktop.instance.closeAssociatedWindows();
760 } catch (java.beans.PropertyVetoException ex)
766 Desktop.instance.closeAssociatedWindows();
768 FileLoader loader = new FileLoader();
769 String protocol = fileName.startsWith("http:") ? "URL" : "File";
770 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
774 Rectangle bounds = this.getBounds();
776 FileLoader loader = new FileLoader();
777 String protocol = fileName.startsWith("http:") ? "URL" : "File";
778 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
779 protocol, currentFileFormat);
781 newframe.setBounds(bounds);
782 if (featureSettings != null && featureSettings.isShowing())
784 final Rectangle fspos = featureSettings.frame.getBounds();
785 // TODO: need a 'show feature settings' function that takes bounds -
786 // need to refactor Desktop.addFrame
787 newframe.featureSettings_actionPerformed(null);
788 final FeatureSettings nfs = newframe.featureSettings;
789 SwingUtilities.invokeLater(new Runnable()
793 nfs.frame.setBounds(fspos);
796 this.featureSettings.close();
797 this.featureSettings = null;
799 this.closeMenuItem_actionPerformed(true);
804 public void addFromText_actionPerformed(ActionEvent e)
806 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
809 public void addFromURL_actionPerformed(ActionEvent e)
811 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
814 public void save_actionPerformed(ActionEvent e)
817 || (currentFileFormat == null || !jalview.io.FormatAdapter
818 .isValidIOFormat(currentFileFormat, true))
819 || fileName.startsWith("http"))
821 saveAs_actionPerformed(null);
825 saveAlignment(fileName, currentFileFormat);
835 public void saveAs_actionPerformed(ActionEvent e)
837 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
838 .getProperty("LAST_DIRECTORY"),
839 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
840 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
841 currentFileFormat, false);
843 chooser.setFileView(new JalviewFileView());
844 chooser.setDialogTitle("Save Alignment to file");
845 chooser.setToolTipText("Save");
847 int value = chooser.showSaveDialog(this);
849 if (value == JalviewFileChooser.APPROVE_OPTION)
851 currentFileFormat = chooser.getSelectedFormat();
852 if (currentFileFormat == null)
854 JOptionPane.showInternalMessageDialog(Desktop.desktop,
855 "You must select a file format before saving!",
856 "File format not specified", JOptionPane.WARNING_MESSAGE);
857 value = chooser.showSaveDialog(this);
861 fileName = chooser.getSelectedFile().getPath();
863 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
866 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
867 if (currentFileFormat.indexOf(" ") > -1)
869 currentFileFormat = currentFileFormat.substring(0,
870 currentFileFormat.indexOf(" "));
872 saveAlignment(fileName, currentFileFormat);
876 public boolean saveAlignment(String file, String format)
878 boolean success = true;
880 if (format.equalsIgnoreCase("Jalview"))
882 String shortName = title;
884 if (shortName.indexOf(java.io.File.separatorChar) > -1)
886 shortName = shortName.substring(shortName
887 .lastIndexOf(java.io.File.separatorChar) + 1);
890 success = new Jalview2XML().SaveAlignment(this, file, shortName);
892 statusBar.setText("Successfully saved to file: " + fileName + " in "
893 + format + " format.");
898 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
900 warningMessage("Cannot save file " + fileName + " using format "
901 + format, "Alignment output format not supported");
902 saveAs_actionPerformed(null);
903 // JBPNote need to have a raise_gui flag here
907 String[] omitHidden = null;
909 if (viewport.hasHiddenColumns)
911 int reply = JOptionPane
912 .showInternalConfirmDialog(
914 "The Alignment contains hidden columns."
915 + "\nDo you want to save only the visible alignment?",
916 "Save / Omit Hidden Columns",
917 JOptionPane.YES_NO_OPTION,
918 JOptionPane.QUESTION_MESSAGE);
920 if (reply == JOptionPane.YES_OPTION)
922 omitHidden = viewport.getViewAsString(false);
925 FormatAdapter f = new FormatAdapter();
926 String output = f.formatSequences(format,
927 (Alignment) viewport.alignment, // class cast exceptions will
928 // occur in the distant future
929 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
939 java.io.PrintWriter out = new java.io.PrintWriter(
940 new java.io.FileWriter(file));
945 statusBar.setText("Successfully saved to file: " + fileName
946 + " in " + format + " format.");
947 } catch (Exception ex)
950 ex.printStackTrace();
957 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
958 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
964 private void warningMessage(String warning, String title)
966 if (new jalview.util.Platform().isHeadless())
968 System.err.println("Warning: " + title + "\nWarning: " + warning);
973 JOptionPane.showInternalMessageDialog(this, warning, title,
974 JOptionPane.WARNING_MESSAGE);
985 protected void outputText_actionPerformed(ActionEvent e)
987 String[] omitHidden = null;
989 if (viewport.hasHiddenColumns)
991 int reply = JOptionPane
992 .showInternalConfirmDialog(
994 "The Alignment contains hidden columns."
995 + "\nDo you want to output only the visible alignment?",
996 "Save / Omit Hidden Columns",
997 JOptionPane.YES_NO_OPTION,
998 JOptionPane.QUESTION_MESSAGE);
1000 if (reply == JOptionPane.YES_OPTION)
1002 omitHidden = viewport.getViewAsString(false);
1006 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1007 cap.setForInput(null);
1010 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1011 viewport.alignment, omitHidden, viewport.colSel));
1012 Desktop.addInternalFrame(cap, "Alignment output - "
1013 + e.getActionCommand(), 600, 500);
1014 } catch (OutOfMemoryError oom)
1016 new OOMWarning("Outputting alignment as "+e.getActionCommand(),oom);
1028 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1030 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
1031 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
1032 .getFeatureRenderer());
1035 public void createImageMap(File file, String image)
1037 alignPanel.makePNGImageMap(file, image);
1046 public void createPNG(File f)
1048 alignPanel.makePNG(f);
1057 public void createEPS(File f)
1059 alignPanel.makeEPS(f);
1062 public void pageSetup_actionPerformed(ActionEvent e)
1064 PrinterJob printJob = PrinterJob.getPrinterJob();
1065 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1074 public void printMenuItem_actionPerformed(ActionEvent e)
1076 // Putting in a thread avoids Swing painting problems
1077 PrintThread thread = new PrintThread(alignPanel);
1081 public void exportFeatures_actionPerformed(ActionEvent e)
1083 new AnnotationExporter().exportFeatures(alignPanel);
1086 public void exportAnnotations_actionPerformed(ActionEvent e)
1088 new AnnotationExporter().exportAnnotations(alignPanel,
1089 viewport.showAnnotation ? viewport.alignment
1090 .getAlignmentAnnotation() : null, viewport.alignment
1092 ((Alignment) viewport.alignment).alignmentProperties);
1095 public void associatedData_actionPerformed(ActionEvent e)
1097 // Pick the tree file
1098 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1099 .getProperty("LAST_DIRECTORY"));
1100 chooser.setFileView(new JalviewFileView());
1101 chooser.setDialogTitle("Load Jalview Annotations or Features File");
1102 chooser.setToolTipText("Load Jalview Annotations / Features file");
1104 int value = chooser.showOpenDialog(null);
1106 if (value == JalviewFileChooser.APPROVE_OPTION)
1108 String choice = chooser.getSelectedFile().getPath();
1109 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1110 loadJalviewDataFile(choice);
1116 * Close the current view or all views in the alignment frame. If the frame
1117 * only contains one view then the alignment will be removed from memory.
1119 * @param closeAllTabs
1121 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1123 if (alignPanels != null && alignPanels.size() < 2)
1125 closeAllTabs = true;
1130 if (alignPanels != null)
1134 if (this.isClosed())
1136 // really close all the windows - otherwise wait till
1137 // setClosed(true) is called
1138 for (int i = 0; i < alignPanels.size(); i++)
1140 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1147 closeView(alignPanel);
1153 this.setClosed(true);
1155 } catch (Exception ex)
1157 ex.printStackTrace();
1162 * close alignPanel2 and shuffle tabs appropriately.
1164 * @param alignPanel2
1166 public void closeView(AlignmentPanel alignPanel2)
1168 int index = tabbedPane.getSelectedIndex();
1169 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1170 alignPanels.removeElement(alignPanel2);
1172 // if (viewport == alignPanel2.av)
1176 alignPanel2.closePanel();
1179 tabbedPane.removeTabAt(closedindex);
1180 tabbedPane.validate();
1182 if (index > closedindex || index == tabbedPane.getTabCount())
1184 // modify currently selected tab index if necessary.
1188 this.tabSelectionChanged(index);
1194 void updateEditMenuBar()
1197 if (viewport.historyList.size() > 0)
1199 undoMenuItem.setEnabled(true);
1200 CommandI command = (CommandI) viewport.historyList.peek();
1201 undoMenuItem.setText("Undo " + command.getDescription());
1205 undoMenuItem.setEnabled(false);
1206 undoMenuItem.setText("Undo");
1209 if (viewport.redoList.size() > 0)
1211 redoMenuItem.setEnabled(true);
1213 CommandI command = (CommandI) viewport.redoList.peek();
1214 redoMenuItem.setText("Redo " + command.getDescription());
1218 redoMenuItem.setEnabled(false);
1219 redoMenuItem.setText("Redo");
1223 public void addHistoryItem(CommandI command)
1225 if (command.getSize() > 0)
1227 viewport.historyList.push(command);
1228 viewport.redoList.clear();
1229 updateEditMenuBar();
1230 viewport.hasHiddenColumns = (viewport.colSel != null
1231 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1232 .getHiddenColumns().size() > 0);
1238 * @return alignment objects for all views
1240 AlignmentI[] getViewAlignments()
1242 if (alignPanels != null)
1244 Enumeration e = alignPanels.elements();
1245 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1246 for (int i = 0; e.hasMoreElements(); i++)
1248 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1252 if (viewport != null)
1254 return new AlignmentI[]
1255 { viewport.alignment };
1266 protected void undoMenuItem_actionPerformed(ActionEvent e)
1268 if (viewport.historyList.empty())
1270 CommandI command = (CommandI) viewport.historyList.pop();
1271 viewport.redoList.push(command);
1272 command.undoCommand(getViewAlignments());
1274 AlignViewport originalSource = getOriginatingSource(command);
1275 updateEditMenuBar();
1277 if (originalSource != null)
1279 originalSource.hasHiddenColumns = (viewport.colSel != null
1280 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1281 .getHiddenColumns().size() > 0);
1282 originalSource.firePropertyChange("alignment", null,
1283 originalSource.alignment.getSequences());
1293 protected void redoMenuItem_actionPerformed(ActionEvent e)
1295 if (viewport.redoList.size() < 1)
1300 CommandI command = (CommandI) viewport.redoList.pop();
1301 viewport.historyList.push(command);
1302 command.doCommand(getViewAlignments());
1304 AlignViewport originalSource = getOriginatingSource(command);
1305 updateEditMenuBar();
1307 if (originalSource != null)
1309 originalSource.hasHiddenColumns = (viewport.colSel != null
1310 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1311 .getHiddenColumns().size() > 0);
1312 originalSource.firePropertyChange("alignment", null,
1313 originalSource.alignment.getSequences());
1317 AlignViewport getOriginatingSource(CommandI command)
1319 AlignViewport originalSource = null;
1320 // For sequence removal and addition, we need to fire
1321 // the property change event FROM the viewport where the
1322 // original alignment was altered
1323 AlignmentI al = null;
1324 if (command instanceof EditCommand)
1326 EditCommand editCommand = (EditCommand) command;
1327 al = editCommand.getAlignment();
1328 Vector comps = (Vector) PaintRefresher.components.get(viewport
1329 .getSequenceSetId());
1331 for (int i = 0; i < comps.size(); i++)
1333 if (comps.elementAt(i) instanceof AlignmentPanel)
1335 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1337 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1344 if (originalSource == null)
1346 // The original view is closed, we must validate
1347 // the current view against the closed view first
1350 PaintRefresher.validateSequences(al, viewport.alignment);
1353 originalSource = viewport;
1356 return originalSource;
1365 public void moveSelectedSequences(boolean up)
1367 SequenceGroup sg = viewport.getSelectionGroup();
1376 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1378 SequenceI seq = viewport.alignment.getSequenceAt(i);
1380 if (!sg.getSequences(null).contains(seq))
1385 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1387 if (sg.getSequences(null).contains(temp))
1392 viewport.alignment.getSequences().setElementAt(temp, i);
1393 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1398 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1400 SequenceI seq = viewport.alignment.getSequenceAt(i);
1402 if (!sg.getSequences(null).contains(seq))
1407 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1409 if (sg.getSequences(null).contains(temp))
1414 viewport.alignment.getSequences().setElementAt(temp, i);
1415 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1419 alignPanel.paintAlignment(true);
1422 synchronized void slideSequences(boolean right, int size)
1424 Vector sg = new Vector();
1425 if (viewport.cursorMode)
1427 sg.addElement(viewport.alignment
1428 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1430 else if (viewport.getSelectionGroup() != null
1431 && viewport.getSelectionGroup().getSize() != viewport.alignment
1434 sg = viewport.getSelectionGroup().getSequences(
1435 viewport.hiddenRepSequences);
1443 Vector invertGroup = new Vector();
1445 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1447 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1448 invertGroup.add(viewport.alignment.getSequenceAt(i));
1451 SequenceI[] seqs1 = new SequenceI[sg.size()];
1452 for (int i = 0; i < sg.size(); i++)
1453 seqs1[i] = (SequenceI) sg.elementAt(i);
1455 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1456 for (int i = 0; i < invertGroup.size(); i++)
1457 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1459 SlideSequencesCommand ssc;
1461 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1462 size, viewport.getGapCharacter());
1464 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1465 size, viewport.getGapCharacter());
1467 int groupAdjustment = 0;
1468 if (ssc.getGapsInsertedBegin() && right)
1470 if (viewport.cursorMode)
1471 alignPanel.seqPanel.moveCursor(size, 0);
1473 groupAdjustment = size;
1475 else if (!ssc.getGapsInsertedBegin() && !right)
1477 if (viewport.cursorMode)
1478 alignPanel.seqPanel.moveCursor(-size, 0);
1480 groupAdjustment = -size;
1483 if (groupAdjustment != 0)
1485 viewport.getSelectionGroup().setStartRes(
1486 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1487 viewport.getSelectionGroup().setEndRes(
1488 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1491 boolean appendHistoryItem = false;
1492 if (viewport.historyList != null && viewport.historyList.size() > 0
1493 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1495 appendHistoryItem = ssc
1496 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1500 if (!appendHistoryItem)
1501 addHistoryItem(ssc);
1512 protected void copy_actionPerformed(ActionEvent e)
1515 if (viewport.getSelectionGroup() == null)
1519 // TODO: preserve the ordering of displayed alignment annotation in any
1520 // internal paste (particularly sequence associated annotation)
1521 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1522 String[] omitHidden = null;
1524 if (viewport.hasHiddenColumns)
1526 omitHidden = viewport.getViewAsString(true);
1529 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1532 StringSelection ss = new StringSelection(output);
1536 jalview.gui.Desktop.internalCopy = true;
1537 // Its really worth setting the clipboard contents
1538 // to empty before setting the large StringSelection!!
1539 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1540 new StringSelection(""), null);
1542 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1544 } catch (OutOfMemoryError er)
1546 new OOMWarning("copying region", er);
1550 Vector hiddenColumns = null;
1551 if (viewport.hasHiddenColumns)
1553 hiddenColumns = new Vector();
1554 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1555 .getSelectionGroup().getEndRes();
1556 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1559 int[] region = (int[]) viewport.getColumnSelection()
1560 .getHiddenColumns().elementAt(i);
1561 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1563 hiddenColumns.addElement(new int[]
1564 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1569 Desktop.jalviewClipboard = new Object[]
1570 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1571 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1580 protected void pasteNew_actionPerformed(ActionEvent e)
1591 protected void pasteThis_actionPerformed(ActionEvent e)
1597 * Paste contents of Jalview clipboard
1599 * @param newAlignment
1600 * true to paste to a new alignment, otherwise add to this.
1602 void paste(boolean newAlignment)
1604 boolean externalPaste = true;
1607 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1608 Transferable contents = c.getContents(this);
1610 if (contents == null)
1618 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1619 if (str.length() < 1)
1624 format = new IdentifyFile().Identify(str, "Paste");
1626 } catch (OutOfMemoryError er)
1628 new OOMWarning("Out of memory pasting sequences!!", er);
1632 SequenceI[] sequences;
1633 boolean annotationAdded = false;
1634 AlignmentI alignment = null;
1636 if (Desktop.jalviewClipboard != null)
1638 // The clipboard was filled from within Jalview, we must use the
1640 // And dataset from the copied alignment
1641 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1642 // be doubly sure that we create *new* sequence objects.
1643 sequences = new SequenceI[newseq.length];
1644 for (int i = 0; i < newseq.length; i++)
1646 sequences[i] = new Sequence(newseq[i]);
1648 alignment = new Alignment(sequences);
1649 externalPaste = false;
1653 // parse the clipboard as an alignment.
1654 alignment = new FormatAdapter().readFile(str, "Paste", format);
1655 sequences = alignment.getSequencesArray();
1663 if (Desktop.jalviewClipboard != null)
1665 // dataset is inherited
1666 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1670 // new dataset is constructed
1671 alignment.setDataset(null);
1673 alwidth = alignment.getWidth() + 1;
1677 AlignmentI pastedal = alignment; // preserve pasted alignment object
1678 // Add pasted sequences and dataset into existing alignment.
1679 alignment = viewport.getAlignment();
1680 alwidth = alignment.getWidth() + 1;
1681 // decide if we need to import sequences from an existing dataset
1682 boolean importDs = Desktop.jalviewClipboard != null
1683 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1684 // importDs==true instructs us to copy over new dataset sequences from
1685 // an existing alignment
1686 Vector newDs = (importDs) ? new Vector() : null; // used to create
1687 // minimum dataset set
1689 for (int i = 0; i < sequences.length; i++)
1693 newDs.addElement(null);
1695 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1697 if (importDs && ds != null)
1699 if (!newDs.contains(ds))
1701 newDs.setElementAt(ds, i);
1702 ds = new Sequence(ds);
1703 // update with new dataset sequence
1704 sequences[i].setDatasetSequence(ds);
1708 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1713 // copy and derive new dataset sequence
1714 sequences[i] = sequences[i].deriveSequence();
1715 alignment.getDataset().addSequence(
1716 sequences[i].getDatasetSequence());
1717 // TODO: avoid creation of duplicate dataset sequences with a
1718 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1720 alignment.addSequence(sequences[i]); // merges dataset
1724 newDs.clear(); // tidy up
1726 if (pastedal.getAlignmentAnnotation() != null)
1728 // Add any annotation attached to alignment.
1729 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1730 for (int i = 0; i < alann.length; i++)
1732 annotationAdded = true;
1733 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1735 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1736 newann.padAnnotation(alwidth);
1737 alignment.addAnnotation(newann);
1747 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1748 sequences, 0, alignment.getWidth(), alignment));
1750 // Add any annotations attached to sequences
1751 for (int i = 0; i < sequences.length; i++)
1753 if (sequences[i].getAnnotation() != null)
1755 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1757 annotationAdded = true;
1758 sequences[i].getAnnotation()[a].adjustForAlignment();
1759 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1760 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1765 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1772 // propagate alignment changed.
1773 viewport.setEndSeq(alignment.getHeight());
1774 if (annotationAdded)
1776 // Duplicate sequence annotation in all views.
1777 AlignmentI[] alview = this.getViewAlignments();
1778 for (int i = 0; i < sequences.length; i++)
1780 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1783 for (int avnum = 0; avnum < alview.length; avnum++)
1785 if (alview[avnum] != alignment)
1787 // duplicate in a view other than the one with input focus
1788 int avwidth = alview[avnum].getWidth() + 1;
1789 // this relies on sann being preserved after we
1790 // modify the sequence's annotation array for each duplication
1791 for (int a = 0; a < sann.length; a++)
1793 AlignmentAnnotation newann = new AlignmentAnnotation(
1795 sequences[i].addAlignmentAnnotation(newann);
1796 newann.padAnnotation(avwidth);
1797 alview[avnum].addAnnotation(newann); // annotation was
1798 // duplicated earlier
1799 alview[avnum].setAnnotationIndex(newann, a);
1804 buildSortByAnnotationScoresMenu();
1806 viewport.firePropertyChange("alignment", null, alignment
1812 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1814 String newtitle = new String("Copied sequences");
1816 if (Desktop.jalviewClipboard != null
1817 && Desktop.jalviewClipboard[2] != null)
1819 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1820 for (int i = 0; i < hc.size(); i++)
1822 int[] region = (int[]) hc.elementAt(i);
1823 af.viewport.hideColumns(region[0], region[1]);
1827 // >>>This is a fix for the moment, until a better solution is
1829 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1831 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1833 // TODO: maintain provenance of an alignment, rather than just make the
1834 // title a concatenation of operations.
1837 if (title.startsWith("Copied sequences"))
1843 newtitle = newtitle.concat("- from " + title);
1848 newtitle = new String("Pasted sequences");
1851 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1856 } catch (Exception ex)
1858 ex.printStackTrace();
1859 System.out.println("Exception whilst pasting: " + ex);
1860 // could be anything being pasted in here
1871 protected void cut_actionPerformed(ActionEvent e)
1873 copy_actionPerformed(null);
1874 delete_actionPerformed(null);
1883 protected void delete_actionPerformed(ActionEvent evt)
1886 SequenceGroup sg = viewport.getSelectionGroup();
1892 Vector seqs = new Vector();
1894 for (int i = 0; i < sg.getSize(); i++)
1896 seq = sg.getSequenceAt(i);
1897 seqs.addElement(seq);
1900 // If the cut affects all sequences, remove highlighted columns
1901 if (sg.getSize() == viewport.alignment.getHeight())
1903 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1904 sg.getEndRes() + 1);
1907 SequenceI[] cut = new SequenceI[seqs.size()];
1908 for (int i = 0; i < seqs.size(); i++)
1910 cut[i] = (SequenceI) seqs.elementAt(i);
1914 * //ADD HISTORY ITEM
1916 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1917 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1918 viewport.alignment));
1920 viewport.setSelectionGroup(null);
1921 viewport.sendSelection();
1922 viewport.alignment.deleteGroup(sg);
1924 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1926 if (viewport.getAlignment().getHeight() < 1)
1930 this.setClosed(true);
1931 } catch (Exception ex)
1943 protected void deleteGroups_actionPerformed(ActionEvent e)
1945 viewport.alignment.deleteAllGroups();
1946 viewport.sequenceColours = null;
1947 viewport.setSelectionGroup(null);
1948 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1949 alignPanel.updateAnnotation();
1950 alignPanel.paintAlignment(true);
1959 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1961 SequenceGroup sg = new SequenceGroup();
1963 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1965 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1968 sg.setEndRes(viewport.alignment.getWidth() - 1);
1969 viewport.setSelectionGroup(sg);
1970 viewport.sendSelection();
1971 alignPanel.paintAlignment(true);
1972 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1981 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1983 if (viewport.cursorMode)
1985 alignPanel.seqPanel.keyboardNo1 = null;
1986 alignPanel.seqPanel.keyboardNo2 = null;
1988 viewport.setSelectionGroup(null);
1989 viewport.getColumnSelection().clear();
1990 viewport.setSelectionGroup(null);
1991 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1992 alignPanel.idPanel.idCanvas.searchResults = null;
1993 alignPanel.paintAlignment(true);
1994 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2003 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2005 SequenceGroup sg = viewport.getSelectionGroup();
2009 selectAllSequenceMenuItem_actionPerformed(null);
2014 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2016 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2019 alignPanel.paintAlignment(true);
2020 viewport.sendSelection();
2021 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2024 public void invertColSel_actionPerformed(ActionEvent e)
2026 viewport.invertColumnSelection();
2027 alignPanel.paintAlignment(true);
2036 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2038 trimAlignment(true);
2047 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2049 trimAlignment(false);
2052 void trimAlignment(boolean trimLeft)
2054 ColumnSelection colSel = viewport.getColumnSelection();
2057 if (colSel.size() > 0)
2061 column = colSel.getMin();
2065 column = colSel.getMax();
2069 if (viewport.getSelectionGroup() != null)
2071 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2072 viewport.hiddenRepSequences);
2076 seqs = viewport.alignment.getSequencesArray();
2079 TrimRegionCommand trimRegion;
2082 trimRegion = new TrimRegionCommand("Remove Left",
2083 TrimRegionCommand.TRIM_LEFT, seqs, column,
2084 viewport.alignment, viewport.colSel,
2085 viewport.selectionGroup);
2086 viewport.setStartRes(0);
2090 trimRegion = new TrimRegionCommand("Remove Right",
2091 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2092 viewport.alignment, viewport.colSel,
2093 viewport.selectionGroup);
2096 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
2098 addHistoryItem(trimRegion);
2100 Vector groups = viewport.alignment.getGroups();
2102 for (int i = 0; i < groups.size(); i++)
2104 SequenceGroup sg = (SequenceGroup) groups.get(i);
2106 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2107 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2109 viewport.alignment.deleteGroup(sg);
2113 viewport.firePropertyChange("alignment", null, viewport
2114 .getAlignment().getSequences());
2124 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2126 int start = 0, end = viewport.alignment.getWidth() - 1;
2129 if (viewport.getSelectionGroup() != null)
2131 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2132 viewport.hiddenRepSequences);
2133 start = viewport.getSelectionGroup().getStartRes();
2134 end = viewport.getSelectionGroup().getEndRes();
2138 seqs = viewport.alignment.getSequencesArray();
2141 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2142 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
2144 addHistoryItem(removeGapCols);
2146 statusBar.setText("Removed " + removeGapCols.getSize()
2147 + " empty columns.");
2149 // This is to maintain viewport position on first residue
2150 // of first sequence
2151 SequenceI seq = viewport.alignment.getSequenceAt(0);
2152 int startRes = seq.findPosition(viewport.startRes);
2153 // ShiftList shifts;
2154 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2155 // edit.alColumnChanges=shifts.getInverse();
2156 // if (viewport.hasHiddenColumns)
2157 // viewport.getColumnSelection().compensateForEdits(shifts);
2158 viewport.setStartRes(seq.findIndex(startRes) - 1);
2159 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2170 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2172 int start = 0, end = viewport.alignment.getWidth() - 1;
2175 if (viewport.getSelectionGroup() != null)
2177 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2178 viewport.hiddenRepSequences);
2179 start = viewport.getSelectionGroup().getStartRes();
2180 end = viewport.getSelectionGroup().getEndRes();
2184 seqs = viewport.alignment.getSequencesArray();
2187 // This is to maintain viewport position on first residue
2188 // of first sequence
2189 SequenceI seq = viewport.alignment.getSequenceAt(0);
2190 int startRes = seq.findPosition(viewport.startRes);
2192 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2193 viewport.alignment));
2195 viewport.setStartRes(seq.findIndex(startRes) - 1);
2197 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2208 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2210 viewport.padGaps = padGapsMenuitem.isSelected();
2211 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2217 // if (justifySeqs>0)
2219 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2231 public void findMenuItem_actionPerformed(ActionEvent e)
2236 public void newView_actionPerformed(ActionEvent e)
2238 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2241 newap.av.gatherViewsHere = false;
2243 if (viewport.viewName == null)
2245 viewport.viewName = "Original";
2248 newap.av.historyList = viewport.historyList;
2249 newap.av.redoList = viewport.redoList;
2251 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2252 String newViewName = "View " + index;
2254 Vector comps = (Vector) PaintRefresher.components.get(viewport
2255 .getSequenceSetId());
2256 Vector existingNames = new Vector();
2257 for (int i = 0; i < comps.size(); i++)
2259 if (comps.elementAt(i) instanceof AlignmentPanel)
2261 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2262 if (!existingNames.contains(ap.av.viewName))
2264 existingNames.addElement(ap.av.viewName);
2269 while (existingNames.contains(newViewName))
2271 newViewName = "View " + (++index);
2274 newap.av.viewName = newViewName;
2276 addAlignmentPanel(newap, true);
2278 if (alignPanels.size() == 2)
2280 viewport.gatherViewsHere = true;
2282 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2285 public void expandViews_actionPerformed(ActionEvent e)
2287 Desktop.instance.explodeViews(this);
2290 public void gatherViews_actionPerformed(ActionEvent e)
2292 Desktop.instance.gatherViews(this);
2301 public void font_actionPerformed(ActionEvent e)
2303 new FontChooser(alignPanel);
2312 protected void seqLimit_actionPerformed(ActionEvent e)
2314 viewport.setShowJVSuffix(seqLimits.isSelected());
2316 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2317 .calculateIdWidth());
2318 alignPanel.paintAlignment(true);
2321 public void idRightAlign_actionPerformed(ActionEvent e)
2323 viewport.rightAlignIds = idRightAlign.isSelected();
2324 alignPanel.paintAlignment(true);
2327 public void centreColumnLabels_actionPerformed(ActionEvent e)
2329 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2330 alignPanel.paintAlignment(true);
2336 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2338 protected void followHighlight_actionPerformed()
2340 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2342 alignPanel.scrollToPosition(
2343 alignPanel.seqPanel.seqCanvas.searchResults, false);
2353 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2355 viewport.setColourText(colourTextMenuItem.isSelected());
2356 alignPanel.paintAlignment(true);
2365 public void wrapMenuItem_actionPerformed(ActionEvent e)
2367 scaleAbove.setVisible(wrapMenuItem.isSelected());
2368 scaleLeft.setVisible(wrapMenuItem.isSelected());
2369 scaleRight.setVisible(wrapMenuItem.isSelected());
2370 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2371 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2374 public void showAllSeqs_actionPerformed(ActionEvent e)
2376 viewport.showAllHiddenSeqs();
2379 public void showAllColumns_actionPerformed(ActionEvent e)
2381 viewport.showAllHiddenColumns();
2385 public void hideSelSequences_actionPerformed(ActionEvent e)
2387 viewport.hideAllSelectedSeqs();
2388 alignPanel.paintAlignment(true);
2392 * called by key handler and the hide all/show all menu items
2397 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2400 boolean hide = false;
2401 SequenceGroup sg = viewport.getSelectionGroup();
2402 if (!toggleSeqs && !toggleCols)
2404 // Hide everything by the current selection - this is a hack - we do the
2405 // invert and then hide
2406 // first check that there will be visible columns after the invert.
2407 if ((viewport.colSel != null && viewport.colSel.getSelected() != null && viewport.colSel
2408 .getSelected().size() > 0)
2409 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2412 // now invert the sequence set, if required - empty selection implies
2413 // that no hiding is required.
2416 invertSequenceMenuItem_actionPerformed(null);
2417 sg = viewport.getSelectionGroup();
2421 viewport.expandColSelection(sg, true);
2422 // finally invert the column selection and get the new sequence
2424 invertColSel_actionPerformed(null);
2431 if (sg != null && sg.getSize() != viewport.alignment.getHeight())
2433 hideSelSequences_actionPerformed(null);
2436 else if (!(toggleCols && viewport.colSel.getSelected().size() > 0))
2438 showAllSeqs_actionPerformed(null);
2444 if (viewport.colSel.getSelected().size() > 0)
2446 hideSelColumns_actionPerformed(null);
2449 viewport.selectionGroup = sg;
2454 showAllColumns_actionPerformed(null);
2463 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2464 * event.ActionEvent)
2466 public void hideAllButSelection_actionPerformed(ActionEvent e)
2468 toggleHiddenRegions(false, false);
2475 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2478 public void hideAllSelection_actionPerformed(ActionEvent e)
2480 SequenceGroup sg = viewport.getSelectionGroup();
2481 viewport.expandColSelection(sg, false);
2482 viewport.hideAllSelectedSeqs();
2483 viewport.hideSelectedColumns();
2484 alignPanel.paintAlignment(true);
2491 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2494 public void showAllhidden_actionPerformed(ActionEvent e)
2496 viewport.showAllHiddenColumns();
2497 viewport.showAllHiddenSeqs();
2498 alignPanel.paintAlignment(true);
2501 public void hideSelColumns_actionPerformed(ActionEvent e)
2503 viewport.hideSelectedColumns();
2504 alignPanel.paintAlignment(true);
2507 public void hiddenMarkers_actionPerformed(ActionEvent e)
2509 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2519 protected void scaleAbove_actionPerformed(ActionEvent e)
2521 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2522 alignPanel.paintAlignment(true);
2531 protected void scaleLeft_actionPerformed(ActionEvent e)
2533 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2534 alignPanel.paintAlignment(true);
2543 protected void scaleRight_actionPerformed(ActionEvent e)
2545 viewport.setScaleRightWrapped(scaleRight.isSelected());
2546 alignPanel.paintAlignment(true);
2555 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2557 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2558 alignPanel.paintAlignment(true);
2567 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2569 viewport.setShowText(viewTextMenuItem.isSelected());
2570 alignPanel.paintAlignment(true);
2579 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2581 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2582 alignPanel.paintAlignment(true);
2585 public FeatureSettings featureSettings;
2587 public void featureSettings_actionPerformed(ActionEvent e)
2589 if (featureSettings != null)
2591 featureSettings.close();
2592 featureSettings = null;
2594 if (!showSeqFeatures.isSelected())
2596 // make sure features are actually displayed
2597 showSeqFeatures.setSelected(true);
2598 showSeqFeatures_actionPerformed(null);
2600 featureSettings = new FeatureSettings(this);
2604 * Set or clear 'Show Sequence Features'
2609 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2611 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2612 alignPanel.paintAlignment(true);
2613 if (alignPanel.getOverviewPanel() != null)
2615 alignPanel.getOverviewPanel().updateOverviewImage();
2620 * Set or clear 'Show Sequence Features'
2625 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2627 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2629 if (viewport.getShowSequenceFeaturesHeight())
2631 // ensure we're actually displaying features
2632 viewport.setShowSequenceFeatures(true);
2633 showSeqFeatures.setSelected(true);
2635 alignPanel.paintAlignment(true);
2636 if (alignPanel.getOverviewPanel() != null)
2638 alignPanel.getOverviewPanel().updateOverviewImage();
2648 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2650 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2651 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2654 public void alignmentProperties()
2656 JEditorPane editPane = new JEditorPane("text/html", "");
2657 editPane.setEditable(false);
2658 StringBuffer contents = new StringBuffer("<html>");
2661 int min = Integer.MAX_VALUE, max = 0;
2662 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2664 int size = viewport.alignment.getSequenceAt(i).getEnd()
2665 - viewport.alignment.getSequenceAt(i).getStart();
2672 avg = avg / (float) viewport.alignment.getHeight();
2674 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2675 contents.append("<br>Minimum Sequence Length: " + min);
2676 contents.append("<br>Maximum Sequence Length: " + max);
2677 contents.append("<br>Average Length: " + (int) avg);
2679 if (((Alignment) viewport.alignment).getProperties() != null)
2681 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2682 Enumeration en = props.keys();
2683 contents.append("<br><br><table border=\"1\">");
2684 while (en.hasMoreElements())
2686 String key = en.nextElement().toString();
2687 StringBuffer val = new StringBuffer();
2688 String vals = props.get(key).toString();
2692 npos = vals.indexOf("\n", pos);
2695 val.append(vals.substring(pos));
2699 val.append(vals.substring(pos, npos));
2703 } while (npos != -1);
2705 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2707 contents.append("</table>");
2709 editPane.setText(contents.toString() + "</html>");
2710 JInternalFrame frame = new JInternalFrame();
2711 frame.getContentPane().add(new JScrollPane(editPane));
2713 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2714 + getTitle(), 500, 400);
2723 public void overviewMenuItem_actionPerformed(ActionEvent e)
2725 if (alignPanel.overviewPanel != null)
2730 JInternalFrame frame = new JInternalFrame();
2731 OverviewPanel overview = new OverviewPanel(alignPanel);
2732 frame.setContentPane(overview);
2733 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2734 .getWidth(), frame.getHeight());
2736 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2738 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2740 public void internalFrameClosed(
2741 javax.swing.event.InternalFrameEvent evt)
2743 alignPanel.setOverviewPanel(null);
2747 alignPanel.setOverviewPanel(overview);
2750 public void textColour_actionPerformed(ActionEvent e)
2752 new TextColourChooser().chooseColour(alignPanel, null);
2761 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2772 public void clustalColour_actionPerformed(ActionEvent e)
2774 changeColour(new ClustalxColourScheme(
2775 viewport.alignment.getSequences(), viewport.alignment
2785 public void zappoColour_actionPerformed(ActionEvent e)
2787 changeColour(new ZappoColourScheme());
2796 public void taylorColour_actionPerformed(ActionEvent e)
2798 changeColour(new TaylorColourScheme());
2807 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2809 changeColour(new HydrophobicColourScheme());
2818 public void helixColour_actionPerformed(ActionEvent e)
2820 changeColour(new HelixColourScheme());
2829 public void strandColour_actionPerformed(ActionEvent e)
2831 changeColour(new StrandColourScheme());
2840 public void turnColour_actionPerformed(ActionEvent e)
2842 changeColour(new TurnColourScheme());
2851 public void buriedColour_actionPerformed(ActionEvent e)
2853 changeColour(new BuriedColourScheme());
2862 public void nucleotideColour_actionPerformed(ActionEvent e)
2864 changeColour(new NucleotideColourScheme());
2867 public void annotationColour_actionPerformed(ActionEvent e)
2869 new AnnotationColourChooser(viewport, alignPanel);
2878 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2880 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2889 public void changeColour(ColourSchemeI cs)
2895 if (viewport.getAbovePIDThreshold())
2897 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2900 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2902 viewport.setGlobalColourScheme(cs);
2906 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2909 if (viewport.getConservationSelected())
2912 Alignment al = (Alignment) viewport.alignment;
2913 Conservation c = new Conservation("All",
2914 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2918 c.verdict(false, viewport.ConsPercGaps);
2920 cs.setConservation(c);
2922 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2927 cs.setConservation(null);
2930 cs.setConsensus(viewport.hconsensus);
2933 viewport.setGlobalColourScheme(cs);
2935 if (viewport.getColourAppliesToAllGroups())
2937 Vector groups = viewport.alignment.getGroups();
2939 for (int i = 0; i < groups.size(); i++)
2941 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2949 if (cs instanceof ClustalxColourScheme)
2951 sg.cs = new ClustalxColourScheme(sg
2952 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2954 else if (cs instanceof UserColourScheme)
2956 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2962 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2963 } catch (Exception ex)
2968 if (viewport.getAbovePIDThreshold()
2969 || cs instanceof PIDColourScheme
2970 || cs instanceof Blosum62ColourScheme)
2972 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2974 sg.cs.setConsensus(AAFrequency.calculate(sg
2975 .getSequences(viewport.hiddenRepSequences), sg
2976 .getStartRes(), sg.getEndRes() + 1));
2980 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2983 if (viewport.getConservationSelected())
2985 Conservation c = new Conservation("Group",
2986 ResidueProperties.propHash, 3, sg
2987 .getSequences(viewport.hiddenRepSequences), sg
2988 .getStartRes(), sg.getEndRes() + 1);
2990 c.verdict(false, viewport.ConsPercGaps);
2991 sg.cs.setConservation(c);
2995 sg.cs.setConservation(null);
3000 if (alignPanel.getOverviewPanel() != null)
3002 alignPanel.getOverviewPanel().updateOverviewImage();
3005 alignPanel.paintAlignment(true);
3014 protected void modifyPID_actionPerformed(ActionEvent e)
3016 if (viewport.getAbovePIDThreshold()
3017 && viewport.globalColourScheme != null)
3019 SliderPanel.setPIDSliderSource(alignPanel, viewport
3020 .getGlobalColourScheme(), "Background");
3021 SliderPanel.showPIDSlider();
3031 protected void modifyConservation_actionPerformed(ActionEvent e)
3033 if (viewport.getConservationSelected()
3034 && viewport.globalColourScheme != null)
3036 SliderPanel.setConservationSlider(alignPanel,
3037 viewport.globalColourScheme, "Background");
3038 SliderPanel.showConservationSlider();
3048 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3050 viewport.setConservationSelected(conservationMenuItem.isSelected());
3052 viewport.setAbovePIDThreshold(false);
3053 abovePIDThreshold.setSelected(false);
3055 changeColour(viewport.getGlobalColourScheme());
3057 modifyConservation_actionPerformed(null);
3066 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3068 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3070 conservationMenuItem.setSelected(false);
3071 viewport.setConservationSelected(false);
3073 changeColour(viewport.getGlobalColourScheme());
3075 modifyPID_actionPerformed(null);
3084 public void userDefinedColour_actionPerformed(ActionEvent e)
3086 if (e.getActionCommand().equals("User Defined..."))
3088 new UserDefinedColours(alignPanel, null);
3092 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3093 .getUserColourSchemes().get(e.getActionCommand());
3099 public void updateUserColourMenu()
3102 Component[] menuItems = colourMenu.getMenuComponents();
3103 int i, iSize = menuItems.length;
3104 for (i = 0; i < iSize; i++)
3106 if (menuItems[i].getName() != null
3107 && menuItems[i].getName().equals("USER_DEFINED"))
3109 colourMenu.remove(menuItems[i]);
3113 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3115 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3116 .getUserColourSchemes().keys();
3118 while (userColours.hasMoreElements())
3120 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3121 userColours.nextElement().toString());
3122 radioItem.setName("USER_DEFINED");
3123 radioItem.addMouseListener(new MouseAdapter()
3125 public void mousePressed(MouseEvent evt)
3127 if (evt.isControlDown()
3128 || SwingUtilities.isRightMouseButton(evt))
3131 .removeActionListener(radioItem.getActionListeners()[0]);
3133 int option = JOptionPane.showInternalConfirmDialog(
3134 jalview.gui.Desktop.desktop,
3135 "Remove from default list?",
3136 "Remove user defined colour",
3137 JOptionPane.YES_NO_OPTION);
3138 if (option == JOptionPane.YES_OPTION)
3140 jalview.gui.UserDefinedColours
3141 .removeColourFromDefaults(radioItem.getText());
3142 colourMenu.remove(radioItem);
3146 radioItem.addActionListener(new ActionListener()
3148 public void actionPerformed(ActionEvent evt)
3150 userDefinedColour_actionPerformed(evt);
3157 radioItem.addActionListener(new ActionListener()
3159 public void actionPerformed(ActionEvent evt)
3161 userDefinedColour_actionPerformed(evt);
3165 colourMenu.insert(radioItem, 15);
3166 colours.add(radioItem);
3177 public void PIDColour_actionPerformed(ActionEvent e)
3179 changeColour(new PIDColourScheme());
3188 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3190 changeColour(new Blosum62ColourScheme());
3199 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3201 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3202 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3203 .getAlignment().getSequenceAt(0), null);
3204 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3205 viewport.alignment));
3206 alignPanel.paintAlignment(true);
3215 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3217 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3218 AlignmentSorter.sortByID(viewport.getAlignment());
3219 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
3220 alignPanel.paintAlignment(true);
3229 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3231 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3232 AlignmentSorter.sortByLength(viewport.getAlignment());
3233 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3234 viewport.alignment));
3235 alignPanel.paintAlignment(true);
3244 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3246 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3247 AlignmentSorter.sortByGroup(viewport.getAlignment());
3248 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3249 viewport.alignment));
3251 alignPanel.paintAlignment(true);
3260 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3262 new RedundancyPanel(alignPanel, this);
3271 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3273 if ((viewport.getSelectionGroup() == null)
3274 || (viewport.getSelectionGroup().getSize() < 2))
3276 JOptionPane.showInternalMessageDialog(this,
3277 "You must select at least 2 sequences.", "Invalid Selection",
3278 JOptionPane.WARNING_MESSAGE);
3282 JInternalFrame frame = new JInternalFrame();
3283 frame.setContentPane(new PairwiseAlignPanel(viewport));
3284 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
3294 public void PCAMenuItem_actionPerformed(ActionEvent e)
3296 if (((viewport.getSelectionGroup() != null)
3297 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3298 .getSelectionGroup().getSize() > 0))
3299 || (viewport.getAlignment().getHeight() < 4))
3301 JOptionPane.showInternalMessageDialog(this,
3302 "Principal component analysis must take\n"
3303 + "at least 4 input sequences.",
3304 "Sequence selection insufficient",
3305 JOptionPane.WARNING_MESSAGE);
3310 new PCAPanel(alignPanel);
3313 public void autoCalculate_actionPerformed(ActionEvent e)
3315 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3316 if (viewport.autoCalculateConsensus)
3318 viewport.firePropertyChange("alignment", null, viewport
3319 .getAlignment().getSequences());
3329 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3331 NewTreePanel("AV", "PID", "Average distance tree using PID");
3340 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3342 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3351 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3353 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3362 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3364 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3377 void NewTreePanel(String type, String pwType, String title)
3381 if (viewport.getSelectionGroup() != null)
3383 if (viewport.getSelectionGroup().getSize() < 3)
3388 "You need to have more than two sequences selected to build a tree!",
3389 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3394 SequenceGroup sg = viewport.getSelectionGroup();
3396 /* Decide if the selection is a column region */
3397 while (s < sg.getSize())
3399 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3405 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3406 + "Try using the Pad function in the edit menu,\n"
3407 + "or one of the multiple sequence alignment web services.",
3408 "Sequences in selection are not aligned",
3409 JOptionPane.WARNING_MESSAGE);
3415 title = title + " on region";
3416 tp = new TreePanel(alignPanel, type, pwType);
3420 // are the visible sequences aligned?
3421 if (!viewport.alignment.isAligned(false))
3426 "The sequences must be aligned before creating a tree.\n"
3427 + "Try using the Pad function in the edit menu,\n"
3428 + "or one of the multiple sequence alignment web services.",
3429 "Sequences not aligned",
3430 JOptionPane.WARNING_MESSAGE);
3435 if (viewport.alignment.getHeight() < 2)
3440 tp = new TreePanel(alignPanel, type, pwType);
3445 if (viewport.viewName != null)
3447 title += viewport.viewName + " of ";
3450 title += this.title;
3452 Desktop.addInternalFrame(tp, title, 600, 500);
3463 public void addSortByOrderMenuItem(String title,
3464 final AlignmentOrder order)
3466 final JMenuItem item = new JMenuItem("by " + title);
3468 item.addActionListener(new java.awt.event.ActionListener()
3470 public void actionPerformed(ActionEvent e)
3472 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3474 // TODO: JBPNote - have to map order entries to curent SequenceI
3476 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3478 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3479 viewport.alignment));
3481 alignPanel.paintAlignment(true);
3487 * Add a new sort by annotation score menu item
3490 * the menu to add the option to
3492 * the label used to retrieve scores for each sequence on the
3495 public void addSortByAnnotScoreMenuItem(JMenu sort,
3496 final String scoreLabel)
3498 final JMenuItem item = new JMenuItem(scoreLabel);
3500 item.addActionListener(new java.awt.event.ActionListener()
3502 public void actionPerformed(ActionEvent e)
3504 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3505 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3506 .getAlignment());// ,viewport.getSelectionGroup());
3507 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3508 viewport.alignment));
3509 alignPanel.paintAlignment(true);
3515 * last hash for alignment's annotation array - used to minimise cost of
3518 protected int _annotationScoreVectorHash;
3521 * search the alignment and rebuild the sort by annotation score submenu the
3522 * last alignment annotation vector hash is stored to minimize cost of
3523 * rebuilding in subsequence calls.
3526 public void buildSortByAnnotationScoresMenu()
3528 if (viewport.alignment.getAlignmentAnnotation() == null)
3533 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3535 sortByAnnotScore.removeAll();
3536 // almost certainly a quicker way to do this - but we keep it simple
3537 Hashtable scoreSorts = new Hashtable();
3538 AlignmentAnnotation aann[];
3539 Enumeration sq = viewport.alignment.getSequences().elements();
3540 while (sq.hasMoreElements())
3542 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3543 for (int i = 0; aann != null && i < aann.length; i++)
3545 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3547 scoreSorts.put(aann[i].label, aann[i].label);
3551 Enumeration labels = scoreSorts.keys();
3552 while (labels.hasMoreElements())
3554 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3557 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3560 _annotationScoreVectorHash = viewport.alignment
3561 .getAlignmentAnnotation().hashCode();
3566 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3567 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3568 * call. Listeners are added to remove the menu item when the treePanel is
3569 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3573 * Displayed tree window.
3575 * SortBy menu item title.
3577 public void buildTreeMenu()
3579 sortByTreeMenu.removeAll();
3581 Vector comps = (Vector) PaintRefresher.components.get(viewport
3582 .getSequenceSetId());
3583 Vector treePanels = new Vector();
3584 int i, iSize = comps.size();
3585 for (i = 0; i < iSize; i++)
3587 if (comps.elementAt(i) instanceof TreePanel)
3589 treePanels.add(comps.elementAt(i));
3593 iSize = treePanels.size();
3597 sortByTreeMenu.setVisible(false);
3601 sortByTreeMenu.setVisible(true);
3603 for (i = 0; i < treePanels.size(); i++)
3605 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3606 final JMenuItem item = new JMenuItem(tp.getTitle());
3607 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3608 item.addActionListener(new java.awt.event.ActionListener()
3610 public void actionPerformed(ActionEvent e)
3612 SequenceI[] oldOrder = viewport.getAlignment()
3613 .getSequencesArray();
3614 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3616 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3617 viewport.alignment));
3619 alignPanel.paintAlignment(true);
3623 sortByTreeMenu.add(item);
3628 * Work out whether the whole set of sequences or just the selected set will
3629 * be submitted for multiple alignment.
3632 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3634 // Now, check we have enough sequences
3635 AlignmentView msa = null;
3637 if ((viewport.getSelectionGroup() != null)
3638 && (viewport.getSelectionGroup().getSize() > 1))
3640 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3641 // some common interface!
3643 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3644 * SequenceI[sz = seqs.getSize(false)];
3646 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3647 * seqs.getSequenceAt(i); }
3649 msa = viewport.getAlignmentView(true);
3654 * Vector seqs = viewport.getAlignment().getSequences();
3656 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3658 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3659 * seqs.elementAt(i); } }
3661 msa = viewport.getAlignmentView(false);
3667 * Decides what is submitted to a secondary structure prediction service: the
3668 * first sequence in the alignment, or in the current selection, or, if the
3669 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3670 * region or the whole alignment. (where the first sequence in the set is the
3671 * one that the prediction will be for).
3673 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3675 AlignmentView seqs = null;
3677 if ((viewport.getSelectionGroup() != null)
3678 && (viewport.getSelectionGroup().getSize() > 0))
3680 seqs = viewport.getAlignmentView(true);
3684 seqs = viewport.getAlignmentView(false);
3686 // limit sequences - JBPNote in future - could spawn multiple prediction
3688 // TODO: viewport.alignment.isAligned is a global state - the local
3689 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3690 if (!viewport.alignment.isAligned(false))
3692 seqs.setSequences(new SeqCigar[]
3693 { seqs.getSequences()[0] });
3694 // TODO: if seqs.getSequences().length>1 then should really have warned
3707 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3709 // Pick the tree file
3710 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3711 .getProperty("LAST_DIRECTORY"));
3712 chooser.setFileView(new JalviewFileView());
3713 chooser.setDialogTitle("Select a newick-like tree file");
3714 chooser.setToolTipText("Load a tree file");
3716 int value = chooser.showOpenDialog(null);
3718 if (value == JalviewFileChooser.APPROVE_OPTION)
3720 String choice = chooser.getSelectedFile().getPath();
3721 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3722 jalview.io.NewickFile fin = null;
3725 fin = new jalview.io.NewickFile(choice, "File");
3726 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3727 } catch (Exception ex)
3729 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3730 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3731 ex.printStackTrace();
3733 if (fin != null && fin.hasWarningMessage())
3735 JOptionPane.showMessageDialog(Desktop.desktop, fin
3736 .getWarningMessage(), "Possible problem with tree file",
3737 JOptionPane.WARNING_MESSAGE);
3742 public TreePanel ShowNewickTree(NewickFile nf, String title)
3744 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3747 public TreePanel ShowNewickTree(NewickFile nf, String title,
3748 AlignmentView input)
3750 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3753 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3754 int h, int x, int y)
3756 return ShowNewickTree(nf, title, null, w, h, x, y);
3760 * Add a treeviewer for the tree extracted from a newick file object to the
3761 * current alignment view
3768 * Associated alignment input data (or null)
3777 * @return TreePanel handle
3779 public TreePanel ShowNewickTree(NewickFile nf, String title,
3780 AlignmentView input, int w, int h, int x, int y)
3782 TreePanel tp = null;
3788 if (nf.getTree() != null)
3790 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3796 tp.setLocation(x, y);
3799 Desktop.addInternalFrame(tp, title, w, h);
3801 } catch (Exception ex)
3803 ex.printStackTrace();
3809 private boolean buildingMenu = false;
3812 * Generates menu items and listener event actions for web service clients
3815 public void BuildWebServiceMenu()
3817 while (buildingMenu)
3821 System.err.println("Waiting for building menu to finish.");
3823 } catch (Exception e)
3828 buildingMenu = true;
3832 .println("Building ws menu again " + Thread.currentThread());
3833 // TODO: add support for context dependent disabling of services based on
3834 // alignment and current selection
3835 // TODO: add additional serviceHandle parameter to specify abstract
3837 // class independently of AbstractName
3838 // TODO: add in rediscovery GUI function to restart discoverer
3839 // TODO: group services by location as well as function and/or introduce
3840 // object broker mechanism.
3841 Vector wsmenu = new Vector();
3842 final IProgressIndicator af = this;
3843 if (Cache.getDefault("SHOW_JWS1_SERVICES", true)
3844 && Discoverer.services != null
3845 && (Discoverer.services.size() > 0))
3847 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3848 // stored or retrieved from elsewhere
3849 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3850 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3851 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3852 // TODO: move GUI generation code onto service implementation - so a
3853 // client instance attaches itself to the GUI with method call like
3854 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3858 // Add any Multiple Sequence Alignment Services
3859 final JMenu msawsmenu = new JMenu("Alignment");
3860 for (int i = 0, j = msaws.size(); i < j; i++)
3862 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3864 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3865 .getServiceClient(sh);
3866 impl.attachWSMenuEntry(msawsmenu, this);
3869 wsmenu.add(msawsmenu);
3871 if (secstrpr != null)
3873 // Add any secondary structure prediction services
3874 final JMenu secstrmenu = new JMenu(
3875 "Secondary Structure Prediction");
3876 for (int i = 0, j = secstrpr.size(); i < j; i++)
3878 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3880 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3881 .getServiceClient(sh);
3882 impl.attachWSMenuEntry(secstrmenu, this);
3884 wsmenu.add(secstrmenu);
3886 if (seqsrch != null)
3888 // Add any sequence search services
3889 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3890 for (int i = 0, j = seqsrch.size(); i < j; i++)
3892 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3894 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3895 .getServiceClient(sh);
3896 impl.attachWSMenuEntry(seqsrchmenu, this);
3898 wsmenu.add(seqsrchmenu);
3902 // TODO: move into separate menu builder class.
3903 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
3905 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
3906 if (jws2servs != null)
3908 if (jws2servs.hasServices())
3910 JMenu jws2men = new JMenu("Jalview 2 Services");
3911 jws2servs.attachWSMenuEntry(jws2men, this);
3912 for (int i = 0, iSize = jws2men.getMenuComponentCount(); i < iSize; i++)
3914 wsmenu.add(jws2men.getMenuComponent(i));
3919 resetWebServiceMenu();
3920 // finally, add the whole shebang onto the webservices menu
3921 if (wsmenu.size() > 0)
3923 for (int i = 0, j = wsmenu.size(); i < j; i++)
3925 webService.add((JMenu) wsmenu.get(i));
3930 this.webService.add(this.webServiceNoServices);
3932 } catch (Exception e)
3936 buildingMenu = false;
3940 * empty the web service menu and add any ad-hoc functions not dynamically
3944 private void resetWebServiceMenu()
3946 webService.removeAll();
3947 build_fetchdbmenu(webService);
3948 build_urlServiceMenu(webService);
3952 * construct any groupURL type service menu entries.
3956 private void build_urlServiceMenu(JMenu webService)
3958 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
3960 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(
3966 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3967 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3968 * getProperty("LAST_DIRECTORY"));
3970 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3971 * to Vamsas file"); chooser.setToolTipText("Export");
3973 * int value = chooser.showSaveDialog(this);
3975 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3976 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3977 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3978 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3981 * prototype of an automatically enabled/disabled analysis function
3984 protected void setShowProductsEnabled()
3986 SequenceI[] selection = viewport.getSequenceSelection();
3987 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3988 viewport.getAlignment().getDataset()))
3990 showProducts.setEnabled(true);
3995 showProducts.setEnabled(false);
4000 * search selection for sequence xRef products and build the show products
4005 * @return true if showProducts menu should be enabled.
4007 public boolean canShowProducts(SequenceI[] selection,
4008 boolean isRegionSelection, Alignment dataset)
4010 boolean showp = false;
4013 showProducts.removeAll();
4014 final boolean dna = viewport.getAlignment().isNucleotide();
4015 final Alignment ds = dataset;
4016 String[] ptypes = (selection == null || selection.length == 0) ? null
4017 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4019 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4020 // selection, dataset, true);
4021 final SequenceI[] sel = selection;
4022 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4025 final boolean isRegSel = isRegionSelection;
4026 final AlignFrame af = this;
4027 final String source = ptypes[t];
4028 JMenuItem xtype = new JMenuItem(ptypes[t]);
4029 xtype.addActionListener(new ActionListener()
4032 public void actionPerformed(ActionEvent e)
4034 // TODO: new thread for this call with vis-delay
4035 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4036 isRegSel, dna, source);
4040 showProducts.add(xtype);
4042 showProducts.setVisible(showp);
4043 showProducts.setEnabled(showp);
4044 } catch (Exception e)
4046 jalview.bin.Cache.log
4048 "canTranslate threw an exception - please report to help@jalview.org",
4055 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4056 boolean isRegSel, boolean dna, String source)
4058 final boolean fisRegSel = isRegSel;
4059 final boolean fdna = dna;
4060 final String fsrc = source;
4061 final AlignFrame ths = this;
4062 final SequenceI[] fsel = sel;
4063 Runnable foo = new Runnable()
4068 final long sttime = System.currentTimeMillis();
4069 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4072 Alignment ds = ths.getViewport().alignment.getDataset(); // update
4076 Alignment prods = CrossRef
4077 .findXrefSequences(fsel, fdna, fsrc, ds);
4080 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4081 for (int s = 0; s < sprods.length; s++)
4083 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4084 if (ds.getSequences() == null
4085 || !ds.getSequences().contains(
4086 sprods[s].getDatasetSequence()))
4087 ds.addSequence(sprods[s].getDatasetSequence());
4088 sprods[s].updatePDBIds();
4090 Alignment al = new Alignment(sprods);
4091 AlignedCodonFrame[] cf = prods.getCodonFrames();
4093 for (int s = 0; cf != null && s < cf.length; s++)
4095 al.addCodonFrame(cf[s]);
4098 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4100 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4101 + " for " + ((fisRegSel) ? "selected region of " : "")
4103 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4108 System.err.println("No Sequences generated for xRef type "
4111 } catch (Exception e)
4113 jalview.bin.Cache.log.error(
4114 "Exception when finding crossreferences", e);
4115 } catch (OutOfMemoryError e)
4117 new OOMWarning("whilst fetching crossreferences", e);
4120 jalview.bin.Cache.log.error("Error when finding crossreferences",
4123 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4128 Thread frunner = new Thread(foo);
4132 public boolean canShowTranslationProducts(SequenceI[] selection,
4133 AlignmentI alignment)
4138 return (jalview.analysis.Dna.canTranslate(selection, viewport
4139 .getViewAsVisibleContigs(true)));
4140 } catch (Exception e)
4142 jalview.bin.Cache.log
4144 "canTranslate threw an exception - please report to help@jalview.org",
4150 public void showProducts_actionPerformed(ActionEvent e)
4152 // /////////////////////////////
4153 // Collect Data to be translated/transferred
4155 SequenceI[] selection = viewport.getSequenceSelection();
4156 AlignmentI al = null;
4159 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4160 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4161 viewport.getAlignment().getDataset());
4162 } catch (Exception ex)
4165 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4172 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4173 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4177 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4178 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4179 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4183 public void showTranslation_actionPerformed(ActionEvent e)
4185 // /////////////////////////////
4186 // Collect Data to be translated/transferred
4188 SequenceI[] selection = viewport.getSequenceSelection();
4189 String[] seqstring = viewport.getViewAsString(true);
4190 AlignmentI al = null;
4193 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4194 viewport.getViewAsVisibleContigs(true), viewport
4195 .getGapCharacter(), viewport.alignment
4196 .getAlignmentAnnotation(), viewport.alignment
4197 .getWidth(), viewport.getAlignment().getDataset());
4198 } catch (Exception ex)
4201 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4208 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4209 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4213 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4214 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4215 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4220 * Try to load a features file onto the alignment.
4223 * contents or path to retrieve file
4225 * access mode of file (see jalview.io.AlignFile)
4226 * @return true if features file was parsed corectly.
4228 public boolean parseFeaturesFile(String file, String type)
4230 boolean featuresFile = false;
4233 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
4234 .getDataset(), alignPanel.seqPanel.seqCanvas
4235 .getFeatureRenderer().featureColours, false);
4236 } catch (Exception ex)
4238 ex.printStackTrace();
4243 viewport.showSequenceFeatures = true;
4244 showSeqFeatures.setSelected(true);
4245 if (alignPanel.seqPanel.seqCanvas.fr != null)
4247 // update the min/max ranges where necessary
4248 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4250 if (featureSettings != null)
4252 featureSettings.setTableData();
4254 alignPanel.paintAlignment(true);
4257 return featuresFile;
4260 public void dragEnter(DropTargetDragEvent evt)
4264 public void dragExit(DropTargetEvent evt)
4268 public void dragOver(DropTargetDragEvent evt)
4272 public void dropActionChanged(DropTargetDragEvent evt)
4276 public void drop(DropTargetDropEvent evt)
4278 Transferable t = evt.getTransferable();
4279 java.util.List files = null;
4283 DataFlavor uriListFlavor = new DataFlavor(
4284 "text/uri-list;class=java.lang.String");
4285 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4287 // Works on Windows and MacOSX
4288 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4289 files = (java.util.List) t
4290 .getTransferData(DataFlavor.javaFileListFlavor);
4292 else if (t.isDataFlavorSupported(uriListFlavor))
4294 // This is used by Unix drag system
4295 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4296 String data = (String) t.getTransferData(uriListFlavor);
4297 files = new java.util.ArrayList(1);
4298 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4299 data, "\r\n"); st.hasMoreTokens();)
4301 String s = st.nextToken();
4302 if (s.startsWith("#"))
4304 // the line is a comment (as per the RFC 2483)
4308 java.net.URI uri = new java.net.URI(s);
4309 // check to see if we can handle this kind of URI
4310 if (uri.getScheme().toLowerCase().startsWith("http"))
4312 files.add(uri.toString());
4316 // otherwise preserve old behaviour: catch all for file objects
4317 java.io.File file = new java.io.File(uri);
4318 files.add(file.toString());
4322 } catch (Exception e)
4324 e.printStackTrace();
4331 for (int i = 0; i < files.size(); i++)
4333 loadJalviewDataFile(files.get(i).toString());
4335 } catch (Exception ex)
4337 ex.printStackTrace();
4343 * Attempt to load a "dropped" file or URL string: First by testing whether
4344 * it's and Annotation file, then a JNet file, and finally a features file. If
4345 * all are false then the user may have dropped an alignment file onto this
4349 * either a filename or a URL string.
4351 public void loadJalviewDataFile(String file)
4355 String protocol = jalview.io.FormatAdapter.FILE;
4356 String f = file.toLowerCase();
4357 if (f.indexOf("http:") == 0 || f.indexOf("https:") == 0
4358 || f.indexOf("file:") == 0)
4360 protocol = jalview.io.FormatAdapter.URL;
4363 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
4364 viewport.alignment, file, protocol);
4368 // try to see if its a JNet 'concise' style annotation file *before* we
4369 // try to parse it as a features file
4370 String format = new IdentifyFile().Identify(file, protocol);
4371 if (format.equalsIgnoreCase("JnetFile"))
4373 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
4375 new JnetAnnotationMaker().add_annotation(predictions, viewport
4376 .getAlignment(), 0, false);
4377 isAnnotation = true;
4381 // try to parse it as a features file
4382 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4383 // if it wasn't a features file then we just treat it as a general
4384 // alignment file to load into the current view.
4387 new FileLoader().LoadFile(viewport, file, protocol, format);
4391 alignPanel.paintAlignment(true);
4398 alignPanel.adjustAnnotationHeight();
4399 viewport.updateSequenceIdColours();
4400 buildSortByAnnotationScoresMenu();
4401 alignPanel.paintAlignment(true);
4403 } catch (Exception ex)
4405 ex.printStackTrace();
4409 public void tabSelectionChanged(int index)
4413 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4414 viewport = alignPanel.av;
4415 setMenusFromViewport(viewport);
4419 public void tabbedPane_mousePressed(MouseEvent e)
4421 if (SwingUtilities.isRightMouseButton(e))
4423 String reply = JOptionPane.showInternalInputDialog(this,
4424 "Enter View Name", "Edit View Name",
4425 JOptionPane.QUESTION_MESSAGE);
4429 viewport.viewName = reply;
4430 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4435 public AlignViewport getCurrentView()
4441 * Open the dialog for regex description parsing.
4443 protected void extractScores_actionPerformed(ActionEvent e)
4445 ParseProperties pp = new jalview.analysis.ParseProperties(
4446 viewport.alignment);
4447 // TODO: verify regex and introduce GUI dialog for version 2.5
4448 // if (pp.getScoresFromDescription("col", "score column ",
4449 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4451 if (pp.getScoresFromDescription("description column",
4452 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4454 buildSortByAnnotationScoresMenu();
4462 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4465 protected void showDbRefs_actionPerformed(ActionEvent e)
4467 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
4473 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4476 protected void showNpFeats_actionPerformed(ActionEvent e)
4478 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
4482 * find the viewport amongst the tabs in this alignment frame and close that
4487 public boolean closeView(AlignViewport av)
4491 this.closeMenuItem_actionPerformed(false);
4494 Component[] comp = tabbedPane.getComponents();
4495 for (int i = 0; comp != null && i < comp.length; i++)
4497 if (comp[i] instanceof AlignmentPanel)
4499 if (((AlignmentPanel) comp[i]).av == av)
4502 closeView((AlignmentPanel) comp[i]);
4510 protected void build_fetchdbmenu(JMenu webService)
4512 // Temporary hack - DBRef Fetcher always top level ws entry.
4513 // TODO We probably want to store a sequence database checklist in
4514 // preferences and have checkboxes.. rather than individual sources selected
4516 JMenu rfetch = new JMenu("Fetch DB References");
4518 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
4519 webService.add(rfetch);
4521 JMenuItem fetchr = new JMenuItem("Standard Databases");
4523 .setToolTipText("Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources");
4524 fetchr.addActionListener(new ActionListener()
4527 public void actionPerformed(ActionEvent e)
4529 new Thread(new Runnable()
4534 new jalview.ws.DBRefFetcher(alignPanel.av
4535 .getSequenceSelection(), alignPanel.alignFrame)
4536 .fetchDBRefs(false);
4544 JMenu dfetch = new JMenu();
4546 jalview.ws.SequenceFetcher sf = SequenceFetcher
4547 .getSequenceFetcherSingleton(this);
4548 String[] otherdb = sf.getOrderedSupportedSources();
4549 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4550 // jalview.util.QuickSort.sort(otherdb, otherdb);
4551 int comp = 0, mcomp = 15;
4552 String mname = null;
4553 if (otherdb != null && otherdb.length > 0)
4555 for (int i = 0; i < otherdb.length; i++)
4557 String dbname = sf.getSourceProxy(otherdb[i]).getDbName();
4560 mname = "from '" + dbname + "'";
4562 fetchr = new JMenuItem(otherdb[i]);
4563 final String[] dassource = new String[]
4565 fetchr.addActionListener(new ActionListener()
4568 public void actionPerformed(ActionEvent e)
4570 new Thread(new Runnable()
4575 new jalview.ws.DBRefFetcher(alignPanel.av
4576 .getSequenceSelection(), alignPanel.alignFrame,
4577 dassource).fetchDBRefs(false);
4583 fetchr.setToolTipText("Retrieve from " + dbname);
4585 if (comp++ == mcomp || i == (otherdb.length - 1))
4587 dfetch.setText(mname + " to '" + dbname + "'");
4589 dfetch = new JMenu();
4598 * Left justify the whole alignment.
4600 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
4602 AlignmentI al = viewport.getAlignment();
4604 viewport.firePropertyChange("alignment", null, al);
4608 * Right justify the whole alignment.
4610 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
4612 AlignmentI al = viewport.getAlignment();
4614 viewport.firePropertyChange("alignment", null, al);
4617 public void setShowSeqFeatures(boolean b)
4619 showSeqFeatures.setSelected(true);
4620 viewport.setShowSequenceFeatures(true);
4627 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
4628 * awt.event.ActionEvent)
4630 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
4632 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
4633 alignPanel.paintAlignment(true);
4640 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
4643 protected void showGroupConsensus_actionPerformed(ActionEvent e)
4645 viewport.setShowGroupConsensus(showGroupConsensus.getState());
4646 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4654 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
4655 * .event.ActionEvent)
4657 protected void showGroupConservation_actionPerformed(ActionEvent e)
4659 viewport.setShowGroupConservation(showGroupConservation.getState());
4660 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4667 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
4668 * .event.ActionEvent)
4670 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
4672 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
4673 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4680 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
4681 * .event.ActionEvent)
4683 protected void showSequenceLogo_actionPerformed(ActionEvent e)
4685 viewport.setShowSequenceLogo(showSequenceLogo.getState());
4686 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4689 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
4691 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4698 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
4699 * .event.ActionEvent)
4701 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
4703 if (viewport.getSelectionGroup() != null)
4705 SequenceGroup[] gps = jalview.analysis.Grouping.makeGroupsFrom(
4706 viewport.getSequenceSelection(), viewport.getAlignmentView(
4707 true).getSequenceStrings(viewport.getGapCharacter()),
4708 viewport.alignment.getGroups());
4709 viewport.alignment.deleteAllGroups();
4710 viewport.sequenceColours = null;
4711 viewport.setSelectionGroup(null);
4712 // set view properties for each group
4713 for (int g = 0; g < gps.length; g++)
4715 gps[g].setShowNonconserved(viewport.getShowUnconserved());
4716 gps[g].setshowSequenceLogo(viewport.isShowSequenceLogo());
4717 viewport.alignment.addGroup(gps[g]);
4718 Color col = new Color((int) (Math.random() * 255), (int) (Math
4719 .random() * 255), (int) (Math.random() * 255));
4720 col = col.brighter();
4721 for (Enumeration sq = gps[g].getSequences(null).elements(); sq
4722 .hasMoreElements(); viewport.setSequenceColour(
4723 (SequenceI) sq.nextElement(), col))
4726 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
4727 alignPanel.updateAnnotation();
4728 alignPanel.paintAlignment(true);
4733 class PrintThread extends Thread
4737 public PrintThread(AlignmentPanel ap)
4742 static PageFormat pf;
4746 PrinterJob printJob = PrinterJob.getPrinterJob();
4750 printJob.setPrintable(ap, pf);
4754 printJob.setPrintable(ap);
4757 if (printJob.printDialog())
4762 } catch (Exception PrintException)
4764 PrintException.printStackTrace();