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);
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 setColourSelected(ColourSchemeProperty.getColourName(av
659 .getGlobalColourScheme()));
661 showSeqFeatures.setSelected(av.showSequenceFeatures);
662 hiddenMarkers.setState(av.showHiddenMarkers);
663 applyToAllGroups.setState(av.colourAppliesToAllGroups);
664 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
665 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
667 setShowProductsEnabled();
672 Hashtable progressBars, progressBarHandlers;
677 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
679 public void setProgressBar(String message, long id)
681 if (progressBars == null)
683 progressBars = new Hashtable();
684 progressBarHandlers = new Hashtable();
687 JPanel progressPanel;
688 Long lId=new Long(id);
689 GridLayout layout = (GridLayout) statusPanel.getLayout();
690 if (progressBars.get(lId) != null)
692 progressPanel = (JPanel) progressBars.get(new Long(id));
693 statusPanel.remove(progressPanel);
694 progressBars.remove(lId);
695 progressPanel = null;
698 statusBar.setText(message);
700 if (progressBarHandlers.contains(lId))
702 progressBarHandlers.remove(lId);
704 layout.setRows(layout.getRows() - 1);
708 progressPanel = new JPanel(new BorderLayout(10, 5));
710 JProgressBar progressBar = new JProgressBar();
711 progressBar.setIndeterminate(true);
713 progressPanel.add(new JLabel(message), BorderLayout.WEST);
714 progressPanel.add(progressBar, BorderLayout.CENTER);
716 layout.setRows(layout.getRows() + 1);
717 statusPanel.add(progressPanel);
719 progressBars.put(lId, progressPanel);
722 setMenusForViewport();
726 public void registerHandler(final long id,
727 final IProgressIndicatorHandler handler)
729 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
732 "call setProgressBar before registering the progress bar's handler.");
734 progressBarHandlers.put(new Long(id), handler);
735 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
736 if (handler.canCancel())
738 JButton cancel = new JButton("Cancel");
739 final IProgressIndicator us = this;
740 cancel.addActionListener(new ActionListener()
743 public void actionPerformed(ActionEvent e)
745 handler.cancelActivity(id);
746 us.setProgressBar("Cancelled "
747 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
750 progressPanel.add(cancel, BorderLayout.EAST);
756 * @return true if any progress bars are still active
758 public boolean operationInProgress()
760 if (progressBars != null && progressBars.size() > 0)
768 * Added so Castor Mapping file can obtain Jalview Version
770 public String getVersion()
772 return jalview.bin.Cache.getProperty("VERSION");
775 public FeatureRenderer getFeatureRenderer()
777 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
780 public void fetchSequence_actionPerformed(ActionEvent e)
782 new SequenceFetcher(this);
785 public void addFromFile_actionPerformed(ActionEvent e)
787 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
790 public void reload_actionPerformed(ActionEvent e)
792 if (fileName != null)
794 if (currentFileFormat.equals("Jalview"))
796 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
797 for (int i = 0; i < frames.length; i++)
799 if (frames[i] instanceof AlignFrame && frames[i] != this
800 && ((AlignFrame) frames[i]).fileName.equals(fileName))
804 frames[i].setSelected(true);
805 Desktop.instance.closeAssociatedWindows();
806 } catch (java.beans.PropertyVetoException ex)
812 Desktop.instance.closeAssociatedWindows();
814 FileLoader loader = new FileLoader();
815 String protocol = fileName.startsWith("http:") ? "URL" : "File";
816 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
820 Rectangle bounds = this.getBounds();
822 FileLoader loader = new FileLoader();
823 String protocol = fileName.startsWith("http:") ? "URL" : "File";
824 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
825 protocol, currentFileFormat);
827 newframe.setBounds(bounds);
829 this.closeMenuItem_actionPerformed(true);
834 public void addFromText_actionPerformed(ActionEvent e)
836 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
839 public void addFromURL_actionPerformed(ActionEvent e)
841 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
844 public void save_actionPerformed(ActionEvent e)
847 || (currentFileFormat == null || !jalview.io.FormatAdapter
848 .isValidIOFormat(currentFileFormat, true))
849 || fileName.startsWith("http"))
851 saveAs_actionPerformed(null);
855 saveAlignment(fileName, currentFileFormat);
865 public void saveAs_actionPerformed(ActionEvent e)
867 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
868 .getProperty("LAST_DIRECTORY"),
869 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
870 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
871 currentFileFormat, false);
873 chooser.setFileView(new JalviewFileView());
874 chooser.setDialogTitle("Save Alignment to file");
875 chooser.setToolTipText("Save");
877 int value = chooser.showSaveDialog(this);
879 if (value == JalviewFileChooser.APPROVE_OPTION)
881 currentFileFormat = chooser.getSelectedFormat();
882 if (currentFileFormat == null)
884 JOptionPane.showInternalMessageDialog(Desktop.desktop,
885 "You must select a file format before saving!",
886 "File format not specified", JOptionPane.WARNING_MESSAGE);
887 value = chooser.showSaveDialog(this);
891 fileName = chooser.getSelectedFile().getPath();
893 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
896 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
897 if (currentFileFormat.indexOf(" ") > -1)
899 currentFileFormat = currentFileFormat.substring(0,
900 currentFileFormat.indexOf(" "));
902 saveAlignment(fileName, currentFileFormat);
906 public boolean saveAlignment(String file, String format)
908 boolean success = true;
910 if (format.equalsIgnoreCase("Jalview"))
912 String shortName = title;
914 if (shortName.indexOf(java.io.File.separatorChar) > -1)
916 shortName = shortName.substring(shortName
917 .lastIndexOf(java.io.File.separatorChar) + 1);
920 success = new Jalview2XML().SaveAlignment(this, file, shortName);
922 statusBar.setText("Successfully saved to file: " + fileName + " in "
923 + format + " format.");
928 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
930 warningMessage("Cannot save file " + fileName + " using format "
931 + format, "Alignment output format not supported");
932 saveAs_actionPerformed(null);
933 // JBPNote need to have a raise_gui flag here
937 String[] omitHidden = null;
939 if (viewport.hasHiddenColumns)
941 int reply = JOptionPane
942 .showInternalConfirmDialog(
944 "The Alignment contains hidden columns."
945 + "\nDo you want to save only the visible alignment?",
946 "Save / Omit Hidden Columns",
947 JOptionPane.YES_NO_OPTION,
948 JOptionPane.QUESTION_MESSAGE);
950 if (reply == JOptionPane.YES_OPTION)
952 omitHidden = viewport.getViewAsString(false);
955 FormatAdapter f = new FormatAdapter();
956 String output = f.formatSequences(format,
957 (Alignment) viewport.alignment, // class cast exceptions will
958 // occur in the distant future
959 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
969 java.io.PrintWriter out = new java.io.PrintWriter(
970 new java.io.FileWriter(file));
975 statusBar.setText("Successfully saved to file: " + fileName
976 + " in " + format + " format.");
977 } catch (Exception ex)
980 ex.printStackTrace();
987 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
988 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
994 private void warningMessage(String warning, String title)
996 if (new jalview.util.Platform().isHeadless())
998 System.err.println("Warning: " + title + "\nWarning: " + warning);
1003 JOptionPane.showInternalMessageDialog(this, warning, title,
1004 JOptionPane.WARNING_MESSAGE);
1015 protected void outputText_actionPerformed(ActionEvent e)
1017 String[] omitHidden = null;
1019 if (viewport.hasHiddenColumns)
1021 int reply = JOptionPane
1022 .showInternalConfirmDialog(
1024 "The Alignment contains hidden columns."
1025 + "\nDo you want to output only the visible alignment?",
1026 "Save / Omit Hidden Columns",
1027 JOptionPane.YES_NO_OPTION,
1028 JOptionPane.QUESTION_MESSAGE);
1030 if (reply == JOptionPane.YES_OPTION)
1032 omitHidden = viewport.getViewAsString(false);
1036 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1037 cap.setForInput(null);
1038 Desktop.addInternalFrame(cap, "Alignment output - "
1039 + e.getActionCommand(), 600, 500);
1041 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1042 viewport.alignment, omitHidden, viewport.colSel));
1051 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1053 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
1054 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
1055 .getFeatureRenderer());
1058 public void createImageMap(File file, String image)
1060 alignPanel.makePNGImageMap(file, image);
1069 public void createPNG(File f)
1071 alignPanel.makePNG(f);
1080 public void createEPS(File f)
1082 alignPanel.makeEPS(f);
1085 public void pageSetup_actionPerformed(ActionEvent e)
1087 PrinterJob printJob = PrinterJob.getPrinterJob();
1088 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1097 public void printMenuItem_actionPerformed(ActionEvent e)
1099 // Putting in a thread avoids Swing painting problems
1100 PrintThread thread = new PrintThread(alignPanel);
1104 public void exportFeatures_actionPerformed(ActionEvent e)
1106 new AnnotationExporter().exportFeatures(alignPanel);
1109 public void exportAnnotations_actionPerformed(ActionEvent e)
1111 new AnnotationExporter().exportAnnotations(alignPanel,
1112 viewport.showAnnotation ? viewport.alignment
1113 .getAlignmentAnnotation() : null, viewport.alignment
1115 ((Alignment) viewport.alignment).alignmentProperties);
1118 public void associatedData_actionPerformed(ActionEvent e)
1120 // Pick the tree file
1121 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1122 .getProperty("LAST_DIRECTORY"));
1123 chooser.setFileView(new JalviewFileView());
1124 chooser.setDialogTitle("Load Jalview Annotations or Features File");
1125 chooser.setToolTipText("Load Jalview Annotations / Features file");
1127 int value = chooser.showOpenDialog(null);
1129 if (value == JalviewFileChooser.APPROVE_OPTION)
1131 String choice = chooser.getSelectedFile().getPath();
1132 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1133 loadJalviewDataFile(choice);
1139 * Close the current view or all views in the alignment frame. If the frame
1140 * only contains one view then the alignment will be removed from memory.
1142 * @param closeAllTabs
1144 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1146 if (alignPanels != null && alignPanels.size() < 2)
1148 closeAllTabs = true;
1153 if (alignPanels != null)
1157 if (this.isClosed())
1159 // really close all the windows - otherwise wait till
1160 // setClosed(true) is called
1161 for (int i = 0; i < alignPanels.size(); i++)
1163 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1170 closeView(alignPanel);
1176 this.setClosed(true);
1178 } catch (Exception ex)
1180 ex.printStackTrace();
1185 * close alignPanel2 and shuffle tabs appropriately.
1187 * @param alignPanel2
1189 public void closeView(AlignmentPanel alignPanel2)
1191 int index = tabbedPane.getSelectedIndex();
1192 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1193 alignPanels.removeElement(alignPanel2);
1195 // if (viewport == alignPanel2.av)
1199 alignPanel2.closePanel();
1202 tabbedPane.removeTabAt(closedindex);
1203 tabbedPane.validate();
1205 if (index > closedindex || index == tabbedPane.getTabCount())
1207 // modify currently selected tab index if necessary.
1211 this.tabSelectionChanged(index);
1217 void updateEditMenuBar()
1220 if (viewport.historyList.size() > 0)
1222 undoMenuItem.setEnabled(true);
1223 CommandI command = (CommandI) viewport.historyList.peek();
1224 undoMenuItem.setText("Undo " + command.getDescription());
1228 undoMenuItem.setEnabled(false);
1229 undoMenuItem.setText("Undo");
1232 if (viewport.redoList.size() > 0)
1234 redoMenuItem.setEnabled(true);
1236 CommandI command = (CommandI) viewport.redoList.peek();
1237 redoMenuItem.setText("Redo " + command.getDescription());
1241 redoMenuItem.setEnabled(false);
1242 redoMenuItem.setText("Redo");
1246 public void addHistoryItem(CommandI command)
1248 if (command.getSize() > 0)
1250 viewport.historyList.push(command);
1251 viewport.redoList.clear();
1252 updateEditMenuBar();
1253 viewport.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1259 * @return alignment objects for all views
1261 AlignmentI[] getViewAlignments()
1263 if (alignPanels != null)
1265 Enumeration e = alignPanels.elements();
1266 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1267 for (int i = 0; e.hasMoreElements(); i++)
1269 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1273 if (viewport != null)
1275 return new AlignmentI[]
1276 { viewport.alignment };
1287 protected void undoMenuItem_actionPerformed(ActionEvent e)
1289 if (viewport.historyList.empty())
1291 CommandI command = (CommandI) viewport.historyList.pop();
1292 viewport.redoList.push(command);
1293 command.undoCommand(getViewAlignments());
1295 AlignViewport originalSource = getOriginatingSource(command);
1296 updateEditMenuBar();
1298 if (originalSource != null)
1300 originalSource.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1301 originalSource.firePropertyChange("alignment", null,
1302 originalSource.alignment.getSequences());
1312 protected void redoMenuItem_actionPerformed(ActionEvent e)
1314 if (viewport.redoList.size() < 1)
1319 CommandI command = (CommandI) viewport.redoList.pop();
1320 viewport.historyList.push(command);
1321 command.doCommand(getViewAlignments());
1323 AlignViewport originalSource = getOriginatingSource(command);
1324 updateEditMenuBar();
1326 if (originalSource != null)
1328 originalSource.hasHiddenColumns = (viewport.colSel!=null && viewport.colSel.getHiddenColumns() != null && viewport.colSel.getHiddenColumns().size()>0);
1329 originalSource.firePropertyChange("alignment", null,
1330 originalSource.alignment.getSequences());
1334 AlignViewport getOriginatingSource(CommandI command)
1336 AlignViewport originalSource = null;
1337 // For sequence removal and addition, we need to fire
1338 // the property change event FROM the viewport where the
1339 // original alignment was altered
1340 AlignmentI al = null;
1341 if (command instanceof EditCommand)
1343 EditCommand editCommand = (EditCommand) command;
1344 al = editCommand.getAlignment();
1345 Vector comps = (Vector) PaintRefresher.components.get(viewport
1346 .getSequenceSetId());
1348 for (int i = 0; i < comps.size(); i++)
1350 if (comps.elementAt(i) instanceof AlignmentPanel)
1352 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1354 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1361 if (originalSource == null)
1363 // The original view is closed, we must validate
1364 // the current view against the closed view first
1367 PaintRefresher.validateSequences(al, viewport.alignment);
1370 originalSource = viewport;
1373 return originalSource;
1382 public void moveSelectedSequences(boolean up)
1384 SequenceGroup sg = viewport.getSelectionGroup();
1393 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1395 SequenceI seq = viewport.alignment.getSequenceAt(i);
1397 if (!sg.getSequences(null).contains(seq))
1402 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1404 if (sg.getSequences(null).contains(temp))
1409 viewport.alignment.getSequences().setElementAt(temp, i);
1410 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1415 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1417 SequenceI seq = viewport.alignment.getSequenceAt(i);
1419 if (!sg.getSequences(null).contains(seq))
1424 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1426 if (sg.getSequences(null).contains(temp))
1431 viewport.alignment.getSequences().setElementAt(temp, i);
1432 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1436 alignPanel.paintAlignment(true);
1439 synchronized void slideSequences(boolean right, int size)
1441 Vector sg = new Vector();
1442 if (viewport.cursorMode)
1444 sg.addElement(viewport.alignment
1445 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1447 else if (viewport.getSelectionGroup() != null
1448 && viewport.getSelectionGroup().getSize() != viewport.alignment
1451 sg = viewport.getSelectionGroup().getSequences(
1452 viewport.hiddenRepSequences);
1460 Vector invertGroup = new Vector();
1462 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1464 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1465 invertGroup.add(viewport.alignment.getSequenceAt(i));
1468 SequenceI[] seqs1 = new SequenceI[sg.size()];
1469 for (int i = 0; i < sg.size(); i++)
1470 seqs1[i] = (SequenceI) sg.elementAt(i);
1472 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1473 for (int i = 0; i < invertGroup.size(); i++)
1474 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1476 SlideSequencesCommand ssc;
1478 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1479 size, viewport.getGapCharacter());
1481 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1482 size, viewport.getGapCharacter());
1484 int groupAdjustment = 0;
1485 if (ssc.getGapsInsertedBegin() && right)
1487 if (viewport.cursorMode)
1488 alignPanel.seqPanel.moveCursor(size, 0);
1490 groupAdjustment = size;
1492 else if (!ssc.getGapsInsertedBegin() && !right)
1494 if (viewport.cursorMode)
1495 alignPanel.seqPanel.moveCursor(-size, 0);
1497 groupAdjustment = -size;
1500 if (groupAdjustment != 0)
1502 viewport.getSelectionGroup().setStartRes(
1503 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1504 viewport.getSelectionGroup().setEndRes(
1505 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1508 boolean appendHistoryItem = false;
1509 if (viewport.historyList != null && viewport.historyList.size() > 0
1510 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1512 appendHistoryItem = ssc
1513 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1517 if (!appendHistoryItem)
1518 addHistoryItem(ssc);
1529 protected void copy_actionPerformed(ActionEvent e)
1532 if (viewport.getSelectionGroup() == null)
1536 // TODO: preserve the ordering of displayed alignment annotation in any
1537 // internal paste (particularly sequence associated annotation)
1538 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1539 String[] omitHidden = null;
1541 if (viewport.hasHiddenColumns)
1543 omitHidden = viewport.getViewAsString(true);
1546 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1549 StringSelection ss = new StringSelection(output);
1553 jalview.gui.Desktop.internalCopy = true;
1554 // Its really worth setting the clipboard contents
1555 // to empty before setting the large StringSelection!!
1556 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1557 new StringSelection(""), null);
1559 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1561 } catch (OutOfMemoryError er)
1563 new OOMWarning("copying region", er);
1567 Vector hiddenColumns = null;
1568 if (viewport.hasHiddenColumns)
1570 hiddenColumns = new Vector();
1571 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1572 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1575 int[] region = (int[]) viewport.getColumnSelection()
1576 .getHiddenColumns().elementAt(i);
1578 hiddenColumns.addElement(new int[]
1579 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1583 Desktop.jalviewClipboard = new Object[]
1584 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1585 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1594 protected void pasteNew_actionPerformed(ActionEvent e)
1605 protected void pasteThis_actionPerformed(ActionEvent e)
1611 * Paste contents of Jalview clipboard
1613 * @param newAlignment
1614 * true to paste to a new alignment, otherwise add to this.
1616 void paste(boolean newAlignment)
1618 boolean externalPaste = true;
1621 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1622 Transferable contents = c.getContents(this);
1624 if (contents == null)
1632 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1633 if (str.length() < 1)
1638 format = new IdentifyFile().Identify(str, "Paste");
1640 } catch (OutOfMemoryError er)
1642 new OOMWarning("Out of memory pasting sequences!!", er);
1646 SequenceI[] sequences;
1647 boolean annotationAdded = false;
1648 AlignmentI alignment = null;
1650 if (Desktop.jalviewClipboard != null)
1652 // The clipboard was filled from within Jalview, we must use the
1654 // And dataset from the copied alignment
1655 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1656 // be doubly sure that we create *new* sequence objects.
1657 sequences = new SequenceI[newseq.length];
1658 for (int i = 0; i < newseq.length; i++)
1660 sequences[i] = new Sequence(newseq[i]);
1662 alignment = new Alignment(sequences);
1663 externalPaste = false;
1667 // parse the clipboard as an alignment.
1668 alignment = new FormatAdapter().readFile(str, "Paste", format);
1669 sequences = alignment.getSequencesArray();
1677 if (Desktop.jalviewClipboard != null)
1679 // dataset is inherited
1680 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1684 // new dataset is constructed
1685 alignment.setDataset(null);
1687 alwidth = alignment.getWidth() + 1;
1691 AlignmentI pastedal = alignment; // preserve pasted alignment object
1692 // Add pasted sequences and dataset into existing alignment.
1693 alignment = viewport.getAlignment();
1694 alwidth = alignment.getWidth() + 1;
1695 // decide if we need to import sequences from an existing dataset
1696 boolean importDs = Desktop.jalviewClipboard != null
1697 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1698 // importDs==true instructs us to copy over new dataset sequences from
1699 // an existing alignment
1700 Vector newDs = (importDs) ? new Vector() : null; // used to create
1701 // minimum dataset set
1703 for (int i = 0; i < sequences.length; i++)
1707 newDs.addElement(null);
1709 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1711 if (importDs && ds != null)
1713 if (!newDs.contains(ds))
1715 newDs.setElementAt(ds, i);
1716 ds = new Sequence(ds);
1717 // update with new dataset sequence
1718 sequences[i].setDatasetSequence(ds);
1722 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1727 // copy and derive new dataset sequence
1728 sequences[i] = sequences[i].deriveSequence();
1729 alignment.getDataset().addSequence(
1730 sequences[i].getDatasetSequence());
1731 // TODO: avoid creation of duplicate dataset sequences with a
1732 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1734 alignment.addSequence(sequences[i]); // merges dataset
1738 newDs.clear(); // tidy up
1740 if (pastedal.getAlignmentAnnotation() != null)
1742 // Add any annotation attached to alignment.
1743 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1744 for (int i = 0; i < alann.length; i++)
1746 annotationAdded = true;
1747 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1749 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1750 newann.padAnnotation(alwidth);
1751 alignment.addAnnotation(newann);
1761 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1762 sequences, 0, alignment.getWidth(), alignment));
1764 // Add any annotations attached to sequences
1765 for (int i = 0; i < sequences.length; i++)
1767 if (sequences[i].getAnnotation() != null)
1769 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1771 annotationAdded = true;
1772 sequences[i].getAnnotation()[a].adjustForAlignment();
1773 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1774 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1779 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1786 // propagate alignment changed.
1787 viewport.setEndSeq(alignment.getHeight());
1788 if (annotationAdded)
1790 // Duplicate sequence annotation in all views.
1791 AlignmentI[] alview = this.getViewAlignments();
1792 for (int i = 0; i < sequences.length; i++)
1794 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1797 for (int avnum = 0; avnum < alview.length; avnum++)
1799 if (alview[avnum] != alignment)
1801 // duplicate in a view other than the one with input focus
1802 int avwidth = alview[avnum].getWidth() + 1;
1803 // this relies on sann being preserved after we
1804 // modify the sequence's annotation array for each duplication
1805 for (int a = 0; a < sann.length; a++)
1807 AlignmentAnnotation newann = new AlignmentAnnotation(
1809 sequences[i].addAlignmentAnnotation(newann);
1810 newann.padAnnotation(avwidth);
1811 alview[avnum].addAnnotation(newann); // annotation was
1812 // duplicated earlier
1813 alview[avnum].setAnnotationIndex(newann, a);
1818 buildSortByAnnotationScoresMenu();
1820 viewport.firePropertyChange("alignment", null, alignment
1826 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1828 String newtitle = new String("Copied sequences");
1830 if (Desktop.jalviewClipboard != null
1831 && Desktop.jalviewClipboard[2] != null)
1833 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1834 for (int i = 0; i < hc.size(); i++)
1836 int[] region = (int[]) hc.elementAt(i);
1837 af.viewport.hideColumns(region[0], region[1]);
1841 // >>>This is a fix for the moment, until a better solution is
1843 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1845 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1847 // TODO: maintain provenance of an alignment, rather than just make the
1848 // title a concatenation of operations.
1851 if (title.startsWith("Copied sequences"))
1857 newtitle = newtitle.concat("- from " + title);
1862 newtitle = new String("Pasted sequences");
1865 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1870 } catch (Exception ex)
1872 ex.printStackTrace();
1873 System.out.println("Exception whilst pasting: " + ex);
1874 // could be anything being pasted in here
1885 protected void cut_actionPerformed(ActionEvent e)
1887 copy_actionPerformed(null);
1888 delete_actionPerformed(null);
1897 protected void delete_actionPerformed(ActionEvent evt)
1900 SequenceGroup sg = viewport.getSelectionGroup();
1906 Vector seqs = new Vector();
1908 for (int i = 0; i < sg.getSize(); i++)
1910 seq = sg.getSequenceAt(i);
1911 seqs.addElement(seq);
1914 // If the cut affects all sequences, remove highlighted columns
1915 if (sg.getSize() == viewport.alignment.getHeight())
1917 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1918 sg.getEndRes() + 1);
1921 SequenceI[] cut = new SequenceI[seqs.size()];
1922 for (int i = 0; i < seqs.size(); i++)
1924 cut[i] = (SequenceI) seqs.elementAt(i);
1928 * //ADD HISTORY ITEM
1930 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1931 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1932 viewport.alignment));
1934 viewport.setSelectionGroup(null);
1935 viewport.sendSelection();
1936 viewport.alignment.deleteGroup(sg);
1938 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1940 if (viewport.getAlignment().getHeight() < 1)
1944 this.setClosed(true);
1945 } catch (Exception ex)
1957 protected void deleteGroups_actionPerformed(ActionEvent e)
1959 viewport.alignment.deleteAllGroups();
1960 viewport.sequenceColours = null;
1961 viewport.setSelectionGroup(null);
1962 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1963 alignPanel.updateAnnotation();
1964 alignPanel.paintAlignment(true);
1973 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1975 SequenceGroup sg = new SequenceGroup();
1977 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1979 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1982 sg.setEndRes(viewport.alignment.getWidth() - 1);
1983 viewport.setSelectionGroup(sg);
1984 viewport.sendSelection();
1985 alignPanel.paintAlignment(true);
1986 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1995 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1997 if (viewport.cursorMode)
1999 alignPanel.seqPanel.keyboardNo1 = null;
2000 alignPanel.seqPanel.keyboardNo2 = null;
2002 viewport.setSelectionGroup(null);
2003 viewport.getColumnSelection().clear();
2004 viewport.setSelectionGroup(null);
2005 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
2006 alignPanel.idPanel.idCanvas.searchResults = null;
2007 alignPanel.paintAlignment(true);
2008 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2017 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2019 SequenceGroup sg = viewport.getSelectionGroup();
2023 selectAllSequenceMenuItem_actionPerformed(null);
2028 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2030 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2033 alignPanel.paintAlignment(true);
2034 viewport.sendSelection();
2035 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2038 public void invertColSel_actionPerformed(ActionEvent e)
2040 viewport.invertColumnSelection();
2041 alignPanel.paintAlignment(true);
2050 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2052 trimAlignment(true);
2061 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2063 trimAlignment(false);
2066 void trimAlignment(boolean trimLeft)
2068 ColumnSelection colSel = viewport.getColumnSelection();
2071 if (colSel.size() > 0)
2075 column = colSel.getMin();
2079 column = colSel.getMax();
2083 if (viewport.getSelectionGroup() != null)
2085 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2086 viewport.hiddenRepSequences);
2090 seqs = viewport.alignment.getSequencesArray();
2093 TrimRegionCommand trimRegion;
2096 trimRegion = new TrimRegionCommand("Remove Left",
2097 TrimRegionCommand.TRIM_LEFT, seqs, column,
2098 viewport.alignment, viewport.colSel,
2099 viewport.selectionGroup);
2100 viewport.setStartRes(0);
2104 trimRegion = new TrimRegionCommand("Remove Right",
2105 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2106 viewport.alignment, viewport.colSel,
2107 viewport.selectionGroup);
2110 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
2112 addHistoryItem(trimRegion);
2114 Vector groups = viewport.alignment.getGroups();
2116 for (int i = 0; i < groups.size(); i++)
2118 SequenceGroup sg = (SequenceGroup) groups.get(i);
2120 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2121 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2123 viewport.alignment.deleteGroup(sg);
2127 viewport.firePropertyChange("alignment", null, viewport
2128 .getAlignment().getSequences());
2138 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2140 int start = 0, end = viewport.alignment.getWidth() - 1;
2143 if (viewport.getSelectionGroup() != null)
2145 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2146 viewport.hiddenRepSequences);
2147 start = viewport.getSelectionGroup().getStartRes();
2148 end = viewport.getSelectionGroup().getEndRes();
2152 seqs = viewport.alignment.getSequencesArray();
2155 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2156 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
2158 addHistoryItem(removeGapCols);
2160 statusBar.setText("Removed " + removeGapCols.getSize()
2161 + " empty columns.");
2163 // This is to maintain viewport position on first residue
2164 // of first sequence
2165 SequenceI seq = viewport.alignment.getSequenceAt(0);
2166 int startRes = seq.findPosition(viewport.startRes);
2167 // ShiftList shifts;
2168 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2169 // edit.alColumnChanges=shifts.getInverse();
2170 // if (viewport.hasHiddenColumns)
2171 // viewport.getColumnSelection().compensateForEdits(shifts);
2172 viewport.setStartRes(seq.findIndex(startRes) - 1);
2173 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2184 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2186 int start = 0, end = viewport.alignment.getWidth() - 1;
2189 if (viewport.getSelectionGroup() != null)
2191 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2192 viewport.hiddenRepSequences);
2193 start = viewport.getSelectionGroup().getStartRes();
2194 end = viewport.getSelectionGroup().getEndRes();
2198 seqs = viewport.alignment.getSequencesArray();
2201 // This is to maintain viewport position on first residue
2202 // of first sequence
2203 SequenceI seq = viewport.alignment.getSequenceAt(0);
2204 int startRes = seq.findPosition(viewport.startRes);
2206 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2207 viewport.alignment));
2209 viewport.setStartRes(seq.findIndex(startRes) - 1);
2211 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2222 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2224 viewport.padGaps = padGapsMenuitem.isSelected();
2225 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2231 // if (justifySeqs>0)
2233 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2245 public void findMenuItem_actionPerformed(ActionEvent e)
2250 public void newView_actionPerformed(ActionEvent e)
2252 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2255 newap.av.gatherViewsHere = false;
2257 if (viewport.viewName == null)
2259 viewport.viewName = "Original";
2262 newap.av.historyList = viewport.historyList;
2263 newap.av.redoList = viewport.redoList;
2265 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2266 String newViewName = "View " + index;
2268 Vector comps = (Vector) PaintRefresher.components.get(viewport
2269 .getSequenceSetId());
2270 Vector existingNames = new Vector();
2271 for (int i = 0; i < comps.size(); i++)
2273 if (comps.elementAt(i) instanceof AlignmentPanel)
2275 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2276 if (!existingNames.contains(ap.av.viewName))
2278 existingNames.addElement(ap.av.viewName);
2283 while (existingNames.contains(newViewName))
2285 newViewName = "View " + (++index);
2288 newap.av.viewName = newViewName;
2290 addAlignmentPanel(newap, true);
2292 if (alignPanels.size() == 2)
2294 viewport.gatherViewsHere = true;
2296 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2299 public void expandViews_actionPerformed(ActionEvent e)
2301 Desktop.instance.explodeViews(this);
2304 public void gatherViews_actionPerformed(ActionEvent e)
2306 Desktop.instance.gatherViews(this);
2315 public void font_actionPerformed(ActionEvent e)
2317 new FontChooser(alignPanel);
2326 protected void seqLimit_actionPerformed(ActionEvent e)
2328 viewport.setShowJVSuffix(seqLimits.isSelected());
2330 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2331 .calculateIdWidth());
2332 alignPanel.paintAlignment(true);
2335 public void idRightAlign_actionPerformed(ActionEvent e)
2337 viewport.rightAlignIds = idRightAlign.isSelected();
2338 alignPanel.paintAlignment(true);
2341 public void centreColumnLabels_actionPerformed(ActionEvent e)
2343 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2344 alignPanel.paintAlignment(true);
2350 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2352 protected void followHighlight_actionPerformed()
2354 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2356 alignPanel.scrollToPosition(
2357 alignPanel.seqPanel.seqCanvas.searchResults, false);
2367 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2369 viewport.setColourText(colourTextMenuItem.isSelected());
2370 alignPanel.paintAlignment(true);
2379 public void wrapMenuItem_actionPerformed(ActionEvent e)
2381 scaleAbove.setVisible(wrapMenuItem.isSelected());
2382 scaleLeft.setVisible(wrapMenuItem.isSelected());
2383 scaleRight.setVisible(wrapMenuItem.isSelected());
2384 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2385 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2388 public void showAllSeqs_actionPerformed(ActionEvent e)
2390 viewport.showAllHiddenSeqs();
2393 public void showAllColumns_actionPerformed(ActionEvent e)
2395 viewport.showAllHiddenColumns();
2399 public void hideSelSequences_actionPerformed(ActionEvent e)
2401 viewport.hideAllSelectedSeqs();
2402 alignPanel.paintAlignment(true);
2405 public void hideSelColumns_actionPerformed(ActionEvent e)
2407 viewport.hideSelectedColumns();
2408 alignPanel.paintAlignment(true);
2411 public void hiddenMarkers_actionPerformed(ActionEvent e)
2413 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2423 protected void scaleAbove_actionPerformed(ActionEvent e)
2425 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2426 alignPanel.paintAlignment(true);
2435 protected void scaleLeft_actionPerformed(ActionEvent e)
2437 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2438 alignPanel.paintAlignment(true);
2447 protected void scaleRight_actionPerformed(ActionEvent e)
2449 viewport.setScaleRightWrapped(scaleRight.isSelected());
2450 alignPanel.paintAlignment(true);
2459 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2461 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2462 alignPanel.paintAlignment(true);
2471 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2473 viewport.setShowText(viewTextMenuItem.isSelected());
2474 alignPanel.paintAlignment(true);
2483 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2485 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2486 alignPanel.paintAlignment(true);
2489 public FeatureSettings featureSettings;
2491 public void featureSettings_actionPerformed(ActionEvent e)
2493 if (featureSettings != null)
2495 featureSettings.close();
2496 featureSettings = null;
2498 featureSettings = new FeatureSettings(this);
2502 * Set or clear 'Show Sequence Features'
2507 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2509 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2510 alignPanel.paintAlignment(true);
2511 if (alignPanel.getOverviewPanel() != null)
2513 alignPanel.getOverviewPanel().updateOverviewImage();
2518 * Set or clear 'Show Sequence Features'
2523 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2525 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2527 if (viewport.getShowSequenceFeaturesHeight())
2529 // ensure we're actually displaying features
2530 viewport.setShowSequenceFeatures(true);
2531 showSeqFeatures.setSelected(true);
2533 alignPanel.paintAlignment(true);
2534 if (alignPanel.getOverviewPanel() != null)
2536 alignPanel.getOverviewPanel().updateOverviewImage();
2546 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2548 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2549 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2552 public void alignmentProperties()
2554 JEditorPane editPane = new JEditorPane("text/html", "");
2555 editPane.setEditable(false);
2556 StringBuffer contents = new StringBuffer("<html>");
2559 int min = Integer.MAX_VALUE, max = 0;
2560 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2562 int size = viewport.alignment.getSequenceAt(i).getEnd()
2563 - viewport.alignment.getSequenceAt(i).getStart();
2570 avg = avg / (float) viewport.alignment.getHeight();
2572 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2573 contents.append("<br>Minimum Sequence Length: " + min);
2574 contents.append("<br>Maximum Sequence Length: " + max);
2575 contents.append("<br>Average Length: " + (int) avg);
2577 if (((Alignment) viewport.alignment).getProperties() != null)
2579 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2580 Enumeration en = props.keys();
2581 contents.append("<br><br><table border=\"1\">");
2582 while (en.hasMoreElements())
2584 String key = en.nextElement().toString();
2585 StringBuffer val = new StringBuffer();
2586 String vals = props.get(key).toString();
2590 npos = vals.indexOf("\n", pos);
2593 val.append(vals.substring(pos));
2597 val.append(vals.substring(pos, npos));
2601 } while (npos != -1);
2603 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2605 contents.append("</table>");
2607 editPane.setText(contents.toString() + "</html>");
2608 JInternalFrame frame = new JInternalFrame();
2609 frame.getContentPane().add(new JScrollPane(editPane));
2611 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2612 + getTitle(), 500, 400);
2621 public void overviewMenuItem_actionPerformed(ActionEvent e)
2623 if (alignPanel.overviewPanel != null)
2628 JInternalFrame frame = new JInternalFrame();
2629 OverviewPanel overview = new OverviewPanel(alignPanel);
2630 frame.setContentPane(overview);
2631 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2632 .getWidth(), frame.getHeight());
2634 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2636 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2638 public void internalFrameClosed(
2639 javax.swing.event.InternalFrameEvent evt)
2641 alignPanel.setOverviewPanel(null);
2645 alignPanel.setOverviewPanel(overview);
2648 public void textColour_actionPerformed(ActionEvent e)
2650 new TextColourChooser().chooseColour(alignPanel, null);
2659 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2670 public void clustalColour_actionPerformed(ActionEvent e)
2672 changeColour(new ClustalxColourScheme(
2673 viewport.alignment.getSequences(), viewport.alignment
2683 public void zappoColour_actionPerformed(ActionEvent e)
2685 changeColour(new ZappoColourScheme());
2694 public void taylorColour_actionPerformed(ActionEvent e)
2696 changeColour(new TaylorColourScheme());
2705 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2707 changeColour(new HydrophobicColourScheme());
2716 public void helixColour_actionPerformed(ActionEvent e)
2718 changeColour(new HelixColourScheme());
2727 public void strandColour_actionPerformed(ActionEvent e)
2729 changeColour(new StrandColourScheme());
2738 public void turnColour_actionPerformed(ActionEvent e)
2740 changeColour(new TurnColourScheme());
2749 public void buriedColour_actionPerformed(ActionEvent e)
2751 changeColour(new BuriedColourScheme());
2760 public void nucleotideColour_actionPerformed(ActionEvent e)
2762 changeColour(new NucleotideColourScheme());
2765 public void annotationColour_actionPerformed(ActionEvent e)
2767 new AnnotationColourChooser(viewport, alignPanel);
2776 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2778 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2787 public void changeColour(ColourSchemeI cs)
2793 if (viewport.getAbovePIDThreshold())
2795 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2798 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2800 viewport.setGlobalColourScheme(cs);
2804 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2807 if (viewport.getConservationSelected())
2810 Alignment al = (Alignment) viewport.alignment;
2811 Conservation c = new Conservation("All",
2812 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2816 c.verdict(false, viewport.ConsPercGaps);
2818 cs.setConservation(c);
2820 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2825 cs.setConservation(null);
2828 cs.setConsensus(viewport.hconsensus);
2831 viewport.setGlobalColourScheme(cs);
2833 if (viewport.getColourAppliesToAllGroups())
2835 Vector groups = viewport.alignment.getGroups();
2837 for (int i = 0; i < groups.size(); i++)
2839 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2847 if (cs instanceof ClustalxColourScheme)
2849 sg.cs = new ClustalxColourScheme(sg
2850 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2852 else if (cs instanceof UserColourScheme)
2854 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2860 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2861 } catch (Exception ex)
2866 if (viewport.getAbovePIDThreshold()
2867 || cs instanceof PIDColourScheme
2868 || cs instanceof Blosum62ColourScheme)
2870 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2872 sg.cs.setConsensus(AAFrequency.calculate(sg
2873 .getSequences(viewport.hiddenRepSequences), sg
2874 .getStartRes(), sg.getEndRes() + 1));
2878 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2881 if (viewport.getConservationSelected())
2883 Conservation c = new Conservation("Group",
2884 ResidueProperties.propHash, 3, sg
2885 .getSequences(viewport.hiddenRepSequences), sg
2886 .getStartRes(), sg.getEndRes() + 1);
2888 c.verdict(false, viewport.ConsPercGaps);
2889 sg.cs.setConservation(c);
2893 sg.cs.setConservation(null);
2898 if (alignPanel.getOverviewPanel() != null)
2900 alignPanel.getOverviewPanel().updateOverviewImage();
2903 alignPanel.paintAlignment(true);
2912 protected void modifyPID_actionPerformed(ActionEvent e)
2914 if (viewport.getAbovePIDThreshold()
2915 && viewport.globalColourScheme != null)
2917 SliderPanel.setPIDSliderSource(alignPanel, viewport
2918 .getGlobalColourScheme(), "Background");
2919 SliderPanel.showPIDSlider();
2929 protected void modifyConservation_actionPerformed(ActionEvent e)
2931 if (viewport.getConservationSelected()
2932 && viewport.globalColourScheme != null)
2934 SliderPanel.setConservationSlider(alignPanel,
2935 viewport.globalColourScheme, "Background");
2936 SliderPanel.showConservationSlider();
2946 protected void conservationMenuItem_actionPerformed(ActionEvent e)
2948 viewport.setConservationSelected(conservationMenuItem.isSelected());
2950 viewport.setAbovePIDThreshold(false);
2951 abovePIDThreshold.setSelected(false);
2953 changeColour(viewport.getGlobalColourScheme());
2955 modifyConservation_actionPerformed(null);
2964 public void abovePIDThreshold_actionPerformed(ActionEvent e)
2966 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
2968 conservationMenuItem.setSelected(false);
2969 viewport.setConservationSelected(false);
2971 changeColour(viewport.getGlobalColourScheme());
2973 modifyPID_actionPerformed(null);
2982 public void userDefinedColour_actionPerformed(ActionEvent e)
2984 if (e.getActionCommand().equals("User Defined..."))
2986 new UserDefinedColours(alignPanel, null);
2990 UserColourScheme udc = (UserColourScheme) UserDefinedColours
2991 .getUserColourSchemes().get(e.getActionCommand());
2997 public void updateUserColourMenu()
3000 Component[] menuItems = colourMenu.getMenuComponents();
3001 int i, iSize = menuItems.length;
3002 for (i = 0; i < iSize; i++)
3004 if (menuItems[i].getName() != null
3005 && menuItems[i].getName().equals("USER_DEFINED"))
3007 colourMenu.remove(menuItems[i]);
3011 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3013 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3014 .getUserColourSchemes().keys();
3016 while (userColours.hasMoreElements())
3018 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3019 userColours.nextElement().toString());
3020 radioItem.setName("USER_DEFINED");
3021 radioItem.addMouseListener(new MouseAdapter()
3023 public void mousePressed(MouseEvent evt)
3025 if (evt.isControlDown()
3026 || SwingUtilities.isRightMouseButton(evt))
3029 .removeActionListener(radioItem.getActionListeners()[0]);
3031 int option = JOptionPane.showInternalConfirmDialog(
3032 jalview.gui.Desktop.desktop,
3033 "Remove from default list?",
3034 "Remove user defined colour",
3035 JOptionPane.YES_NO_OPTION);
3036 if (option == JOptionPane.YES_OPTION)
3038 jalview.gui.UserDefinedColours
3039 .removeColourFromDefaults(radioItem.getText());
3040 colourMenu.remove(radioItem);
3044 radioItem.addActionListener(new ActionListener()
3046 public void actionPerformed(ActionEvent evt)
3048 userDefinedColour_actionPerformed(evt);
3055 radioItem.addActionListener(new ActionListener()
3057 public void actionPerformed(ActionEvent evt)
3059 userDefinedColour_actionPerformed(evt);
3063 colourMenu.insert(radioItem, 15);
3064 colours.add(radioItem);
3075 public void PIDColour_actionPerformed(ActionEvent e)
3077 changeColour(new PIDColourScheme());
3086 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3088 changeColour(new Blosum62ColourScheme());
3097 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3099 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3100 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3101 .getAlignment().getSequenceAt(0), null);
3102 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3103 viewport.alignment));
3104 alignPanel.paintAlignment(true);
3113 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3115 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3116 AlignmentSorter.sortByID(viewport.getAlignment());
3117 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
3118 alignPanel.paintAlignment(true);
3127 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3129 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3130 AlignmentSorter.sortByLength(viewport.getAlignment());
3131 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3132 viewport.alignment));
3133 alignPanel.paintAlignment(true);
3142 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3144 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3145 AlignmentSorter.sortByGroup(viewport.getAlignment());
3146 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3147 viewport.alignment));
3149 alignPanel.paintAlignment(true);
3158 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3160 new RedundancyPanel(alignPanel, this);
3169 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3171 if ((viewport.getSelectionGroup() == null)
3172 || (viewport.getSelectionGroup().getSize() < 2))
3174 JOptionPane.showInternalMessageDialog(this,
3175 "You must select at least 2 sequences.", "Invalid Selection",
3176 JOptionPane.WARNING_MESSAGE);
3180 JInternalFrame frame = new JInternalFrame();
3181 frame.setContentPane(new PairwiseAlignPanel(viewport));
3182 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
3192 public void PCAMenuItem_actionPerformed(ActionEvent e)
3194 if (((viewport.getSelectionGroup() != null)
3195 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3196 .getSelectionGroup().getSize() > 0))
3197 || (viewport.getAlignment().getHeight() < 4))
3199 JOptionPane.showInternalMessageDialog(this,
3200 "Principal component analysis must take\n"
3201 + "at least 4 input sequences.",
3202 "Sequence selection insufficient",
3203 JOptionPane.WARNING_MESSAGE);
3208 new PCAPanel(alignPanel);
3211 public void autoCalculate_actionPerformed(ActionEvent e)
3213 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3214 if (viewport.autoCalculateConsensus)
3216 viewport.firePropertyChange("alignment", null, viewport
3217 .getAlignment().getSequences());
3227 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3229 NewTreePanel("AV", "PID", "Average distance tree using PID");
3238 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3240 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3249 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3251 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3260 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3262 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3275 void NewTreePanel(String type, String pwType, String title)
3279 if (viewport.getSelectionGroup() != null)
3281 if (viewport.getSelectionGroup().getSize() < 3)
3286 "You need to have more than two sequences selected to build a tree!",
3287 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3292 SequenceGroup sg = viewport.getSelectionGroup();
3294 /* Decide if the selection is a column region */
3295 while (s < sg.getSize())
3297 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3303 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3304 + "Try using the Pad function in the edit menu,\n"
3305 + "or one of the multiple sequence alignment web services.",
3306 "Sequences in selection are not aligned",
3307 JOptionPane.WARNING_MESSAGE);
3313 title = title + " on region";
3314 tp = new TreePanel(alignPanel, type, pwType);
3318 // are the sequences aligned?
3319 if (!viewport.alignment.isAligned())
3324 "The sequences must be aligned before creating a tree.\n"
3325 + "Try using the Pad function in the edit menu,\n"
3326 + "or one of the multiple sequence alignment web services.",
3327 "Sequences not aligned",
3328 JOptionPane.WARNING_MESSAGE);
3333 if (viewport.alignment.getHeight() < 2)
3338 tp = new TreePanel(alignPanel, type, pwType);
3343 if (viewport.viewName != null)
3345 title += viewport.viewName + " of ";
3348 title += this.title;
3350 Desktop.addInternalFrame(tp, title, 600, 500);
3361 public void addSortByOrderMenuItem(String title,
3362 final AlignmentOrder order)
3364 final JMenuItem item = new JMenuItem("by " + title);
3366 item.addActionListener(new java.awt.event.ActionListener()
3368 public void actionPerformed(ActionEvent e)
3370 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3372 // TODO: JBPNote - have to map order entries to curent SequenceI
3374 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3376 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3377 viewport.alignment));
3379 alignPanel.paintAlignment(true);
3385 * Add a new sort by annotation score menu item
3388 * the menu to add the option to
3390 * the label used to retrieve scores for each sequence on the
3393 public void addSortByAnnotScoreMenuItem(JMenu sort,
3394 final String scoreLabel)
3396 final JMenuItem item = new JMenuItem(scoreLabel);
3398 item.addActionListener(new java.awt.event.ActionListener()
3400 public void actionPerformed(ActionEvent e)
3402 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3403 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3404 .getAlignment());// ,viewport.getSelectionGroup());
3405 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3406 viewport.alignment));
3407 alignPanel.paintAlignment(true);
3413 * last hash for alignment's annotation array - used to minimise cost of
3416 protected int _annotationScoreVectorHash;
3419 * search the alignment and rebuild the sort by annotation score submenu the
3420 * last alignment annotation vector hash is stored to minimize cost of
3421 * rebuilding in subsequence calls.
3424 public void buildSortByAnnotationScoresMenu()
3426 if (viewport.alignment.getAlignmentAnnotation() == null)
3431 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3433 sortByAnnotScore.removeAll();
3434 // almost certainly a quicker way to do this - but we keep it simple
3435 Hashtable scoreSorts = new Hashtable();
3436 AlignmentAnnotation aann[];
3437 Enumeration sq = viewport.alignment.getSequences().elements();
3438 while (sq.hasMoreElements())
3440 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3441 for (int i = 0; aann != null && i < aann.length; i++)
3443 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3445 scoreSorts.put(aann[i].label, aann[i].label);
3449 Enumeration labels = scoreSorts.keys();
3450 while (labels.hasMoreElements())
3452 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3455 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3458 _annotationScoreVectorHash = viewport.alignment
3459 .getAlignmentAnnotation().hashCode();
3464 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3465 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3466 * call. Listeners are added to remove the menu item when the treePanel is
3467 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3471 * Displayed tree window.
3473 * SortBy menu item title.
3475 public void buildTreeMenu()
3477 sortByTreeMenu.removeAll();
3479 Vector comps = (Vector) PaintRefresher.components.get(viewport
3480 .getSequenceSetId());
3481 Vector treePanels = new Vector();
3482 int i, iSize = comps.size();
3483 for (i = 0; i < iSize; i++)
3485 if (comps.elementAt(i) instanceof TreePanel)
3487 treePanels.add(comps.elementAt(i));
3491 iSize = treePanels.size();
3495 sortByTreeMenu.setVisible(false);
3499 sortByTreeMenu.setVisible(true);
3501 for (i = 0; i < treePanels.size(); i++)
3503 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3504 final JMenuItem item = new JMenuItem(tp.getTitle());
3505 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3506 item.addActionListener(new java.awt.event.ActionListener()
3508 public void actionPerformed(ActionEvent e)
3510 SequenceI[] oldOrder = viewport.getAlignment()
3511 .getSequencesArray();
3512 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3514 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3515 viewport.alignment));
3517 alignPanel.paintAlignment(true);
3521 sortByTreeMenu.add(item);
3526 * Work out whether the whole set of sequences or just the selected set will
3527 * be submitted for multiple alignment.
3530 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3532 // Now, check we have enough sequences
3533 AlignmentView msa = null;
3535 if ((viewport.getSelectionGroup() != null)
3536 && (viewport.getSelectionGroup().getSize() > 1))
3538 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3539 // some common interface!
3541 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3542 * SequenceI[sz = seqs.getSize(false)];
3544 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3545 * seqs.getSequenceAt(i); }
3547 msa = viewport.getAlignmentView(true);
3552 * Vector seqs = viewport.getAlignment().getSequences();
3554 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3556 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3557 * seqs.elementAt(i); } }
3559 msa = viewport.getAlignmentView(false);
3565 * Decides what is submitted to a secondary structure prediction service: the
3566 * first sequence in the alignment, or in the current selection, or, if the
3567 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3568 * region or the whole alignment. (where the first sequence in the set is the
3569 * one that the prediction will be for).
3571 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3573 AlignmentView seqs = null;
3575 if ((viewport.getSelectionGroup() != null)
3576 && (viewport.getSelectionGroup().getSize() > 0))
3578 seqs = viewport.getAlignmentView(true);
3582 seqs = viewport.getAlignmentView(false);
3584 // limit sequences - JBPNote in future - could spawn multiple prediction
3586 // TODO: viewport.alignment.isAligned is a global state - the local
3587 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3588 if (!viewport.alignment.isAligned())
3590 seqs.setSequences(new SeqCigar[]
3591 { seqs.getSequences()[0] });
3592 // TODO: if seqs.getSequences().length>1 then should really have warned user!
3604 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3606 // Pick the tree file
3607 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3608 .getProperty("LAST_DIRECTORY"));
3609 chooser.setFileView(new JalviewFileView());
3610 chooser.setDialogTitle("Select a newick-like tree file");
3611 chooser.setToolTipText("Load a tree file");
3613 int value = chooser.showOpenDialog(null);
3615 if (value == JalviewFileChooser.APPROVE_OPTION)
3617 String choice = chooser.getSelectedFile().getPath();
3618 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3619 jalview.io.NewickFile fin = null;
3622 fin = new jalview.io.NewickFile(choice, "File");
3623 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3624 } catch (Exception ex)
3626 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3627 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3628 ex.printStackTrace();
3630 if (fin != null && fin.hasWarningMessage())
3632 JOptionPane.showMessageDialog(Desktop.desktop, fin
3633 .getWarningMessage(), "Possible problem with tree file",
3634 JOptionPane.WARNING_MESSAGE);
3639 public TreePanel ShowNewickTree(NewickFile nf, String title)
3641 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3644 public TreePanel ShowNewickTree(NewickFile nf, String title,
3645 AlignmentView input)
3647 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3650 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3651 int h, int x, int y)
3653 return ShowNewickTree(nf, title, null, w, h, x, y);
3657 * Add a treeviewer for the tree extracted from a newick file object to the
3658 * current alignment view
3665 * Associated alignment input data (or null)
3674 * @return TreePanel handle
3676 public TreePanel ShowNewickTree(NewickFile nf, String title,
3677 AlignmentView input, int w, int h, int x, int y)
3679 TreePanel tp = null;
3685 if (nf.getTree() != null)
3687 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3693 tp.setLocation(x, y);
3696 Desktop.addInternalFrame(tp, title, w, h);
3698 } catch (Exception ex)
3700 ex.printStackTrace();
3707 * Generates menu items and listener event actions for web service clients
3710 public void BuildWebServiceMenu()
3712 // TODO: add support for context dependent disabling of services based on
3713 // alignment and current selection
3714 // TODO: add additional serviceHandle parameter to specify abstract handler
3715 // class independently of AbstractName
3716 // TODO: add in rediscovery GUI function to restart discoverer
3717 // TODO: group services by location as well as function and/or introduce
3718 // object broker mechanism.
3719 if ((Discoverer.services != null) && (Discoverer.services.size() > 0))
3721 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3722 // stored or retrieved from elsewhere
3723 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3724 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3725 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3726 // TODO: move GUI generation code onto service implementation - so a
3727 // client instance attaches itself to the GUI with method call like
3728 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3730 Vector wsmenu = new Vector();
3731 final IProgressIndicator af = this;
3734 // Add any Multiple Sequence Alignment Services
3735 final JMenu msawsmenu = new JMenu("Alignment");
3736 for (int i = 0, j = msaws.size(); i < j; i++)
3738 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3740 jalview.ws.WSClient impl = jalview.ws.Discoverer
3741 .getServiceClient(sh);
3742 impl.attachWSMenuEntry(msawsmenu, this);
3745 wsmenu.add(msawsmenu);
3747 if (secstrpr != null)
3749 // Add any secondary structure prediction services
3750 final JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
3751 for (int i = 0, j = secstrpr.size(); i < j; i++)
3753 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3755 jalview.ws.WSClient impl = jalview.ws.Discoverer
3756 .getServiceClient(sh);
3757 impl.attachWSMenuEntry(secstrmenu, this);
3759 wsmenu.add(secstrmenu);
3761 if (seqsrch != null)
3763 // Add any sequence search services
3764 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3765 for (int i = 0, j = seqsrch.size(); i < j; i++)
3767 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3769 jalview.ws.WSClient impl = jalview.ws.Discoverer
3770 .getServiceClient(sh);
3771 impl.attachWSMenuEntry(seqsrchmenu, this);
3773 // finally, add the whole shebang onto the webservices menu
3774 wsmenu.add(seqsrchmenu);
3776 resetWebServiceMenu();
3777 for (int i = 0, j = wsmenu.size(); i < j; i++)
3779 webService.add((JMenu) wsmenu.get(i));
3784 resetWebServiceMenu();
3785 this.webService.add(this.webServiceNoServices);
3790 * empty the web service menu and add any ad-hoc functions not dynamically
3794 private void resetWebServiceMenu()
3796 webService.removeAll();
3797 build_fetchdbmenu(webService);
3801 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3802 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3803 * getProperty("LAST_DIRECTORY"));
3805 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3806 * to Vamsas file"); chooser.setToolTipText("Export");
3808 * int value = chooser.showSaveDialog(this);
3810 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3811 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3812 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3813 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3816 * prototype of an automatically enabled/disabled analysis function
3819 protected void setShowProductsEnabled()
3821 SequenceI[] selection = viewport.getSequenceSelection();
3822 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3823 viewport.getAlignment().getDataset()))
3825 showProducts.setEnabled(true);
3830 showProducts.setEnabled(false);
3835 * search selection for sequence xRef products and build the show products
3840 * @return true if showProducts menu should be enabled.
3842 public boolean canShowProducts(SequenceI[] selection,
3843 boolean isRegionSelection, Alignment dataset)
3845 boolean showp = false;
3848 showProducts.removeAll();
3849 final boolean dna = viewport.getAlignment().isNucleotide();
3850 final Alignment ds = dataset;
3851 String[] ptypes = (selection == null || selection.length == 0) ? null
3852 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
3854 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
3855 // selection, dataset, true);
3856 final SequenceI[] sel = selection;
3857 for (int t = 0; ptypes != null && t < ptypes.length; t++)
3860 final boolean isRegSel = isRegionSelection;
3861 final AlignFrame af = this;
3862 final String source = ptypes[t];
3863 JMenuItem xtype = new JMenuItem(ptypes[t]);
3864 xtype.addActionListener(new ActionListener()
3867 public void actionPerformed(ActionEvent e)
3869 // TODO: new thread for this call with vis-delay
3870 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
3871 isRegSel, dna, source);
3875 showProducts.add(xtype);
3877 showProducts.setVisible(showp);
3878 showProducts.setEnabled(showp);
3879 } catch (Exception e)
3881 jalview.bin.Cache.log
3883 "canTranslate threw an exception - please report to help@jalview.org",
3890 protected void showProductsFor(SequenceI[] sel, Alignment ds,
3891 boolean isRegSel, boolean dna, String source)
3893 final boolean fisRegSel = isRegSel;
3894 final boolean fdna = dna;
3895 final String fsrc = source;
3896 final AlignFrame ths = this;
3897 final SequenceI[] fsel = sel;
3898 Runnable foo = new Runnable()
3903 final long sttime = System.currentTimeMillis();
3904 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
3907 Alignment ds = ths.getViewport().alignment.getDataset(); // update
3911 Alignment prods = CrossRef
3912 .findXrefSequences(fsel, fdna, fsrc, ds);
3915 SequenceI[] sprods = new SequenceI[prods.getHeight()];
3916 for (int s = 0; s < sprods.length; s++)
3918 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
3919 if (ds.getSequences() == null
3920 || !ds.getSequences().contains(
3921 sprods[s].getDatasetSequence()))
3922 ds.addSequence(sprods[s].getDatasetSequence());
3923 sprods[s].updatePDBIds();
3925 Alignment al = new Alignment(sprods);
3926 AlignedCodonFrame[] cf = prods.getCodonFrames();
3928 for (int s = 0; cf != null && s < cf.length; s++)
3930 al.addCodonFrame(cf[s]);
3933 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
3935 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
3936 + " for " + ((fisRegSel) ? "selected region of " : "")
3938 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
3943 System.err.println("No Sequences generated for xRef type "
3946 } catch (Exception e)
3948 jalview.bin.Cache.log.error(
3949 "Exception when finding crossreferences", e);
3950 } catch (OutOfMemoryError e)
3952 new OOMWarning("whilst fetching crossreferences", e);
3955 jalview.bin.Cache.log.error("Error when finding crossreferences",
3958 ths.setProgressBar("Finished searching for sequences from " + fsrc,
3963 Thread frunner = new Thread(foo);
3967 public boolean canShowTranslationProducts(SequenceI[] selection,
3968 AlignmentI alignment)
3973 return (jalview.analysis.Dna.canTranslate(selection, viewport
3974 .getViewAsVisibleContigs(true)));
3975 } catch (Exception e)
3977 jalview.bin.Cache.log
3979 "canTranslate threw an exception - please report to help@jalview.org",
3985 public void showProducts_actionPerformed(ActionEvent e)
3987 // /////////////////////////////
3988 // Collect Data to be translated/transferred
3990 SequenceI[] selection = viewport.getSequenceSelection();
3991 AlignmentI al = null;
3994 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
3995 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
3996 viewport.getAlignment().getDataset());
3997 } catch (Exception ex)
4000 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4007 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4008 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4012 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4013 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4014 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4018 public void showTranslation_actionPerformed(ActionEvent e)
4020 // /////////////////////////////
4021 // Collect Data to be translated/transferred
4023 SequenceI[] selection = viewport.getSequenceSelection();
4024 String[] seqstring = viewport.getViewAsString(true);
4025 AlignmentI al = null;
4028 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4029 viewport.getViewAsVisibleContigs(true), viewport
4030 .getGapCharacter(), viewport.alignment
4031 .getAlignmentAnnotation(), viewport.alignment
4032 .getWidth(), viewport.getAlignment().getDataset());
4033 } catch (Exception ex)
4036 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4043 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4044 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4048 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4049 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4050 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4055 * Try to load a features file onto the alignment.
4058 * contents or path to retrieve file
4060 * access mode of file (see jalview.io.AlignFile)
4061 * @return true if features file was parsed corectly.
4063 public boolean parseFeaturesFile(String file, String type)
4065 boolean featuresFile = false;
4068 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
4069 .getDataset(), alignPanel.seqPanel.seqCanvas
4070 .getFeatureRenderer().featureColours, false);
4071 } catch (Exception ex)
4073 ex.printStackTrace();
4078 viewport.showSequenceFeatures = true;
4079 showSeqFeatures.setSelected(true);
4080 if (alignPanel.seqPanel.seqCanvas.fr != null)
4082 // update the min/max ranges where necessary
4083 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4085 alignPanel.paintAlignment(true);
4088 return featuresFile;
4091 public void dragEnter(DropTargetDragEvent evt)
4095 public void dragExit(DropTargetEvent evt)
4099 public void dragOver(DropTargetDragEvent evt)
4103 public void dropActionChanged(DropTargetDragEvent evt)
4107 public void drop(DropTargetDropEvent evt)
4109 Transferable t = evt.getTransferable();
4110 java.util.List files = null;
4114 DataFlavor uriListFlavor = new DataFlavor(
4115 "text/uri-list;class=java.lang.String");
4116 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4118 // Works on Windows and MacOSX
4119 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4120 files = (java.util.List) t
4121 .getTransferData(DataFlavor.javaFileListFlavor);
4123 else if (t.isDataFlavorSupported(uriListFlavor))
4125 // This is used by Unix drag system
4126 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4127 String data = (String) t.getTransferData(uriListFlavor);
4128 files = new java.util.ArrayList(1);
4129 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4130 data, "\r\n"); st.hasMoreTokens();)
4132 String s = st.nextToken();
4133 if (s.startsWith("#"))
4135 // the line is a comment (as per the RFC 2483)
4139 java.net.URI uri = new java.net.URI(s);
4140 // check to see if we can handle this kind of URI
4141 if (uri.getScheme().toLowerCase().startsWith("http"))
4143 files.add(uri.toString());
4147 // otherwise preserve old behaviour: catch all for file objects
4148 java.io.File file = new java.io.File(uri);
4149 files.add(file.toString());
4153 } catch (Exception e)
4155 e.printStackTrace();
4162 for (int i = 0; i < files.size(); i++)
4164 loadJalviewDataFile(files.get(i).toString());
4166 } catch (Exception ex)
4168 ex.printStackTrace();
4174 * Attempt to load a "dropped" file or URL string: First by testing whether
4175 * it's and Annotation file, then a JNet file, and finally a features file. If
4176 * all are false then the user may have dropped an alignment file onto this
4180 * either a filename or a URL string.
4182 public void loadJalviewDataFile(String file)
4186 String protocol = jalview.io.FormatAdapter.FILE;
4187 String f = file.toLowerCase();
4188 if (f.indexOf("http:") == 0 || f.indexOf("https:") == 0
4189 || f.indexOf("file:") == 0)
4191 protocol = jalview.io.FormatAdapter.URL;
4194 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
4195 viewport.alignment, file, protocol);
4199 // try to see if its a JNet 'concise' style annotation file *before* we
4200 // try to parse it as a features file
4201 String format = new IdentifyFile().Identify(file, protocol);
4202 if (format.equalsIgnoreCase("JnetFile"))
4204 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
4206 new JnetAnnotationMaker().add_annotation(predictions, viewport
4207 .getAlignment(), 0, false);
4208 isAnnotation = true;
4212 // try to parse it as a features file
4213 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4214 // if it wasn't a features file then we just treat it as a general
4215 // alignment file to load into the current view.
4218 new FileLoader().LoadFile(viewport, file, protocol, format);
4222 alignPanel.paintAlignment(true);
4229 alignPanel.adjustAnnotationHeight();
4230 viewport.updateSequenceIdColours();
4231 buildSortByAnnotationScoresMenu();
4232 alignPanel.paintAlignment(true);
4234 } catch (Exception ex)
4236 ex.printStackTrace();
4240 public void tabSelectionChanged(int index)
4244 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4245 viewport = alignPanel.av;
4246 setMenusFromViewport(viewport);
4250 public void tabbedPane_mousePressed(MouseEvent e)
4252 if (SwingUtilities.isRightMouseButton(e))
4254 String reply = JOptionPane.showInternalInputDialog(this,
4255 "Enter View Name", "Edit View Name",
4256 JOptionPane.QUESTION_MESSAGE);
4260 viewport.viewName = reply;
4261 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4266 public AlignViewport getCurrentView()
4272 * Open the dialog for regex description parsing.
4274 protected void extractScores_actionPerformed(ActionEvent e)
4276 ParseProperties pp = new jalview.analysis.ParseProperties(
4277 viewport.alignment);
4278 // TODO: verify regex and introduce GUI dialog for version 2.5
4279 // if (pp.getScoresFromDescription("col", "score column ",
4280 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4282 if (pp.getScoresFromDescription("description column",
4283 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4285 buildSortByAnnotationScoresMenu();
4293 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4296 protected void showDbRefs_actionPerformed(ActionEvent e)
4298 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
4304 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4307 protected void showNpFeats_actionPerformed(ActionEvent e)
4309 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
4313 * find the viewport amongst the tabs in this alignment frame and close that
4318 public boolean closeView(AlignViewport av)
4322 this.closeMenuItem_actionPerformed(false);
4325 Component[] comp = tabbedPane.getComponents();
4326 for (int i = 0; comp != null && i < comp.length; i++)
4328 if (comp[i] instanceof AlignmentPanel)
4330 if (((AlignmentPanel) comp[i]).av == av)
4333 closeView((AlignmentPanel) comp[i]);
4341 protected void build_fetchdbmenu(JMenu webService)
4343 // Temporary hack - DBRef Fetcher always top level ws entry.
4344 // TODO We probably want to store a sequence database checklist in
4345 // preferences and have checkboxes.. rather than individual sources selected
4347 JMenu rfetch = new JMenu("Fetch DB References");
4349 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
4350 webService.add(rfetch);
4352 JMenuItem fetchr = new JMenuItem("Standard Databases");
4354 .setToolTipText("Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources");
4355 fetchr.addActionListener(new ActionListener()
4358 public void actionPerformed(ActionEvent e)
4360 new Thread(new Runnable()
4365 new jalview.ws.DBRefFetcher(alignPanel.av
4366 .getSequenceSelection(), alignPanel.alignFrame)
4367 .fetchDBRefs(false);
4375 JMenu dfetch = new JMenu();
4377 jalview.ws.SequenceFetcher sf = SequenceFetcher
4378 .getSequenceFetcherSingleton(this);
4379 String[] otherdb = sf.getOrderedSupportedSources();
4380 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4381 // jalview.util.QuickSort.sort(otherdb, otherdb);
4382 int comp = 0, mcomp = 15;
4383 String mname = null;
4384 if (otherdb != null && otherdb.length > 0)
4386 for (int i = 0; i < otherdb.length; i++)
4388 String dbname = sf.getSourceProxy(otherdb[i]).getDbName();
4391 mname = "from '" + dbname + "'";
4393 fetchr = new JMenuItem(otherdb[i]);
4394 final String[] dassource = new String[]
4396 fetchr.addActionListener(new ActionListener()
4399 public void actionPerformed(ActionEvent e)
4401 new Thread(new Runnable()
4406 new jalview.ws.DBRefFetcher(alignPanel.av
4407 .getSequenceSelection(), alignPanel.alignFrame,
4408 dassource).fetchDBRefs(false);
4414 fetchr.setToolTipText("Retrieve from " + dbname);
4416 if (comp++ == mcomp || i == (otherdb.length - 1))
4418 dfetch.setText(mname + " to '" + dbname + "'");
4420 dfetch = new JMenu();
4429 * Left justify the whole alignment.
4431 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
4433 AlignmentI al = viewport.getAlignment();
4435 viewport.firePropertyChange("alignment", null, al);
4439 * Right justify the whole alignment.
4441 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
4443 AlignmentI al = viewport.getAlignment();
4445 viewport.firePropertyChange("alignment", null, al);
4448 public void setShowSeqFeatures(boolean b)
4450 showSeqFeatures.setSelected(true);
4451 viewport.setShowSequenceFeatures(true);
4458 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
4459 * awt.event.ActionEvent)
4461 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
4463 viewport.setShowUnconserved(showUnconservedMenuItem.getState());
4464 alignPanel.paintAlignment(true);
4471 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
4474 protected void showGroupConsensus_actionPerformed(ActionEvent e)
4476 viewport.setShowGroupConsensus(showGroupConsensus.getState());
4477 alignPanel.updateAnnotation();
4485 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
4486 * .event.ActionEvent)
4488 protected void showGroupConservation_actionPerformed(ActionEvent e)
4490 viewport.setShowGroupConservation(showGroupConservation.getState());
4491 alignPanel.updateAnnotation();
4498 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
4499 * .event.ActionEvent)
4501 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
4503 if (viewport.getSelectionGroup() != null)
4505 SequenceGroup[] gps = jalview.analysis.Grouping.makeGroupsFrom(
4506 viewport.getSequenceSelection(), viewport.getAlignmentView(
4507 true).getSequenceStrings(viewport.getGapCharacter()),
4508 viewport.alignment.getGroups());
4509 viewport.alignment.deleteAllGroups();
4510 viewport.sequenceColours = null;
4511 viewport.setSelectionGroup(null);
4512 // set view properties for each group
4513 for (int g = 0; g < gps.length; g++)
4515 gps[g].setShowunconserved(viewport.getShowUnconserved());
4516 gps[g].setIncludeAllConsSymbols(viewport.isIncludeAllConsensusSymbols());
4517 viewport.alignment.addGroup(gps[g]);
4518 Color col = new Color((int) (Math.random() * 255), (int) (Math
4519 .random() * 255), (int) (Math.random() * 255));
4520 col = col.brighter();
4521 for (Enumeration sq = gps[g].getSequences(null).elements(); sq
4522 .hasMoreElements(); viewport.setSequenceColour(
4523 (SequenceI) sq.nextElement(), col))
4526 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
4527 alignPanel.updateAnnotation();
4528 alignPanel.paintAlignment(true);
4533 class PrintThread extends Thread
4537 public PrintThread(AlignmentPanel ap)
4542 static PageFormat pf;
4546 PrinterJob printJob = PrinterJob.getPrinterJob();
4550 printJob.setPrintable(ap, pf);
4554 printJob.setPrintable(ap);
4557 if (printJob.printDialog())
4562 } catch (Exception PrintException)
4564 PrintException.printStackTrace();