2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26 import java.awt.datatransfer.*;
27 import java.awt.dnd.*;
28 import java.awt.event.*;
29 import java.awt.print.*;
31 import javax.swing.event.MenuEvent;
33 import jalview.analysis.*;
34 import jalview.commands.*;
35 import jalview.datamodel.*;
37 import jalview.jbgui.*;
38 import jalview.schemes.*;
47 public class AlignFrame extends GAlignFrame implements DropTargetListener,
52 public static final int DEFAULT_WIDTH = 700;
55 public static final int DEFAULT_HEIGHT = 500;
57 public AlignmentPanel alignPanel;
59 AlignViewport viewport;
61 Vector alignPanels = new Vector();
64 * Last format used to load or save alignments in this window
66 String currentFileFormat = null;
69 * Current filename for this alignment
71 String fileName = null;
74 * Creates a new AlignFrame object with specific width and height.
80 public AlignFrame(AlignmentI al, int width, int height)
82 this(al, null, width, height);
86 * Creates a new AlignFrame object with specific width, height and
92 * @param sequenceSetId
94 public AlignFrame(AlignmentI al, int width, int height,
97 this(al, null, width, height, sequenceSetId);
101 * Creates a new AlignFrame object with specific width, height and
107 * @param sequenceSetId
110 public AlignFrame(AlignmentI al, int width, int height,
111 String sequenceSetId, String viewId)
113 this(al, null, width, height, sequenceSetId, viewId);
117 * new alignment window with hidden columns
121 * @param hiddenColumns
122 * ColumnSelection or null
124 * Width of alignment frame
128 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
129 int width, int height)
131 this(al, hiddenColumns, width, height, null);
135 * Create alignment frame for al with hiddenColumns, a specific width and
136 * height, and specific sequenceId
139 * @param hiddenColumns
142 * @param sequenceSetId
145 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
146 int width, int height, String sequenceSetId)
148 this(al, hiddenColumns, width, height, sequenceSetId, null);
152 * Create alignment frame for al with hiddenColumns, a specific width and
153 * height, and specific sequenceId
156 * @param hiddenColumns
159 * @param sequenceSetId
164 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
165 int width, int height, String sequenceSetId, String viewId)
167 setSize(width, height);
168 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
170 alignPanel = new AlignmentPanel(this, viewport);
172 if (al.getDataset() == null)
177 addAlignmentPanel(alignPanel, true);
182 * Make a new AlignFrame from exisiting alignmentPanels
189 public AlignFrame(AlignmentPanel ap)
193 addAlignmentPanel(ap, false);
198 * initalise the alignframe from the underlying viewport data and the
203 if (viewport.conservation == null)
205 BLOSUM62Colour.setEnabled(false);
206 conservationMenuItem.setEnabled(false);
207 modifyConservation.setEnabled(false);
208 // PIDColour.setEnabled(false);
209 // abovePIDThreshold.setEnabled(false);
210 // modifyPID.setEnabled(false);
213 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
216 if (sortby.equals("Id"))
218 sortIDMenuItem_actionPerformed(null);
220 else if (sortby.equals("Pairwise Identity"))
222 sortPairwiseMenuItem_actionPerformed(null);
225 if (Desktop.desktop != null)
227 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
228 addServiceListeners();
229 setGUINucleotide(viewport.alignment.isNucleotide());
232 setMenusFromViewport(viewport);
233 buildSortByAnnotationScoresMenu();
234 if (viewport.wrapAlignment)
236 wrapMenuItem_actionPerformed(null);
239 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
241 this.overviewMenuItem_actionPerformed(null);
249 * Change the filename and format for the alignment, and enable the 'reload'
250 * button functionality.
257 public void setFileName(String file, String format)
260 currentFileFormat = format;
261 reload.setEnabled(true);
264 void addKeyListener()
266 addKeyListener(new KeyAdapter()
268 public void keyPressed(KeyEvent evt)
270 if (viewport.cursorMode
271 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
272 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
273 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
274 && Character.isDigit(evt.getKeyChar()))
275 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
277 switch (evt.getKeyCode())
280 case 27: // escape key
281 deselectAllSequenceMenuItem_actionPerformed(null);
285 case KeyEvent.VK_DOWN:
286 if (evt.isAltDown() || !viewport.cursorMode)
287 moveSelectedSequences(false);
288 if (viewport.cursorMode)
289 alignPanel.seqPanel.moveCursor(0, 1);
293 if (evt.isAltDown() || !viewport.cursorMode)
294 moveSelectedSequences(true);
295 if (viewport.cursorMode)
296 alignPanel.seqPanel.moveCursor(0, -1);
300 case KeyEvent.VK_LEFT:
301 if (evt.isAltDown() || !viewport.cursorMode)
302 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
304 alignPanel.seqPanel.moveCursor(-1, 0);
308 case KeyEvent.VK_RIGHT:
309 if (evt.isAltDown() || !viewport.cursorMode)
310 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
312 alignPanel.seqPanel.moveCursor(1, 0);
315 case KeyEvent.VK_SPACE:
316 if (viewport.cursorMode)
318 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
319 || evt.isShiftDown() || evt.isAltDown());
323 case KeyEvent.VK_DELETE:
324 case KeyEvent.VK_BACK_SPACE:
325 if (!viewport.cursorMode)
327 cut_actionPerformed(null);
331 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
332 || evt.isShiftDown() || evt.isAltDown());
338 if (viewport.cursorMode)
340 alignPanel.seqPanel.setCursorRow();
344 if (viewport.cursorMode && !evt.isControlDown())
346 alignPanel.seqPanel.setCursorColumn();
350 if (viewport.cursorMode)
352 alignPanel.seqPanel.setCursorPosition();
356 case KeyEvent.VK_ENTER:
357 case KeyEvent.VK_COMMA:
358 if (viewport.cursorMode)
360 alignPanel.seqPanel.setCursorRowAndColumn();
365 if (viewport.cursorMode)
367 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
371 if (viewport.cursorMode)
373 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
378 viewport.cursorMode = !viewport.cursorMode;
379 statusBar.setText("Keyboard editing mode is "
380 + (viewport.cursorMode ? "on" : "off"));
381 if (viewport.cursorMode)
383 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
384 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
386 alignPanel.seqPanel.seqCanvas.repaint();
392 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
393 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
395 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
397 javax.help.HelpBroker hb = hs.createHelpBroker();
398 hb.setCurrentID("home");
399 hb.setDisplayed(true);
400 } catch (Exception ex)
402 ex.printStackTrace();
407 boolean toggleSeqs = !evt.isControlDown();
408 boolean toggleCols = !evt.isShiftDown();
410 boolean hide = false;
411 SequenceGroup sg = viewport.getSelectionGroup();
412 // TODO: document ctrl-shift-h for show visible selected area and fix hack so columns for the current selected region get transferred.
413 if (!toggleSeqs && !toggleCols)
415 // Hide everything by the current selection - this is a hack - we do the invert and then hide
416 // first check that there will be visible columns after the invert.
417 if ((viewport.colSel!=null && viewport.colSel.getSelected()!=null && viewport.colSel.getSelected().size()>0) || (sg!=null && sg.getSize()>0 && sg.getStartRes()<=sg.getEndRes()))
419 // now invert the sequence set, if required - empty selection implies that no hiding is required.
421 invertSequenceMenuItem_actionPerformed(null);
422 sg = viewport.getSelectionGroup();
427 if (sg!=null && sg.getStartRes()>=0 && sg.getStartRes()<=sg.getEndRes()&& (viewport.colSel==null || viewport.colSel.getSelected()==null || viewport.colSel.getSelected().size()==0))
429 // synthesize a column selection if none exists. this happens if a single region has been selected rather than whole columns.
430 if (viewport.colSel==null)
432 viewport.colSel = new ColumnSelection();
434 for (int cspos = sg.getStartRes(); cspos<=sg.getEndRes(); cspos++) {
435 viewport.colSel.addElement(cspos);
438 // finally invert the column selection and get the new sequence selection.
439 invertColSel_actionPerformed(null);
447 && sg.getSize() != viewport.alignment.getHeight())
449 hideSelSequences_actionPerformed(null);
452 else if (!(toggleCols && viewport.colSel.getSelected().size() > 0))
454 showAllSeqs_actionPerformed(null);
460 if (viewport.colSel.getSelected().size() > 0)
462 hideSelColumns_actionPerformed(null);
465 viewport.selectionGroup = sg;
470 showAllColumns_actionPerformed(null);
475 case KeyEvent.VK_PAGE_UP:
476 if (viewport.wrapAlignment)
478 alignPanel.scrollUp(true);
482 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
483 - viewport.endSeq + viewport.startSeq);
486 case KeyEvent.VK_PAGE_DOWN:
487 if (viewport.wrapAlignment)
489 alignPanel.scrollUp(false);
493 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
494 + viewport.endSeq - viewport.startSeq);
500 public void keyReleased(KeyEvent evt)
502 switch (evt.getKeyCode())
504 case KeyEvent.VK_LEFT:
505 if (evt.isAltDown() || !viewport.cursorMode)
506 viewport.firePropertyChange("alignment", null, viewport
507 .getAlignment().getSequences());
510 case KeyEvent.VK_RIGHT:
511 if (evt.isAltDown() || !viewport.cursorMode)
512 viewport.firePropertyChange("alignment", null, viewport
513 .getAlignment().getSequences());
520 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
522 ap.alignFrame = this;
524 alignPanels.addElement(ap);
526 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
528 int aSize = alignPanels.size();
530 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
532 if (aSize == 1 && ap.av.viewName == null)
534 this.getContentPane().add(ap, BorderLayout.CENTER);
540 setInitialTabVisible();
543 expandViews.setEnabled(true);
544 gatherViews.setEnabled(true);
545 tabbedPane.addTab(ap.av.viewName, ap);
547 ap.setVisible(false);
554 ap.av.alignment.padGaps();
556 ap.av.updateConservation(ap);
557 ap.av.updateConsensus(ap);
561 public void setInitialTabVisible()
563 expandViews.setEnabled(true);
564 gatherViews.setEnabled(true);
565 tabbedPane.setVisible(true);
566 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
567 tabbedPane.addTab(first.av.viewName, first);
568 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
571 public AlignViewport getViewport()
576 /* Set up intrinsic listeners for dynamically generated GUI bits. */
577 private void addServiceListeners()
579 final java.beans.PropertyChangeListener thisListener;
580 // Do this once to get current state
581 BuildWebServiceMenu();
583 .addPropertyChangeListener(thisListener = new java.beans.PropertyChangeListener()
585 public void propertyChange(PropertyChangeEvent evt)
587 // System.out.println("Discoverer property change.");
588 if (evt.getPropertyName().equals("services"))
590 // System.out.println("Rebuilding web service menu");
591 BuildWebServiceMenu();
596 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
598 public void internalFrameClosed(
599 javax.swing.event.InternalFrameEvent evt)
601 // System.out.println("deregistering discoverer listener");
602 Desktop.discoverer.removePropertyChangeListener(thisListener);
603 closeMenuItem_actionPerformed(true);
608 public void setGUINucleotide(boolean nucleotide)
610 showTranslation.setVisible(nucleotide);
611 conservationMenuItem.setEnabled(!nucleotide);
612 modifyConservation.setEnabled(!nucleotide);
613 showGroupConservation.setEnabled(!nucleotide);
614 // Remember AlignFrame always starts as protein
617 calculateMenu.remove(calculateMenu.getItemCount() - 2);
622 * set up menus for the currently viewport. This may be called after any
623 * operation that affects the data in the current view (selection changed,
624 * etc) to update the menus to reflect the new state.
626 public void setMenusForViewport()
628 setMenusFromViewport(viewport);
632 * Need to call this method when tabs are selected for multiple views, or when
633 * loading from Jalview2XML.java
638 void setMenusFromViewport(AlignViewport av)
640 padGapsMenuitem.setSelected(av.padGaps);
641 colourTextMenuItem.setSelected(av.showColourText);
642 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
643 conservationMenuItem.setSelected(av.getConservationSelected());
644 seqLimits.setSelected(av.getShowJVSuffix());
645 idRightAlign.setSelected(av.rightAlignIds);
646 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
647 renderGapsMenuItem.setSelected(av.renderGaps);
648 wrapMenuItem.setSelected(av.wrapAlignment);
649 scaleAbove.setVisible(av.wrapAlignment);
650 scaleLeft.setVisible(av.wrapAlignment);
651 scaleRight.setVisible(av.wrapAlignment);
652 annotationPanelMenuItem.setState(av.showAnnotation);
653 viewBoxesMenuItem.setSelected(av.showBoxes);
654 viewTextMenuItem.setSelected(av.showText);
655 showUnconservedMenuItem.setSelected(av.showUnconserved);
656 showGroupConsensus.setSelected(av.showGroupConsensus);
657 showGroupConservation.setSelected(av.showGroupConservation);
658 showConsensusHistogram.setSelected(av.showConsensusHistogram);
659 showSequenceLogo.setSelected(av.showSequenceLogo);
660 setColourSelected(ColourSchemeProperty.getColourName(av
661 .getGlobalColourScheme()));
663 showSeqFeatures.setSelected(av.showSequenceFeatures);
664 hiddenMarkers.setState(av.showHiddenMarkers);
665 applyToAllGroups.setState(av.colourAppliesToAllGroups);
666 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
667 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
669 setShowProductsEnabled();
674 Hashtable progressBars, progressBarHandlers;
679 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
681 public void setProgressBar(String message, long id)
683 if (progressBars == null)
685 progressBars = new Hashtable();
686 progressBarHandlers = new Hashtable();
689 JPanel progressPanel;
690 Long lId=new Long(id);
691 GridLayout layout = (GridLayout) statusPanel.getLayout();
692 if (progressBars.get(lId) != null)
694 progressPanel = (JPanel) progressBars.get(new Long(id));
695 statusPanel.remove(progressPanel);
696 progressBars.remove(lId);
697 progressPanel = null;
700 statusBar.setText(message);
702 if (progressBarHandlers.contains(lId))
704 progressBarHandlers.remove(lId);
706 layout.setRows(layout.getRows() - 1);
710 progressPanel = new JPanel(new BorderLayout(10, 5));
712 JProgressBar progressBar = new JProgressBar();
713 progressBar.setIndeterminate(true);
715 progressPanel.add(new JLabel(message), BorderLayout.WEST);
716 progressPanel.add(progressBar, BorderLayout.CENTER);
718 layout.setRows(layout.getRows() + 1);
719 statusPanel.add(progressPanel);
721 progressBars.put(lId, progressPanel);
724 setMenusForViewport();
728 public void registerHandler(final long id,
729 final IProgressIndicatorHandler handler)
731 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
734 "call setProgressBar before registering the progress bar's handler.");
736 progressBarHandlers.put(new Long(id), handler);
737 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
738 if (handler.canCancel())
740 JButton cancel = new JButton("Cancel");
741 final IProgressIndicator us = this;
742 cancel.addActionListener(new ActionListener()
745 public void actionPerformed(ActionEvent e)
747 handler.cancelActivity(id);
748 us.setProgressBar("Cancelled "
749 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
752 progressPanel.add(cancel, BorderLayout.EAST);
758 * @return true if any progress bars are still active
760 public boolean operationInProgress()
762 if (progressBars != null && progressBars.size() > 0)
770 * Added so Castor Mapping file can obtain Jalview Version
772 public String getVersion()
774 return jalview.bin.Cache.getProperty("VERSION");
777 public FeatureRenderer getFeatureRenderer()
779 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
782 public void fetchSequence_actionPerformed(ActionEvent e)
784 new SequenceFetcher(this);
787 public void addFromFile_actionPerformed(ActionEvent e)
789 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
792 public void reload_actionPerformed(ActionEvent e)
794 if (fileName != null)
796 // TODO: work out how to recover feature settings for correct view(s) when file is reloaded.
797 if (currentFileFormat.equals("Jalview"))
799 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
800 for (int i = 0; i < frames.length; i++)
802 if (frames[i] instanceof AlignFrame && frames[i] != this
803 && ((AlignFrame) frames[i]).fileName.equals(fileName))
807 frames[i].setSelected(true);
808 Desktop.instance.closeAssociatedWindows();
809 } catch (java.beans.PropertyVetoException ex)
815 Desktop.instance.closeAssociatedWindows();
817 FileLoader loader = new FileLoader();
818 String protocol = fileName.startsWith("http:") ? "URL" : "File";
819 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
823 Rectangle bounds = this.getBounds();
825 FileLoader loader = new FileLoader();
826 String protocol = fileName.startsWith("http:") ? "URL" : "File";
827 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
828 protocol, currentFileFormat);
830 newframe.setBounds(bounds);
831 if (featureSettings!=null && featureSettings.isShowing()) {
832 final Rectangle fspos = featureSettings.frame.getBounds();
833 // TODO: need a 'show feature settings' function that takes bounds - need to refactor Desktop.addFrame
834 newframe.featureSettings_actionPerformed(null);
835 final FeatureSettings nfs = newframe.featureSettings;
836 SwingUtilities.invokeLater(new Runnable() {
839 nfs.frame.setBounds(fspos);
842 this.featureSettings.close();
843 this.featureSettings=null;
845 this.closeMenuItem_actionPerformed(true);
850 public void addFromText_actionPerformed(ActionEvent e)
852 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
855 public void addFromURL_actionPerformed(ActionEvent e)
857 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
860 public void save_actionPerformed(ActionEvent e)
863 || (currentFileFormat == null || !jalview.io.FormatAdapter
864 .isValidIOFormat(currentFileFormat, true))
865 || fileName.startsWith("http"))
867 saveAs_actionPerformed(null);
871 saveAlignment(fileName, currentFileFormat);
881 public void saveAs_actionPerformed(ActionEvent e)
883 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
884 .getProperty("LAST_DIRECTORY"),
885 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
886 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
887 currentFileFormat, false);
889 chooser.setFileView(new JalviewFileView());
890 chooser.setDialogTitle("Save Alignment to file");
891 chooser.setToolTipText("Save");
893 int value = chooser.showSaveDialog(this);
895 if (value == JalviewFileChooser.APPROVE_OPTION)
897 currentFileFormat = chooser.getSelectedFormat();
898 if (currentFileFormat == null)
900 JOptionPane.showInternalMessageDialog(Desktop.desktop,
901 "You must select a file format before saving!",
902 "File format not specified", JOptionPane.WARNING_MESSAGE);
903 value = chooser.showSaveDialog(this);
907 fileName = chooser.getSelectedFile().getPath();
909 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
912 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
913 if (currentFileFormat.indexOf(" ") > -1)
915 currentFileFormat = currentFileFormat.substring(0,
916 currentFileFormat.indexOf(" "));
918 saveAlignment(fileName, currentFileFormat);
922 public boolean saveAlignment(String file, String format)
924 boolean success = true;
926 if (format.equalsIgnoreCase("Jalview"))
928 String shortName = title;
930 if (shortName.indexOf(java.io.File.separatorChar) > -1)
932 shortName = shortName.substring(shortName
933 .lastIndexOf(java.io.File.separatorChar) + 1);
936 success = new Jalview2XML().SaveAlignment(this, file, shortName);
938 statusBar.setText("Successfully saved to file: " + fileName + " in "
939 + format + " format.");
944 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
946 warningMessage("Cannot save file " + fileName + " using format "
947 + format, "Alignment output format not supported");
948 saveAs_actionPerformed(null);
949 // JBPNote need to have a raise_gui flag here
953 String[] omitHidden = null;
955 if (viewport.hasHiddenColumns)
957 int reply = JOptionPane
958 .showInternalConfirmDialog(
960 "The Alignment contains hidden columns."
961 + "\nDo you want to save only the visible alignment?",
962 "Save / Omit Hidden Columns",
963 JOptionPane.YES_NO_OPTION,
964 JOptionPane.QUESTION_MESSAGE);
966 if (reply == JOptionPane.YES_OPTION)
968 omitHidden = viewport.getViewAsString(false);
971 FormatAdapter f = new FormatAdapter();
972 String output = f.formatSequences(format,
973 (Alignment) viewport.alignment, // class cast exceptions will
974 // occur in the distant future
975 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
985 java.io.PrintWriter out = new java.io.PrintWriter(
986 new java.io.FileWriter(file));
991 statusBar.setText("Successfully saved to file: " + fileName
992 + " in " + format + " format.");
993 } catch (Exception ex)
996 ex.printStackTrace();
1003 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
1004 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
1010 private void warningMessage(String warning, String title)
1012 if (new jalview.util.Platform().isHeadless())
1014 System.err.println("Warning: " + title + "\nWarning: " + warning);
1019 JOptionPane.showInternalMessageDialog(this, warning, title,
1020 JOptionPane.WARNING_MESSAGE);
1031 protected void outputText_actionPerformed(ActionEvent e)
1033 String[] omitHidden = null;
1035 if (viewport.hasHiddenColumns)
1037 int reply = JOptionPane
1038 .showInternalConfirmDialog(
1040 "The Alignment contains hidden columns."
1041 + "\nDo you want to output only the visible alignment?",
1042 "Save / Omit Hidden Columns",
1043 JOptionPane.YES_NO_OPTION,
1044 JOptionPane.QUESTION_MESSAGE);
1046 if (reply == JOptionPane.YES_OPTION)
1048 omitHidden = viewport.getViewAsString(false);
1052 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1053 cap.setForInput(null);
1054 Desktop.addInternalFrame(cap, "Alignment output - "
1055 + e.getActionCommand(), 600, 500);
1057 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1058 viewport.alignment, omitHidden, viewport.colSel));
1067 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1069 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
1070 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
1071 .getFeatureRenderer());
1074 public void createImageMap(File file, String image)
1076 alignPanel.makePNGImageMap(file, image);
1085 public void createPNG(File f)
1087 alignPanel.makePNG(f);
1096 public void createEPS(File f)
1098 alignPanel.makeEPS(f);
1101 public void pageSetup_actionPerformed(ActionEvent e)
1103 PrinterJob printJob = PrinterJob.getPrinterJob();
1104 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1113 public void printMenuItem_actionPerformed(ActionEvent e)
1115 // Putting in a thread avoids Swing painting problems
1116 PrintThread thread = new PrintThread(alignPanel);
1120 public void exportFeatures_actionPerformed(ActionEvent e)
1122 new AnnotationExporter().exportFeatures(alignPanel);
1125 public void exportAnnotations_actionPerformed(ActionEvent e)
1127 new AnnotationExporter().exportAnnotations(alignPanel,
1128 viewport.showAnnotation ? viewport.alignment
1129 .getAlignmentAnnotation() : null, viewport.alignment
1131 ((Alignment) viewport.alignment).alignmentProperties);
1134 public void associatedData_actionPerformed(ActionEvent e)
1136 // Pick the tree file
1137 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1138 .getProperty("LAST_DIRECTORY"));
1139 chooser.setFileView(new JalviewFileView());
1140 chooser.setDialogTitle("Load Jalview Annotations or Features File");
1141 chooser.setToolTipText("Load Jalview Annotations / Features file");
1143 int value = chooser.showOpenDialog(null);
1145 if (value == JalviewFileChooser.APPROVE_OPTION)
1147 String choice = chooser.getSelectedFile().getPath();
1148 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1149 loadJalviewDataFile(choice);
1155 * Close the current view or all views in the alignment frame. If the frame
1156 * only contains one view then the alignment will be removed from memory.
1158 * @param closeAllTabs
1160 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1162 if (alignPanels != null && alignPanels.size() < 2)
1164 closeAllTabs = true;
1169 if (alignPanels != null)
1173 if (this.isClosed())
1175 // really close all the windows - otherwise wait till
1176 // setClosed(true) is called
1177 for (int i = 0; i < alignPanels.size(); i++)
1179 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1186 closeView(alignPanel);
1192 this.setClosed(true);
1194 } catch (Exception ex)
1196 ex.printStackTrace();
1201 * close alignPanel2 and shuffle tabs appropriately.
1203 * @param alignPanel2
1205 public void closeView(AlignmentPanel alignPanel2)
1207 int index = tabbedPane.getSelectedIndex();
1208 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1209 alignPanels.removeElement(alignPanel2);
1211 // if (viewport == alignPanel2.av)
1215 alignPanel2.closePanel();
1218 tabbedPane.removeTabAt(closedindex);
1219 tabbedPane.validate();
1221 if (index > closedindex || index == tabbedPane.getTabCount())
1223 // modify currently selected tab index if necessary.
1227 this.tabSelectionChanged(index);
1233 void updateEditMenuBar()
1236 if (viewport.historyList.size() > 0)
1238 undoMenuItem.setEnabled(true);
1239 CommandI command = (CommandI) viewport.historyList.peek();
1240 undoMenuItem.setText("Undo " + command.getDescription());
1244 undoMenuItem.setEnabled(false);
1245 undoMenuItem.setText("Undo");
1248 if (viewport.redoList.size() > 0)
1250 redoMenuItem.setEnabled(true);
1252 CommandI command = (CommandI) viewport.redoList.peek();
1253 redoMenuItem.setText("Redo " + command.getDescription());
1257 redoMenuItem.setEnabled(false);
1258 redoMenuItem.setText("Redo");
1262 public void addHistoryItem(CommandI command)
1264 if (command.getSize() > 0)
1266 viewport.historyList.push(command);
1267 viewport.redoList.clear();
1268 updateEditMenuBar();
1269 viewport.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1275 * @return alignment objects for all views
1277 AlignmentI[] getViewAlignments()
1279 if (alignPanels != null)
1281 Enumeration e = alignPanels.elements();
1282 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1283 for (int i = 0; e.hasMoreElements(); i++)
1285 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1289 if (viewport != null)
1291 return new AlignmentI[]
1292 { viewport.alignment };
1303 protected void undoMenuItem_actionPerformed(ActionEvent e)
1305 if (viewport.historyList.empty())
1307 CommandI command = (CommandI) viewport.historyList.pop();
1308 viewport.redoList.push(command);
1309 command.undoCommand(getViewAlignments());
1311 AlignViewport originalSource = getOriginatingSource(command);
1312 updateEditMenuBar();
1314 if (originalSource != null)
1316 originalSource.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1317 originalSource.firePropertyChange("alignment", null,
1318 originalSource.alignment.getSequences());
1328 protected void redoMenuItem_actionPerformed(ActionEvent e)
1330 if (viewport.redoList.size() < 1)
1335 CommandI command = (CommandI) viewport.redoList.pop();
1336 viewport.historyList.push(command);
1337 command.doCommand(getViewAlignments());
1339 AlignViewport originalSource = getOriginatingSource(command);
1340 updateEditMenuBar();
1342 if (originalSource != null)
1344 originalSource.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1345 originalSource.firePropertyChange("alignment", null,
1346 originalSource.alignment.getSequences());
1350 AlignViewport getOriginatingSource(CommandI command)
1352 AlignViewport originalSource = null;
1353 // For sequence removal and addition, we need to fire
1354 // the property change event FROM the viewport where the
1355 // original alignment was altered
1356 AlignmentI al = null;
1357 if (command instanceof EditCommand)
1359 EditCommand editCommand = (EditCommand) command;
1360 al = editCommand.getAlignment();
1361 Vector comps = (Vector) PaintRefresher.components.get(viewport
1362 .getSequenceSetId());
1364 for (int i = 0; i < comps.size(); i++)
1366 if (comps.elementAt(i) instanceof AlignmentPanel)
1368 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1370 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1377 if (originalSource == null)
1379 // The original view is closed, we must validate
1380 // the current view against the closed view first
1383 PaintRefresher.validateSequences(al, viewport.alignment);
1386 originalSource = viewport;
1389 return originalSource;
1398 public void moveSelectedSequences(boolean up)
1400 SequenceGroup sg = viewport.getSelectionGroup();
1409 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1411 SequenceI seq = viewport.alignment.getSequenceAt(i);
1413 if (!sg.getSequences(null).contains(seq))
1418 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1420 if (sg.getSequences(null).contains(temp))
1425 viewport.alignment.getSequences().setElementAt(temp, i);
1426 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1431 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1433 SequenceI seq = viewport.alignment.getSequenceAt(i);
1435 if (!sg.getSequences(null).contains(seq))
1440 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1442 if (sg.getSequences(null).contains(temp))
1447 viewport.alignment.getSequences().setElementAt(temp, i);
1448 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1452 alignPanel.paintAlignment(true);
1455 synchronized void slideSequences(boolean right, int size)
1457 Vector sg = new Vector();
1458 if (viewport.cursorMode)
1460 sg.addElement(viewport.alignment
1461 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1463 else if (viewport.getSelectionGroup() != null
1464 && viewport.getSelectionGroup().getSize() != viewport.alignment
1467 sg = viewport.getSelectionGroup().getSequences(
1468 viewport.hiddenRepSequences);
1476 Vector invertGroup = new Vector();
1478 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1480 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1481 invertGroup.add(viewport.alignment.getSequenceAt(i));
1484 SequenceI[] seqs1 = new SequenceI[sg.size()];
1485 for (int i = 0; i < sg.size(); i++)
1486 seqs1[i] = (SequenceI) sg.elementAt(i);
1488 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1489 for (int i = 0; i < invertGroup.size(); i++)
1490 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1492 SlideSequencesCommand ssc;
1494 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1495 size, viewport.getGapCharacter());
1497 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1498 size, viewport.getGapCharacter());
1500 int groupAdjustment = 0;
1501 if (ssc.getGapsInsertedBegin() && right)
1503 if (viewport.cursorMode)
1504 alignPanel.seqPanel.moveCursor(size, 0);
1506 groupAdjustment = size;
1508 else if (!ssc.getGapsInsertedBegin() && !right)
1510 if (viewport.cursorMode)
1511 alignPanel.seqPanel.moveCursor(-size, 0);
1513 groupAdjustment = -size;
1516 if (groupAdjustment != 0)
1518 viewport.getSelectionGroup().setStartRes(
1519 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1520 viewport.getSelectionGroup().setEndRes(
1521 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1524 boolean appendHistoryItem = false;
1525 if (viewport.historyList != null && viewport.historyList.size() > 0
1526 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1528 appendHistoryItem = ssc
1529 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1533 if (!appendHistoryItem)
1534 addHistoryItem(ssc);
1545 protected void copy_actionPerformed(ActionEvent e)
1548 if (viewport.getSelectionGroup() == null)
1552 // TODO: preserve the ordering of displayed alignment annotation in any
1553 // internal paste (particularly sequence associated annotation)
1554 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1555 String[] omitHidden = null;
1557 if (viewport.hasHiddenColumns)
1559 omitHidden = viewport.getViewAsString(true);
1562 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1565 StringSelection ss = new StringSelection(output);
1569 jalview.gui.Desktop.internalCopy = true;
1570 // Its really worth setting the clipboard contents
1571 // to empty before setting the large StringSelection!!
1572 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1573 new StringSelection(""), null);
1575 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1577 } catch (OutOfMemoryError er)
1579 new OOMWarning("copying region", er);
1583 Vector hiddenColumns = null;
1584 if (viewport.hasHiddenColumns)
1586 hiddenColumns = new Vector();
1587 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1588 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1591 int[] region = (int[]) viewport.getColumnSelection()
1592 .getHiddenColumns().elementAt(i);
1594 hiddenColumns.addElement(new int[]
1595 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1599 Desktop.jalviewClipboard = new Object[]
1600 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1601 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1610 protected void pasteNew_actionPerformed(ActionEvent e)
1621 protected void pasteThis_actionPerformed(ActionEvent e)
1627 * Paste contents of Jalview clipboard
1629 * @param newAlignment
1630 * true to paste to a new alignment, otherwise add to this.
1632 void paste(boolean newAlignment)
1634 boolean externalPaste = true;
1637 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1638 Transferable contents = c.getContents(this);
1640 if (contents == null)
1648 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1649 if (str.length() < 1)
1654 format = new IdentifyFile().Identify(str, "Paste");
1656 } catch (OutOfMemoryError er)
1658 new OOMWarning("Out of memory pasting sequences!!", er);
1662 SequenceI[] sequences;
1663 boolean annotationAdded = false;
1664 AlignmentI alignment = null;
1666 if (Desktop.jalviewClipboard != null)
1668 // The clipboard was filled from within Jalview, we must use the
1670 // And dataset from the copied alignment
1671 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1672 // be doubly sure that we create *new* sequence objects.
1673 sequences = new SequenceI[newseq.length];
1674 for (int i = 0; i < newseq.length; i++)
1676 sequences[i] = new Sequence(newseq[i]);
1678 alignment = new Alignment(sequences);
1679 externalPaste = false;
1683 // parse the clipboard as an alignment.
1684 alignment = new FormatAdapter().readFile(str, "Paste", format);
1685 sequences = alignment.getSequencesArray();
1693 if (Desktop.jalviewClipboard != null)
1695 // dataset is inherited
1696 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1700 // new dataset is constructed
1701 alignment.setDataset(null);
1703 alwidth = alignment.getWidth() + 1;
1707 AlignmentI pastedal = alignment; // preserve pasted alignment object
1708 // Add pasted sequences and dataset into existing alignment.
1709 alignment = viewport.getAlignment();
1710 alwidth = alignment.getWidth() + 1;
1711 // decide if we need to import sequences from an existing dataset
1712 boolean importDs = Desktop.jalviewClipboard != null
1713 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1714 // importDs==true instructs us to copy over new dataset sequences from
1715 // an existing alignment
1716 Vector newDs = (importDs) ? new Vector() : null; // used to create
1717 // minimum dataset set
1719 for (int i = 0; i < sequences.length; i++)
1723 newDs.addElement(null);
1725 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1727 if (importDs && ds != null)
1729 if (!newDs.contains(ds))
1731 newDs.setElementAt(ds, i);
1732 ds = new Sequence(ds);
1733 // update with new dataset sequence
1734 sequences[i].setDatasetSequence(ds);
1738 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1743 // copy and derive new dataset sequence
1744 sequences[i] = sequences[i].deriveSequence();
1745 alignment.getDataset().addSequence(
1746 sequences[i].getDatasetSequence());
1747 // TODO: avoid creation of duplicate dataset sequences with a
1748 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1750 alignment.addSequence(sequences[i]); // merges dataset
1754 newDs.clear(); // tidy up
1756 if (pastedal.getAlignmentAnnotation() != null)
1758 // Add any annotation attached to alignment.
1759 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1760 for (int i = 0; i < alann.length; i++)
1762 annotationAdded = true;
1763 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1765 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1766 newann.padAnnotation(alwidth);
1767 alignment.addAnnotation(newann);
1777 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1778 sequences, 0, alignment.getWidth(), alignment));
1780 // Add any annotations attached to sequences
1781 for (int i = 0; i < sequences.length; i++)
1783 if (sequences[i].getAnnotation() != null)
1785 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1787 annotationAdded = true;
1788 sequences[i].getAnnotation()[a].adjustForAlignment();
1789 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1790 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1795 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1802 // propagate alignment changed.
1803 viewport.setEndSeq(alignment.getHeight());
1804 if (annotationAdded)
1806 // Duplicate sequence annotation in all views.
1807 AlignmentI[] alview = this.getViewAlignments();
1808 for (int i = 0; i < sequences.length; i++)
1810 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1813 for (int avnum = 0; avnum < alview.length; avnum++)
1815 if (alview[avnum] != alignment)
1817 // duplicate in a view other than the one with input focus
1818 int avwidth = alview[avnum].getWidth() + 1;
1819 // this relies on sann being preserved after we
1820 // modify the sequence's annotation array for each duplication
1821 for (int a = 0; a < sann.length; a++)
1823 AlignmentAnnotation newann = new AlignmentAnnotation(
1825 sequences[i].addAlignmentAnnotation(newann);
1826 newann.padAnnotation(avwidth);
1827 alview[avnum].addAnnotation(newann); // annotation was
1828 // duplicated earlier
1829 alview[avnum].setAnnotationIndex(newann, a);
1834 buildSortByAnnotationScoresMenu();
1836 viewport.firePropertyChange("alignment", null, alignment
1842 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1844 String newtitle = new String("Copied sequences");
1846 if (Desktop.jalviewClipboard != null
1847 && Desktop.jalviewClipboard[2] != null)
1849 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1850 for (int i = 0; i < hc.size(); i++)
1852 int[] region = (int[]) hc.elementAt(i);
1853 af.viewport.hideColumns(region[0], region[1]);
1857 // >>>This is a fix for the moment, until a better solution is
1859 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1861 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1863 // TODO: maintain provenance of an alignment, rather than just make the
1864 // title a concatenation of operations.
1867 if (title.startsWith("Copied sequences"))
1873 newtitle = newtitle.concat("- from " + title);
1878 newtitle = new String("Pasted sequences");
1881 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1886 } catch (Exception ex)
1888 ex.printStackTrace();
1889 System.out.println("Exception whilst pasting: " + ex);
1890 // could be anything being pasted in here
1901 protected void cut_actionPerformed(ActionEvent e)
1903 copy_actionPerformed(null);
1904 delete_actionPerformed(null);
1913 protected void delete_actionPerformed(ActionEvent evt)
1916 SequenceGroup sg = viewport.getSelectionGroup();
1922 Vector seqs = new Vector();
1924 for (int i = 0; i < sg.getSize(); i++)
1926 seq = sg.getSequenceAt(i);
1927 seqs.addElement(seq);
1930 // If the cut affects all sequences, remove highlighted columns
1931 if (sg.getSize() == viewport.alignment.getHeight())
1933 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1934 sg.getEndRes() + 1);
1937 SequenceI[] cut = new SequenceI[seqs.size()];
1938 for (int i = 0; i < seqs.size(); i++)
1940 cut[i] = (SequenceI) seqs.elementAt(i);
1944 * //ADD HISTORY ITEM
1946 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1947 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1948 viewport.alignment));
1950 viewport.setSelectionGroup(null);
1951 viewport.sendSelection();
1952 viewport.alignment.deleteGroup(sg);
1954 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1956 if (viewport.getAlignment().getHeight() < 1)
1960 this.setClosed(true);
1961 } catch (Exception ex)
1973 protected void deleteGroups_actionPerformed(ActionEvent e)
1975 viewport.alignment.deleteAllGroups();
1976 viewport.sequenceColours = null;
1977 viewport.setSelectionGroup(null);
1978 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1979 alignPanel.updateAnnotation();
1980 alignPanel.paintAlignment(true);
1989 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1991 SequenceGroup sg = new SequenceGroup();
1993 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1995 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1998 sg.setEndRes(viewport.alignment.getWidth() - 1);
1999 viewport.setSelectionGroup(sg);
2000 viewport.sendSelection();
2001 alignPanel.paintAlignment(true);
2002 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2011 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2013 if (viewport.cursorMode)
2015 alignPanel.seqPanel.keyboardNo1 = null;
2016 alignPanel.seqPanel.keyboardNo2 = null;
2018 viewport.setSelectionGroup(null);
2019 viewport.getColumnSelection().clear();
2020 viewport.setSelectionGroup(null);
2021 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2022 alignPanel.idPanel.idCanvas.searchResults = null;
2023 alignPanel.paintAlignment(true);
2024 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2033 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2035 SequenceGroup sg = viewport.getSelectionGroup();
2039 selectAllSequenceMenuItem_actionPerformed(null);
2044 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2046 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2049 alignPanel.paintAlignment(true);
2050 viewport.sendSelection();
2051 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2054 public void invertColSel_actionPerformed(ActionEvent e)
2056 viewport.invertColumnSelection();
2057 alignPanel.paintAlignment(true);
2066 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2068 trimAlignment(true);
2077 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2079 trimAlignment(false);
2082 void trimAlignment(boolean trimLeft)
2084 ColumnSelection colSel = viewport.getColumnSelection();
2087 if (colSel.size() > 0)
2091 column = colSel.getMin();
2095 column = colSel.getMax();
2099 if (viewport.getSelectionGroup() != null)
2101 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2102 viewport.hiddenRepSequences);
2106 seqs = viewport.alignment.getSequencesArray();
2109 TrimRegionCommand trimRegion;
2112 trimRegion = new TrimRegionCommand("Remove Left",
2113 TrimRegionCommand.TRIM_LEFT, seqs, column,
2114 viewport.alignment, viewport.colSel,
2115 viewport.selectionGroup);
2116 viewport.setStartRes(0);
2120 trimRegion = new TrimRegionCommand("Remove Right",
2121 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2122 viewport.alignment, viewport.colSel,
2123 viewport.selectionGroup);
2126 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
2128 addHistoryItem(trimRegion);
2130 Vector groups = viewport.alignment.getGroups();
2132 for (int i = 0; i < groups.size(); i++)
2134 SequenceGroup sg = (SequenceGroup) groups.get(i);
2136 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2137 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2139 viewport.alignment.deleteGroup(sg);
2143 viewport.firePropertyChange("alignment", null, viewport
2144 .getAlignment().getSequences());
2154 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2156 int start = 0, end = viewport.alignment.getWidth() - 1;
2159 if (viewport.getSelectionGroup() != null)
2161 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2162 viewport.hiddenRepSequences);
2163 start = viewport.getSelectionGroup().getStartRes();
2164 end = viewport.getSelectionGroup().getEndRes();
2168 seqs = viewport.alignment.getSequencesArray();
2171 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2172 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
2174 addHistoryItem(removeGapCols);
2176 statusBar.setText("Removed " + removeGapCols.getSize()
2177 + " empty columns.");
2179 // This is to maintain viewport position on first residue
2180 // of first sequence
2181 SequenceI seq = viewport.alignment.getSequenceAt(0);
2182 int startRes = seq.findPosition(viewport.startRes);
2183 // ShiftList shifts;
2184 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2185 // edit.alColumnChanges=shifts.getInverse();
2186 // if (viewport.hasHiddenColumns)
2187 // viewport.getColumnSelection().compensateForEdits(shifts);
2188 viewport.setStartRes(seq.findIndex(startRes) - 1);
2189 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2200 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2202 int start = 0, end = viewport.alignment.getWidth() - 1;
2205 if (viewport.getSelectionGroup() != null)
2207 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2208 viewport.hiddenRepSequences);
2209 start = viewport.getSelectionGroup().getStartRes();
2210 end = viewport.getSelectionGroup().getEndRes();
2214 seqs = viewport.alignment.getSequencesArray();
2217 // This is to maintain viewport position on first residue
2218 // of first sequence
2219 SequenceI seq = viewport.alignment.getSequenceAt(0);
2220 int startRes = seq.findPosition(viewport.startRes);
2222 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2223 viewport.alignment));
2225 viewport.setStartRes(seq.findIndex(startRes) - 1);
2227 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2238 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2240 viewport.padGaps = padGapsMenuitem.isSelected();
2241 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2247 // if (justifySeqs>0)
2249 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2261 public void findMenuItem_actionPerformed(ActionEvent e)
2266 public void newView_actionPerformed(ActionEvent e)
2268 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2271 newap.av.gatherViewsHere = false;
2273 if (viewport.viewName == null)
2275 viewport.viewName = "Original";
2278 newap.av.historyList = viewport.historyList;
2279 newap.av.redoList = viewport.redoList;
2281 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2282 String newViewName = "View " + index;
2284 Vector comps = (Vector) PaintRefresher.components.get(viewport
2285 .getSequenceSetId());
2286 Vector existingNames = new Vector();
2287 for (int i = 0; i < comps.size(); i++)
2289 if (comps.elementAt(i) instanceof AlignmentPanel)
2291 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2292 if (!existingNames.contains(ap.av.viewName))
2294 existingNames.addElement(ap.av.viewName);
2299 while (existingNames.contains(newViewName))
2301 newViewName = "View " + (++index);
2304 newap.av.viewName = newViewName;
2306 addAlignmentPanel(newap, true);
2308 if (alignPanels.size() == 2)
2310 viewport.gatherViewsHere = true;
2312 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2315 public void expandViews_actionPerformed(ActionEvent e)
2317 Desktop.instance.explodeViews(this);
2320 public void gatherViews_actionPerformed(ActionEvent e)
2322 Desktop.instance.gatherViews(this);
2331 public void font_actionPerformed(ActionEvent e)
2333 new FontChooser(alignPanel);
2342 protected void seqLimit_actionPerformed(ActionEvent e)
2344 viewport.setShowJVSuffix(seqLimits.isSelected());
2346 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2347 .calculateIdWidth());
2348 alignPanel.paintAlignment(true);
2351 public void idRightAlign_actionPerformed(ActionEvent e)
2353 viewport.rightAlignIds = idRightAlign.isSelected();
2354 alignPanel.paintAlignment(true);
2357 public void centreColumnLabels_actionPerformed(ActionEvent e)
2359 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2360 alignPanel.paintAlignment(true);
2366 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2368 protected void followHighlight_actionPerformed()
2370 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2372 alignPanel.scrollToPosition(
2373 alignPanel.seqPanel.seqCanvas.searchResults, false);
2383 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2385 viewport.setColourText(colourTextMenuItem.isSelected());
2386 alignPanel.paintAlignment(true);
2395 public void wrapMenuItem_actionPerformed(ActionEvent e)
2397 scaleAbove.setVisible(wrapMenuItem.isSelected());
2398 scaleLeft.setVisible(wrapMenuItem.isSelected());
2399 scaleRight.setVisible(wrapMenuItem.isSelected());
2400 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2401 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2404 public void showAllSeqs_actionPerformed(ActionEvent e)
2406 viewport.showAllHiddenSeqs();
2409 public void showAllColumns_actionPerformed(ActionEvent e)
2411 viewport.showAllHiddenColumns();
2415 public void hideSelSequences_actionPerformed(ActionEvent e)
2417 viewport.hideAllSelectedSeqs();
2418 alignPanel.paintAlignment(true);
2421 public void hideSelColumns_actionPerformed(ActionEvent e)
2423 viewport.hideSelectedColumns();
2424 alignPanel.paintAlignment(true);
2427 public void hiddenMarkers_actionPerformed(ActionEvent e)
2429 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2439 protected void scaleAbove_actionPerformed(ActionEvent e)
2441 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2442 alignPanel.paintAlignment(true);
2451 protected void scaleLeft_actionPerformed(ActionEvent e)
2453 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2454 alignPanel.paintAlignment(true);
2463 protected void scaleRight_actionPerformed(ActionEvent e)
2465 viewport.setScaleRightWrapped(scaleRight.isSelected());
2466 alignPanel.paintAlignment(true);
2475 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2477 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2478 alignPanel.paintAlignment(true);
2487 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2489 viewport.setShowText(viewTextMenuItem.isSelected());
2490 alignPanel.paintAlignment(true);
2499 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2501 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2502 alignPanel.paintAlignment(true);
2505 public FeatureSettings featureSettings;
2507 public void featureSettings_actionPerformed(ActionEvent e)
2509 if (featureSettings != null)
2511 featureSettings.close();
2512 featureSettings = null;
2514 if (!showSeqFeatures.isSelected())
2516 // make sure features are actually displayed
2517 showSeqFeatures.setSelected(true);
2518 showSeqFeatures_actionPerformed(null);
2520 featureSettings = new FeatureSettings(this);
2524 * Set or clear 'Show Sequence Features'
2529 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2531 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2532 alignPanel.paintAlignment(true);
2533 if (alignPanel.getOverviewPanel() != null)
2535 alignPanel.getOverviewPanel().updateOverviewImage();
2540 * Set or clear 'Show Sequence Features'
2545 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2547 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2549 if (viewport.getShowSequenceFeaturesHeight())
2551 // ensure we're actually displaying features
2552 viewport.setShowSequenceFeatures(true);
2553 showSeqFeatures.setSelected(true);
2555 alignPanel.paintAlignment(true);
2556 if (alignPanel.getOverviewPanel() != null)
2558 alignPanel.getOverviewPanel().updateOverviewImage();
2568 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2570 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2571 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2574 public void alignmentProperties()
2576 JEditorPane editPane = new JEditorPane("text/html", "");
2577 editPane.setEditable(false);
2578 StringBuffer contents = new StringBuffer("<html>");
2581 int min = Integer.MAX_VALUE, max = 0;
2582 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2584 int size = viewport.alignment.getSequenceAt(i).getEnd()
2585 - viewport.alignment.getSequenceAt(i).getStart();
2592 avg = avg / (float) viewport.alignment.getHeight();
2594 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2595 contents.append("<br>Minimum Sequence Length: " + min);
2596 contents.append("<br>Maximum Sequence Length: " + max);
2597 contents.append("<br>Average Length: " + (int) avg);
2599 if (((Alignment) viewport.alignment).getProperties() != null)
2601 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2602 Enumeration en = props.keys();
2603 contents.append("<br><br><table border=\"1\">");
2604 while (en.hasMoreElements())
2606 String key = en.nextElement().toString();
2607 StringBuffer val = new StringBuffer();
2608 String vals = props.get(key).toString();
2612 npos = vals.indexOf("\n", pos);
2615 val.append(vals.substring(pos));
2619 val.append(vals.substring(pos, npos));
2623 } while (npos != -1);
2625 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2627 contents.append("</table>");
2629 editPane.setText(contents.toString() + "</html>");
2630 JInternalFrame frame = new JInternalFrame();
2631 frame.getContentPane().add(new JScrollPane(editPane));
2633 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2634 + getTitle(), 500, 400);
2643 public void overviewMenuItem_actionPerformed(ActionEvent e)
2645 if (alignPanel.overviewPanel != null)
2650 JInternalFrame frame = new JInternalFrame();
2651 OverviewPanel overview = new OverviewPanel(alignPanel);
2652 frame.setContentPane(overview);
2653 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2654 .getWidth(), frame.getHeight());
2656 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2658 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2660 public void internalFrameClosed(
2661 javax.swing.event.InternalFrameEvent evt)
2663 alignPanel.setOverviewPanel(null);
2667 alignPanel.setOverviewPanel(overview);
2670 public void textColour_actionPerformed(ActionEvent e)
2672 new TextColourChooser().chooseColour(alignPanel, null);
2681 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2692 public void clustalColour_actionPerformed(ActionEvent e)
2694 changeColour(new ClustalxColourScheme(
2695 viewport.alignment.getSequences(), viewport.alignment
2705 public void zappoColour_actionPerformed(ActionEvent e)
2707 changeColour(new ZappoColourScheme());
2716 public void taylorColour_actionPerformed(ActionEvent e)
2718 changeColour(new TaylorColourScheme());
2727 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2729 changeColour(new HydrophobicColourScheme());
2738 public void helixColour_actionPerformed(ActionEvent e)
2740 changeColour(new HelixColourScheme());
2749 public void strandColour_actionPerformed(ActionEvent e)
2751 changeColour(new StrandColourScheme());
2760 public void turnColour_actionPerformed(ActionEvent e)
2762 changeColour(new TurnColourScheme());
2771 public void buriedColour_actionPerformed(ActionEvent e)
2773 changeColour(new BuriedColourScheme());
2782 public void nucleotideColour_actionPerformed(ActionEvent e)
2784 changeColour(new NucleotideColourScheme());
2787 public void annotationColour_actionPerformed(ActionEvent e)
2789 new AnnotationColourChooser(viewport, alignPanel);
2798 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2800 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2809 public void changeColour(ColourSchemeI cs)
2815 if (viewport.getAbovePIDThreshold())
2817 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2820 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2822 viewport.setGlobalColourScheme(cs);
2826 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2829 if (viewport.getConservationSelected())
2832 Alignment al = (Alignment) viewport.alignment;
2833 Conservation c = new Conservation("All",
2834 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2838 c.verdict(false, viewport.ConsPercGaps);
2840 cs.setConservation(c);
2842 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2847 cs.setConservation(null);
2850 cs.setConsensus(viewport.hconsensus);
2853 viewport.setGlobalColourScheme(cs);
2855 if (viewport.getColourAppliesToAllGroups())
2857 Vector groups = viewport.alignment.getGroups();
2859 for (int i = 0; i < groups.size(); i++)
2861 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2869 if (cs instanceof ClustalxColourScheme)
2871 sg.cs = new ClustalxColourScheme(sg
2872 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2874 else if (cs instanceof UserColourScheme)
2876 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2882 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2883 } catch (Exception ex)
2888 if (viewport.getAbovePIDThreshold()
2889 || cs instanceof PIDColourScheme
2890 || cs instanceof Blosum62ColourScheme)
2892 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2894 sg.cs.setConsensus(AAFrequency.calculate(sg
2895 .getSequences(viewport.hiddenRepSequences), sg
2896 .getStartRes(), sg.getEndRes() + 1));
2900 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2903 if (viewport.getConservationSelected())
2905 Conservation c = new Conservation("Group",
2906 ResidueProperties.propHash, 3, sg
2907 .getSequences(viewport.hiddenRepSequences), sg
2908 .getStartRes(), sg.getEndRes() + 1);
2910 c.verdict(false, viewport.ConsPercGaps);
2911 sg.cs.setConservation(c);
2915 sg.cs.setConservation(null);
2920 if (alignPanel.getOverviewPanel() != null)
2922 alignPanel.getOverviewPanel().updateOverviewImage();
2925 alignPanel.paintAlignment(true);
2934 protected void modifyPID_actionPerformed(ActionEvent e)
2936 if (viewport.getAbovePIDThreshold()
2937 && viewport.globalColourScheme != null)
2939 SliderPanel.setPIDSliderSource(alignPanel, viewport
2940 .getGlobalColourScheme(), "Background");
2941 SliderPanel.showPIDSlider();
2951 protected void modifyConservation_actionPerformed(ActionEvent e)
2953 if (viewport.getConservationSelected()
2954 && viewport.globalColourScheme != null)
2956 SliderPanel.setConservationSlider(alignPanel,
2957 viewport.globalColourScheme, "Background");
2958 SliderPanel.showConservationSlider();
2968 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2970 viewport.setConservationSelected(conservationMenuItem.isSelected());
2972 viewport.setAbovePIDThreshold(false);
2973 abovePIDThreshold.setSelected(false);
2975 changeColour(viewport.getGlobalColourScheme());
2977 modifyConservation_actionPerformed(null);
2986 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2988 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2990 conservationMenuItem.setSelected(false);
2991 viewport.setConservationSelected(false);
2993 changeColour(viewport.getGlobalColourScheme());
2995 modifyPID_actionPerformed(null);
3004 public void userDefinedColour_actionPerformed(ActionEvent e)
3006 if (e.getActionCommand().equals("User Defined..."))
3008 new UserDefinedColours(alignPanel, null);
3012 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3013 .getUserColourSchemes().get(e.getActionCommand());
3019 public void updateUserColourMenu()
3022 Component[] menuItems = colourMenu.getMenuComponents();
3023 int i, iSize = menuItems.length;
3024 for (i = 0; i < iSize; i++)
3026 if (menuItems[i].getName() != null
3027 && menuItems[i].getName().equals("USER_DEFINED"))
3029 colourMenu.remove(menuItems[i]);
3033 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3035 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3036 .getUserColourSchemes().keys();
3038 while (userColours.hasMoreElements())
3040 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3041 userColours.nextElement().toString());
3042 radioItem.setName("USER_DEFINED");
3043 radioItem.addMouseListener(new MouseAdapter()
3045 public void mousePressed(MouseEvent evt)
3047 if (evt.isControlDown()
3048 || SwingUtilities.isRightMouseButton(evt))
3051 .removeActionListener(radioItem.getActionListeners()[0]);
3053 int option = JOptionPane.showInternalConfirmDialog(
3054 jalview.gui.Desktop.desktop,
3055 "Remove from default list?",
3056 "Remove user defined colour",
3057 JOptionPane.YES_NO_OPTION);
3058 if (option == JOptionPane.YES_OPTION)
3060 jalview.gui.UserDefinedColours
3061 .removeColourFromDefaults(radioItem.getText());
3062 colourMenu.remove(radioItem);
3066 radioItem.addActionListener(new ActionListener()
3068 public void actionPerformed(ActionEvent evt)
3070 userDefinedColour_actionPerformed(evt);
3077 radioItem.addActionListener(new ActionListener()
3079 public void actionPerformed(ActionEvent evt)
3081 userDefinedColour_actionPerformed(evt);
3085 colourMenu.insert(radioItem, 15);
3086 colours.add(radioItem);
3097 public void PIDColour_actionPerformed(ActionEvent e)
3099 changeColour(new PIDColourScheme());
3108 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3110 changeColour(new Blosum62ColourScheme());
3119 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3121 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3122 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3123 .getAlignment().getSequenceAt(0), null);
3124 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3125 viewport.alignment));
3126 alignPanel.paintAlignment(true);
3135 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3137 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3138 AlignmentSorter.sortByID(viewport.getAlignment());
3139 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
3140 alignPanel.paintAlignment(true);
3149 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3151 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3152 AlignmentSorter.sortByLength(viewport.getAlignment());
3153 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3154 viewport.alignment));
3155 alignPanel.paintAlignment(true);
3164 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3166 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3167 AlignmentSorter.sortByGroup(viewport.getAlignment());
3168 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3169 viewport.alignment));
3171 alignPanel.paintAlignment(true);
3180 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3182 new RedundancyPanel(alignPanel, this);
3191 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3193 if ((viewport.getSelectionGroup() == null)
3194 || (viewport.getSelectionGroup().getSize() < 2))
3196 JOptionPane.showInternalMessageDialog(this,
3197 "You must select at least 2 sequences.", "Invalid Selection",
3198 JOptionPane.WARNING_MESSAGE);
3202 JInternalFrame frame = new JInternalFrame();
3203 frame.setContentPane(new PairwiseAlignPanel(viewport));
3204 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
3214 public void PCAMenuItem_actionPerformed(ActionEvent e)
3216 if (((viewport.getSelectionGroup() != null)
3217 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3218 .getSelectionGroup().getSize() > 0))
3219 || (viewport.getAlignment().getHeight() < 4))
3221 JOptionPane.showInternalMessageDialog(this,
3222 "Principal component analysis must take\n"
3223 + "at least 4 input sequences.",
3224 "Sequence selection insufficient",
3225 JOptionPane.WARNING_MESSAGE);
3230 new PCAPanel(alignPanel);
3233 public void autoCalculate_actionPerformed(ActionEvent e)
3235 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3236 if (viewport.autoCalculateConsensus)
3238 viewport.firePropertyChange("alignment", null, viewport
3239 .getAlignment().getSequences());
3249 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3251 NewTreePanel("AV", "PID", "Average distance tree using PID");
3260 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3262 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3271 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3273 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3282 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3284 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3297 void NewTreePanel(String type, String pwType, String title)
3301 if (viewport.getSelectionGroup() != null)
3303 if (viewport.getSelectionGroup().getSize() < 3)
3308 "You need to have more than two sequences selected to build a tree!",
3309 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3314 SequenceGroup sg = viewport.getSelectionGroup();
3316 /* Decide if the selection is a column region */
3317 while (s < sg.getSize())
3319 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3325 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3326 + "Try using the Pad function in the edit menu,\n"
3327 + "or one of the multiple sequence alignment web services.",
3328 "Sequences in selection are not aligned",
3329 JOptionPane.WARNING_MESSAGE);
3335 title = title + " on region";
3336 tp = new TreePanel(alignPanel, type, pwType);
3340 // are the sequences aligned?
3341 if (!viewport.alignment.isAligned())
3346 "The sequences must be aligned before creating a tree.\n"
3347 + "Try using the Pad function in the edit menu,\n"
3348 + "or one of the multiple sequence alignment web services.",
3349 "Sequences not aligned",
3350 JOptionPane.WARNING_MESSAGE);
3355 if (viewport.alignment.getHeight() < 2)
3360 tp = new TreePanel(alignPanel, type, pwType);
3365 if (viewport.viewName != null)
3367 title += viewport.viewName + " of ";
3370 title += this.title;
3372 Desktop.addInternalFrame(tp, title, 600, 500);
3383 public void addSortByOrderMenuItem(String title,
3384 final AlignmentOrder order)
3386 final JMenuItem item = new JMenuItem("by " + title);
3388 item.addActionListener(new java.awt.event.ActionListener()
3390 public void actionPerformed(ActionEvent e)
3392 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3394 // TODO: JBPNote - have to map order entries to curent SequenceI
3396 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3398 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3399 viewport.alignment));
3401 alignPanel.paintAlignment(true);
3407 * Add a new sort by annotation score menu item
3410 * the menu to add the option to
3412 * the label used to retrieve scores for each sequence on the
3415 public void addSortByAnnotScoreMenuItem(JMenu sort,
3416 final String scoreLabel)
3418 final JMenuItem item = new JMenuItem(scoreLabel);
3420 item.addActionListener(new java.awt.event.ActionListener()
3422 public void actionPerformed(ActionEvent e)
3424 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3425 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3426 .getAlignment());// ,viewport.getSelectionGroup());
3427 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3428 viewport.alignment));
3429 alignPanel.paintAlignment(true);
3435 * last hash for alignment's annotation array - used to minimise cost of
3438 protected int _annotationScoreVectorHash;
3441 * search the alignment and rebuild the sort by annotation score submenu the
3442 * last alignment annotation vector hash is stored to minimize cost of
3443 * rebuilding in subsequence calls.
3446 public void buildSortByAnnotationScoresMenu()
3448 if (viewport.alignment.getAlignmentAnnotation() == null)
3453 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3455 sortByAnnotScore.removeAll();
3456 // almost certainly a quicker way to do this - but we keep it simple
3457 Hashtable scoreSorts = new Hashtable();
3458 AlignmentAnnotation aann[];
3459 Enumeration sq = viewport.alignment.getSequences().elements();
3460 while (sq.hasMoreElements())
3462 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3463 for (int i = 0; aann != null && i < aann.length; i++)
3465 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3467 scoreSorts.put(aann[i].label, aann[i].label);
3471 Enumeration labels = scoreSorts.keys();
3472 while (labels.hasMoreElements())
3474 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3477 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3480 _annotationScoreVectorHash = viewport.alignment
3481 .getAlignmentAnnotation().hashCode();
3486 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3487 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3488 * call. Listeners are added to remove the menu item when the treePanel is
3489 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3493 * Displayed tree window.
3495 * SortBy menu item title.
3497 public void buildTreeMenu()
3499 sortByTreeMenu.removeAll();
3501 Vector comps = (Vector) PaintRefresher.components.get(viewport
3502 .getSequenceSetId());
3503 Vector treePanels = new Vector();
3504 int i, iSize = comps.size();
3505 for (i = 0; i < iSize; i++)
3507 if (comps.elementAt(i) instanceof TreePanel)
3509 treePanels.add(comps.elementAt(i));
3513 iSize = treePanels.size();
3517 sortByTreeMenu.setVisible(false);
3521 sortByTreeMenu.setVisible(true);
3523 for (i = 0; i < treePanels.size(); i++)
3525 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3526 final JMenuItem item = new JMenuItem(tp.getTitle());
3527 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3528 item.addActionListener(new java.awt.event.ActionListener()
3530 public void actionPerformed(ActionEvent e)
3532 SequenceI[] oldOrder = viewport.getAlignment()
3533 .getSequencesArray();
3534 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3536 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3537 viewport.alignment));
3539 alignPanel.paintAlignment(true);
3543 sortByTreeMenu.add(item);
3548 * Work out whether the whole set of sequences or just the selected set will
3549 * be submitted for multiple alignment.
3552 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3554 // Now, check we have enough sequences
3555 AlignmentView msa = null;
3557 if ((viewport.getSelectionGroup() != null)
3558 && (viewport.getSelectionGroup().getSize() > 1))
3560 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3561 // some common interface!
3563 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3564 * SequenceI[sz = seqs.getSize(false)];
3566 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3567 * seqs.getSequenceAt(i); }
3569 msa = viewport.getAlignmentView(true);
3574 * Vector seqs = viewport.getAlignment().getSequences();
3576 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3578 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3579 * seqs.elementAt(i); } }
3581 msa = viewport.getAlignmentView(false);
3587 * Decides what is submitted to a secondary structure prediction service: the
3588 * first sequence in the alignment, or in the current selection, or, if the
3589 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3590 * region or the whole alignment. (where the first sequence in the set is the
3591 * one that the prediction will be for).
3593 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3595 AlignmentView seqs = null;
3597 if ((viewport.getSelectionGroup() != null)
3598 && (viewport.getSelectionGroup().getSize() > 0))
3600 seqs = viewport.getAlignmentView(true);
3604 seqs = viewport.getAlignmentView(false);
3606 // limit sequences - JBPNote in future - could spawn multiple prediction
3608 // TODO: viewport.alignment.isAligned is a global state - the local
3609 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3610 if (!viewport.alignment.isAligned())
3612 seqs.setSequences(new SeqCigar[]
3613 { seqs.getSequences()[0] });
3614 // TODO: if seqs.getSequences().length>1 then should really have warned user!
3626 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3628 // Pick the tree file
3629 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3630 .getProperty("LAST_DIRECTORY"));
3631 chooser.setFileView(new JalviewFileView());
3632 chooser.setDialogTitle("Select a newick-like tree file");
3633 chooser.setToolTipText("Load a tree file");
3635 int value = chooser.showOpenDialog(null);
3637 if (value == JalviewFileChooser.APPROVE_OPTION)
3639 String choice = chooser.getSelectedFile().getPath();
3640 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3641 jalview.io.NewickFile fin = null;
3644 fin = new jalview.io.NewickFile(choice, "File");
3645 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3646 } catch (Exception ex)
3648 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3649 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3650 ex.printStackTrace();
3652 if (fin != null && fin.hasWarningMessage())
3654 JOptionPane.showMessageDialog(Desktop.desktop, fin
3655 .getWarningMessage(), "Possible problem with tree file",
3656 JOptionPane.WARNING_MESSAGE);
3661 public TreePanel ShowNewickTree(NewickFile nf, String title)
3663 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3666 public TreePanel ShowNewickTree(NewickFile nf, String title,
3667 AlignmentView input)
3669 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3672 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3673 int h, int x, int y)
3675 return ShowNewickTree(nf, title, null, w, h, x, y);
3679 * Add a treeviewer for the tree extracted from a newick file object to the
3680 * current alignment view
3687 * Associated alignment input data (or null)
3696 * @return TreePanel handle
3698 public TreePanel ShowNewickTree(NewickFile nf, String title,
3699 AlignmentView input, int w, int h, int x, int y)
3701 TreePanel tp = null;
3707 if (nf.getTree() != null)
3709 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3715 tp.setLocation(x, y);
3718 Desktop.addInternalFrame(tp, title, w, h);
3720 } catch (Exception ex)
3722 ex.printStackTrace();
3729 * Generates menu items and listener event actions for web service clients
3732 public void BuildWebServiceMenu()
3734 // TODO: add support for context dependent disabling of services based on
3735 // alignment and current selection
3736 // TODO: add additional serviceHandle parameter to specify abstract handler
3737 // class independently of AbstractName
3738 // TODO: add in rediscovery GUI function to restart discoverer
3739 // TODO: group services by location as well as function and/or introduce
3740 // object broker mechanism.
3741 if ((Discoverer.services != null) && (Discoverer.services.size() > 0))
3743 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3744 // stored or retrieved from elsewhere
3745 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3746 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3747 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3748 // TODO: move GUI generation code onto service implementation - so a
3749 // client instance attaches itself to the GUI with method call like
3750 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3752 Vector wsmenu = new Vector();
3753 final IProgressIndicator af = this;
3756 // Add any Multiple Sequence Alignment Services
3757 final JMenu msawsmenu = new JMenu("Alignment");
3758 for (int i = 0, j = msaws.size(); i < j; i++)
3760 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3762 jalview.ws.WSClient impl = jalview.ws.Discoverer
3763 .getServiceClient(sh);
3764 impl.attachWSMenuEntry(msawsmenu, this);
3767 wsmenu.add(msawsmenu);
3769 if (secstrpr != null)
3771 // Add any secondary structure prediction services
3772 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3773 for (int i = 0, j = secstrpr.size(); i < j; i++)
3775 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3777 jalview.ws.WSClient impl = jalview.ws.Discoverer
3778 .getServiceClient(sh);
3779 impl.attachWSMenuEntry(secstrmenu, this);
3781 wsmenu.add(secstrmenu);
3783 if (seqsrch != null)
3785 // Add any sequence search services
3786 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3787 for (int i = 0, j = seqsrch.size(); i < j; i++)
3789 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3791 jalview.ws.WSClient impl = jalview.ws.Discoverer
3792 .getServiceClient(sh);
3793 impl.attachWSMenuEntry(seqsrchmenu, this);
3795 wsmenu.add(seqsrchmenu);
3797 // finally, add the whole shebang onto the webservices menu
3798 resetWebServiceMenu();
3799 for (int i = 0, j = wsmenu.size(); i < j; i++)
3801 webService.add((JMenu) wsmenu.get(i));
3806 resetWebServiceMenu();
3807 this.webService.add(this.webServiceNoServices);
3812 * empty the web service menu and add any ad-hoc functions not dynamically
3816 private void resetWebServiceMenu()
3818 webService.removeAll();
3819 build_fetchdbmenu(webService);
3820 build_urlServiceMenu(webService);
3824 * construct any groupURL type service menu entries.
3827 private void build_urlServiceMenu(JMenu webService)
3829 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(webService, this);
3833 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3834 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3835 * getProperty("LAST_DIRECTORY"));
3837 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3838 * to Vamsas file"); chooser.setToolTipText("Export");
3840 * int value = chooser.showSaveDialog(this);
3842 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3843 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3844 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3845 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3848 * prototype of an automatically enabled/disabled analysis function
3851 protected void setShowProductsEnabled()
3853 SequenceI[] selection = viewport.getSequenceSelection();
3854 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3855 viewport.getAlignment().getDataset()))
3857 showProducts.setEnabled(true);
3862 showProducts.setEnabled(false);
3867 * search selection for sequence xRef products and build the show products
3872 * @return true if showProducts menu should be enabled.
3874 public boolean canShowProducts(SequenceI[] selection,
3875 boolean isRegionSelection, Alignment dataset)
3877 boolean showp = false;
3880 showProducts.removeAll();
3881 final boolean dna = viewport.getAlignment().isNucleotide();
3882 final Alignment ds = dataset;
3883 String[] ptypes = (selection == null || selection.length == 0) ? null
3884 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
3886 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
3887 // selection, dataset, true);
3888 final SequenceI[] sel = selection;
3889 for (int t = 0; ptypes != null && t < ptypes.length; t++)
3892 final boolean isRegSel = isRegionSelection;
3893 final AlignFrame af = this;
3894 final String source = ptypes[t];
3895 JMenuItem xtype = new JMenuItem(ptypes[t]);
3896 xtype.addActionListener(new ActionListener()
3899 public void actionPerformed(ActionEvent e)
3901 // TODO: new thread for this call with vis-delay
3902 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
3903 isRegSel, dna, source);
3907 showProducts.add(xtype);
3909 showProducts.setVisible(showp);
3910 showProducts.setEnabled(showp);
3911 } catch (Exception e)
3913 jalview.bin.Cache.log
3915 "canTranslate threw an exception - please report to help@jalview.org",
3922 protected void showProductsFor(SequenceI[] sel, Alignment ds,
3923 boolean isRegSel, boolean dna, String source)
3925 final boolean fisRegSel = isRegSel;
3926 final boolean fdna = dna;
3927 final String fsrc = source;
3928 final AlignFrame ths = this;
3929 final SequenceI[] fsel = sel;
3930 Runnable foo = new Runnable()
3935 final long sttime = System.currentTimeMillis();
3936 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
3939 Alignment ds = ths.getViewport().alignment.getDataset(); // update
3943 Alignment prods = CrossRef
3944 .findXrefSequences(fsel, fdna, fsrc, ds);
3947 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3948 for (int s = 0; s < sprods.length; s++)
3950 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3951 if (ds.getSequences() == null
3952 || !ds.getSequences().contains(
3953 sprods[s].getDatasetSequence()))
3954 ds.addSequence(sprods[s].getDatasetSequence());
3955 sprods[s].updatePDBIds();
3957 Alignment al = new Alignment(sprods);
3958 AlignedCodonFrame[] cf = prods.getCodonFrames();
3960 for (int s = 0; cf != null && s < cf.length; s++)
3962 al.addCodonFrame(cf[s]);
3965 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
3967 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
3968 + " for " + ((fisRegSel) ? "selected region of " : "")
3970 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3975 System.err.println("No Sequences generated for xRef type "
3978 } catch (Exception e)
3980 jalview.bin.Cache.log.error(
3981 "Exception when finding crossreferences", e);
3982 } catch (OutOfMemoryError e)
3984 new OOMWarning("whilst fetching crossreferences", e);
3987 jalview.bin.Cache.log.error("Error when finding crossreferences",
3990 ths.setProgressBar("Finished searching for sequences from " + fsrc,
3995 Thread frunner = new Thread(foo);
3999 public boolean canShowTranslationProducts(SequenceI[] selection,
4000 AlignmentI alignment)
4005 return (jalview.analysis.Dna.canTranslate(selection, viewport
4006 .getViewAsVisibleContigs(true)));
4007 } catch (Exception e)
4009 jalview.bin.Cache.log
4011 "canTranslate threw an exception - please report to help@jalview.org",
4017 public void showProducts_actionPerformed(ActionEvent e)
4019 // /////////////////////////////
4020 // Collect Data to be translated/transferred
4022 SequenceI[] selection = viewport.getSequenceSelection();
4023 AlignmentI al = null;
4026 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4027 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4028 viewport.getAlignment().getDataset());
4029 } catch (Exception ex)
4032 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4039 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4040 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4044 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4045 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4046 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4050 public void showTranslation_actionPerformed(ActionEvent e)
4052 // /////////////////////////////
4053 // Collect Data to be translated/transferred
4055 SequenceI[] selection = viewport.getSequenceSelection();
4056 String[] seqstring = viewport.getViewAsString(true);
4057 AlignmentI al = null;
4060 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4061 viewport.getViewAsVisibleContigs(true), viewport
4062 .getGapCharacter(), viewport.alignment
4063 .getAlignmentAnnotation(), viewport.alignment
4064 .getWidth(), viewport.getAlignment().getDataset());
4065 } catch (Exception ex)
4068 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4075 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4076 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4080 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4081 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4082 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4087 * Try to load a features file onto the alignment.
4090 * contents or path to retrieve file
4092 * access mode of file (see jalview.io.AlignFile)
4093 * @return true if features file was parsed corectly.
4095 public boolean parseFeaturesFile(String file, String type)
4097 boolean featuresFile = false;
4100 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
4101 .getDataset(), alignPanel.seqPanel.seqCanvas
4102 .getFeatureRenderer().featureColours, false);
4103 } catch (Exception ex)
4105 ex.printStackTrace();
4110 viewport.showSequenceFeatures = true;
4111 showSeqFeatures.setSelected(true);
4112 if (alignPanel.seqPanel.seqCanvas.fr != null)
4114 // update the min/max ranges where necessary
4115 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4117 if (featureSettings!=null)
4119 featureSettings.setTableData();
4121 alignPanel.paintAlignment(true);
4124 return featuresFile;
4127 public void dragEnter(DropTargetDragEvent evt)
4131 public void dragExit(DropTargetEvent evt)
4135 public void dragOver(DropTargetDragEvent evt)
4139 public void dropActionChanged(DropTargetDragEvent evt)
4143 public void drop(DropTargetDropEvent evt)
4145 Transferable t = evt.getTransferable();
4146 java.util.List files = null;
4150 DataFlavor uriListFlavor = new DataFlavor(
4151 "text/uri-list;class=java.lang.String");
4152 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4154 // Works on Windows and MacOSX
4155 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4156 files = (java.util.List) t
4157 .getTransferData(DataFlavor.javaFileListFlavor);
4159 else if (t.isDataFlavorSupported(uriListFlavor))
4161 // This is used by Unix drag system
4162 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4163 String data = (String) t.getTransferData(uriListFlavor);
4164 files = new java.util.ArrayList(1);
4165 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4166 data, "\r\n"); st.hasMoreTokens();)
4168 String s = st.nextToken();
4169 if (s.startsWith("#"))
4171 // the line is a comment (as per the RFC 2483)
4175 java.net.URI uri = new java.net.URI(s);
4176 // check to see if we can handle this kind of URI
4177 if (uri.getScheme().toLowerCase().startsWith("http"))
4179 files.add(uri.toString());
4183 // otherwise preserve old behaviour: catch all for file objects
4184 java.io.File file = new java.io.File(uri);
4185 files.add(file.toString());
4189 } catch (Exception e)
4191 e.printStackTrace();
4198 for (int i = 0; i < files.size(); i++)
4200 loadJalviewDataFile(files.get(i).toString());
4202 } catch (Exception ex)
4204 ex.printStackTrace();
4210 * Attempt to load a "dropped" file or URL string: First by testing whether
4211 * it's and Annotation file, then a JNet file, and finally a features file. If
4212 * all are false then the user may have dropped an alignment file onto this
4216 * either a filename or a URL string.
4218 public void loadJalviewDataFile(String file)
4222 String protocol = jalview.io.FormatAdapter.FILE;
4223 String f = file.toLowerCase();
4224 if (f.indexOf("http:") == 0 || f.indexOf("https:") == 0
4225 || f.indexOf("file:") == 0)
4227 protocol = jalview.io.FormatAdapter.URL;
4230 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
4231 viewport.alignment, file, protocol);
4235 // try to see if its a JNet 'concise' style annotation file *before* we
4236 // try to parse it as a features file
4237 String format = new IdentifyFile().Identify(file, protocol);
4238 if (format.equalsIgnoreCase("JnetFile"))
4240 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
4242 new JnetAnnotationMaker().add_annotation(predictions, viewport
4243 .getAlignment(), 0, false);
4244 isAnnotation = true;
4248 // try to parse it as a features file
4249 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4250 // if it wasn't a features file then we just treat it as a general
4251 // alignment file to load into the current view.
4254 new FileLoader().LoadFile(viewport, file, protocol, format);
4258 alignPanel.paintAlignment(true);
4265 alignPanel.adjustAnnotationHeight();
4266 viewport.updateSequenceIdColours();
4267 buildSortByAnnotationScoresMenu();
4268 alignPanel.paintAlignment(true);
4270 } catch (Exception ex)
4272 ex.printStackTrace();
4276 public void tabSelectionChanged(int index)
4280 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4281 viewport = alignPanel.av;
4282 setMenusFromViewport(viewport);
4286 public void tabbedPane_mousePressed(MouseEvent e)
4288 if (SwingUtilities.isRightMouseButton(e))
4290 String reply = JOptionPane.showInternalInputDialog(this,
4291 "Enter View Name", "Edit View Name",
4292 JOptionPane.QUESTION_MESSAGE);
4296 viewport.viewName = reply;
4297 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4302 public AlignViewport getCurrentView()
4308 * Open the dialog for regex description parsing.
4310 protected void extractScores_actionPerformed(ActionEvent e)
4312 ParseProperties pp = new jalview.analysis.ParseProperties(
4313 viewport.alignment);
4314 // TODO: verify regex and introduce GUI dialog for version 2.5
4315 // if (pp.getScoresFromDescription("col", "score column ",
4316 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4318 if (pp.getScoresFromDescription("description column",
4319 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4321 buildSortByAnnotationScoresMenu();
4329 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4332 protected void showDbRefs_actionPerformed(ActionEvent e)
4334 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
4340 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4343 protected void showNpFeats_actionPerformed(ActionEvent e)
4345 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
4349 * find the viewport amongst the tabs in this alignment frame and close that
4354 public boolean closeView(AlignViewport av)
4358 this.closeMenuItem_actionPerformed(false);
4361 Component[] comp = tabbedPane.getComponents();
4362 for (int i = 0; comp != null && i < comp.length; i++)
4364 if (comp[i] instanceof AlignmentPanel)
4366 if (((AlignmentPanel) comp[i]).av == av)
4369 closeView((AlignmentPanel) comp[i]);
4377 protected void build_fetchdbmenu(JMenu webService)
4379 // Temporary hack - DBRef Fetcher always top level ws entry.
4380 // TODO We probably want to store a sequence database checklist in
4381 // preferences and have checkboxes.. rather than individual sources selected
4383 JMenu rfetch = new JMenu("Fetch DB References");
4385 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
4386 webService.add(rfetch);
4388 JMenuItem fetchr = new JMenuItem("Standard Databases");
4390 .setToolTipText("Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources");
4391 fetchr.addActionListener(new ActionListener()
4394 public void actionPerformed(ActionEvent e)
4396 new Thread(new Runnable()
4401 new jalview.ws.DBRefFetcher(alignPanel.av
4402 .getSequenceSelection(), alignPanel.alignFrame)
4403 .fetchDBRefs(false);
4411 JMenu dfetch = new JMenu();
4413 jalview.ws.SequenceFetcher sf = SequenceFetcher
4414 .getSequenceFetcherSingleton(this);
4415 String[] otherdb = sf.getOrderedSupportedSources();
4416 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4417 // jalview.util.QuickSort.sort(otherdb, otherdb);
4418 int comp = 0, mcomp = 15;
4419 String mname = null;
4420 if (otherdb != null && otherdb.length > 0)
4422 for (int i = 0; i < otherdb.length; i++)
4424 String dbname = sf.getSourceProxy(otherdb[i]).getDbName();
4427 mname = "from '" + dbname + "'";
4429 fetchr = new JMenuItem(otherdb[i]);
4430 final String[] dassource = new String[]
4432 fetchr.addActionListener(new ActionListener()
4435 public void actionPerformed(ActionEvent e)
4437 new Thread(new Runnable()
4442 new jalview.ws.DBRefFetcher(alignPanel.av
4443 .getSequenceSelection(), alignPanel.alignFrame,
4444 dassource).fetchDBRefs(false);
4450 fetchr.setToolTipText("Retrieve from " + dbname);
4452 if (comp++ == mcomp || i == (otherdb.length - 1))
4454 dfetch.setText(mname + " to '" + dbname + "'");
4456 dfetch = new JMenu();
4465 * Left justify the whole alignment.
4467 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
4469 AlignmentI al = viewport.getAlignment();
4471 viewport.firePropertyChange("alignment", null, al);
4475 * Right justify the whole alignment.
4477 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
4479 AlignmentI al = viewport.getAlignment();
4481 viewport.firePropertyChange("alignment", null, al);
4484 public void setShowSeqFeatures(boolean b)
4486 showSeqFeatures.setSelected(true);
4487 viewport.setShowSequenceFeatures(true);
4494 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
4495 * awt.event.ActionEvent)
4497 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
4499 viewport.setShowUnconserved(showUnconservedMenuItem.getState());
4500 alignPanel.paintAlignment(true);
4507 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
4510 protected void showGroupConsensus_actionPerformed(ActionEvent e)
4512 viewport.setShowGroupConsensus(showGroupConsensus.getState());
4513 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4521 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
4522 * .event.ActionEvent)
4524 protected void showGroupConservation_actionPerformed(ActionEvent e)
4526 viewport.setShowGroupConservation(showGroupConservation.getState());
4527 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4531 * @see jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt.event.ActionEvent)
4533 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
4535 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
4536 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4540 * @see jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt.event.ActionEvent)
4542 protected void showSequenceLogo_actionPerformed(ActionEvent e)
4544 viewport.setShowSequenceLogo(showSequenceLogo.getState());
4545 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4547 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
4549 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4556 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
4557 * .event.ActionEvent)
4559 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
4561 if (viewport.getSelectionGroup() != null)
4563 SequenceGroup[] gps = jalview.analysis.Grouping.makeGroupsFrom(
4564 viewport.getSequenceSelection(), viewport.getAlignmentView(
4565 true).getSequenceStrings(viewport.getGapCharacter()),
4566 viewport.alignment.getGroups());
4567 viewport.alignment.deleteAllGroups();
4568 viewport.sequenceColours = null;
4569 viewport.setSelectionGroup(null);
4570 // set view properties for each group
4571 for (int g = 0; g < gps.length; g++)
4573 gps[g].setShowunconserved(viewport.getShowUnconserved());
4574 gps[g].setIncludeAllConsSymbols(viewport.isIncludeAllConsensusSymbols());
4575 viewport.alignment.addGroup(gps[g]);
4576 Color col = new Color((int) (Math.random() * 255), (int) (Math
4577 .random() * 255), (int) (Math.random() * 255));
4578 col = col.brighter();
4579 for (Enumeration sq = gps[g].getSequences(null).elements(); sq
4580 .hasMoreElements(); viewport.setSequenceColour(
4581 (SequenceI) sq.nextElement(), col))
4584 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
4585 alignPanel.updateAnnotation();
4586 alignPanel.paintAlignment(true);
4591 class PrintThread extends Thread
4595 public PrintThread(AlignmentPanel ap)
4600 static PageFormat pf;
4604 PrinterJob printJob = PrinterJob.getPrinterJob();
4608 printJob.setPrintable(ap, pf);
4612 printJob.setPrintable(ap);
4615 if (printJob.printDialog())
4620 } catch (Exception PrintException)
4622 PrintException.printStackTrace();