2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
25 import java.awt.datatransfer.*;
26 import java.awt.dnd.*;
27 import java.awt.event.*;
28 import java.awt.print.*;
30 import javax.swing.event.MenuEvent;
32 import jalview.analysis.*;
33 import jalview.bin.Cache;
34 import jalview.commands.*;
35 import jalview.datamodel.*;
37 import jalview.jbgui.*;
38 import jalview.schemes.*;
40 import jalview.ws.jws1.Discoverer;
41 import jalview.ws.jws2.Jws2Discoverer;
49 public class AlignFrame extends GAlignFrame implements DropTargetListener,
54 public static final int DEFAULT_WIDTH = 700;
57 public static final int DEFAULT_HEIGHT = 500;
59 public AlignmentPanel alignPanel;
61 AlignViewport viewport;
63 Vector alignPanels = new Vector();
66 * Last format used to load or save alignments in this window
68 String currentFileFormat = null;
71 * Current filename for this alignment
73 String fileName = null;
76 * Creates a new AlignFrame object with specific width and height.
82 public AlignFrame(AlignmentI al, int width, int height)
84 this(al, null, width, height);
88 * Creates a new AlignFrame object with specific width, height and
94 * @param sequenceSetId
96 public AlignFrame(AlignmentI al, int width, int height,
99 this(al, null, width, height, sequenceSetId);
103 * Creates a new AlignFrame object with specific width, height and
109 * @param sequenceSetId
112 public AlignFrame(AlignmentI al, int width, int height,
113 String sequenceSetId, String viewId)
115 this(al, null, width, height, sequenceSetId, viewId);
119 * new alignment window with hidden columns
123 * @param hiddenColumns
124 * ColumnSelection or null
126 * Width of alignment frame
130 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
131 int width, int height)
133 this(al, hiddenColumns, width, height, null);
137 * Create alignment frame for al with hiddenColumns, a specific width and
138 * height, and specific sequenceId
141 * @param hiddenColumns
144 * @param sequenceSetId
147 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
148 int width, int height, String sequenceSetId)
150 this(al, hiddenColumns, width, height, sequenceSetId, null);
154 * Create alignment frame for al with hiddenColumns, a specific width and
155 * height, and specific sequenceId
158 * @param hiddenColumns
161 * @param sequenceSetId
166 public AlignFrame(AlignmentI al, ColumnSelection hiddenColumns,
167 int width, int height, String sequenceSetId, String viewId)
169 setSize(width, height);
170 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
172 alignPanel = new AlignmentPanel(this, viewport);
174 if (al.getDataset() == null)
179 addAlignmentPanel(alignPanel, true);
184 * Make a new AlignFrame from exisiting alignmentPanels
191 public AlignFrame(AlignmentPanel ap)
195 addAlignmentPanel(ap, false);
200 * initalise the alignframe from the underlying viewport data and the
205 if (viewport.conservation == null)
207 BLOSUM62Colour.setEnabled(false);
208 conservationMenuItem.setEnabled(false);
209 modifyConservation.setEnabled(false);
210 // PIDColour.setEnabled(false);
211 // abovePIDThreshold.setEnabled(false);
212 // modifyPID.setEnabled(false);
215 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
218 if (sortby.equals("Id"))
220 sortIDMenuItem_actionPerformed(null);
222 else if (sortby.equals("Pairwise Identity"))
224 sortPairwiseMenuItem_actionPerformed(null);
227 if (Desktop.desktop != null)
229 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
230 addServiceListeners();
231 setGUINucleotide(viewport.alignment.isNucleotide());
234 setMenusFromViewport(viewport);
235 buildSortByAnnotationScoresMenu();
236 if (viewport.wrapAlignment)
238 wrapMenuItem_actionPerformed(null);
241 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
243 this.overviewMenuItem_actionPerformed(null);
251 * Change the filename and format for the alignment, and enable the 'reload'
252 * button functionality.
259 public void setFileName(String file, String format)
262 currentFileFormat = format;
263 reload.setEnabled(true);
266 void addKeyListener()
268 addKeyListener(new KeyAdapter()
270 public void keyPressed(KeyEvent evt)
272 if (viewport.cursorMode
273 && ((evt.getKeyCode() >= KeyEvent.VK_0 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
274 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
275 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
276 && Character.isDigit(evt.getKeyChar()))
277 alignPanel.seqPanel.numberPressed(evt.getKeyChar());
279 switch (evt.getKeyCode())
282 case 27: // escape key
283 deselectAllSequenceMenuItem_actionPerformed(null);
287 case KeyEvent.VK_DOWN:
288 if (evt.isAltDown() || !viewport.cursorMode)
289 moveSelectedSequences(false);
290 if (viewport.cursorMode)
291 alignPanel.seqPanel.moveCursor(0, 1);
295 if (evt.isAltDown() || !viewport.cursorMode)
296 moveSelectedSequences(true);
297 if (viewport.cursorMode)
298 alignPanel.seqPanel.moveCursor(0, -1);
302 case KeyEvent.VK_LEFT:
303 if (evt.isAltDown() || !viewport.cursorMode)
304 slideSequences(false, alignPanel.seqPanel.getKeyboardNo1());
306 alignPanel.seqPanel.moveCursor(-1, 0);
310 case KeyEvent.VK_RIGHT:
311 if (evt.isAltDown() || !viewport.cursorMode)
312 slideSequences(true, alignPanel.seqPanel.getKeyboardNo1());
314 alignPanel.seqPanel.moveCursor(1, 0);
317 case KeyEvent.VK_SPACE:
318 if (viewport.cursorMode)
320 alignPanel.seqPanel.insertGapAtCursor(evt.isControlDown()
321 || evt.isShiftDown() || evt.isAltDown());
325 case KeyEvent.VK_DELETE:
326 case KeyEvent.VK_BACK_SPACE:
327 if (!viewport.cursorMode)
329 cut_actionPerformed(null);
333 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
334 || evt.isShiftDown() || evt.isAltDown());
340 if (viewport.cursorMode)
342 alignPanel.seqPanel.setCursorRow();
346 if (viewport.cursorMode && !evt.isControlDown())
348 alignPanel.seqPanel.setCursorColumn();
352 if (viewport.cursorMode)
354 alignPanel.seqPanel.setCursorPosition();
358 case KeyEvent.VK_ENTER:
359 case KeyEvent.VK_COMMA:
360 if (viewport.cursorMode)
362 alignPanel.seqPanel.setCursorRowAndColumn();
367 if (viewport.cursorMode)
369 alignPanel.seqPanel.setSelectionAreaAtCursor(true);
373 if (viewport.cursorMode)
375 alignPanel.seqPanel.setSelectionAreaAtCursor(false);
380 viewport.cursorMode = !viewport.cursorMode;
381 statusBar.setText("Keyboard editing mode is "
382 + (viewport.cursorMode ? "on" : "off"));
383 if (viewport.cursorMode)
385 alignPanel.seqPanel.seqCanvas.cursorX = viewport.startRes;
386 alignPanel.seqPanel.seqCanvas.cursorY = viewport.startSeq;
388 alignPanel.seqPanel.seqCanvas.repaint();
394 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
395 java.net.URL url = javax.help.HelpSet.findHelpSet(cl,
397 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
399 javax.help.HelpBroker hb = hs.createHelpBroker();
400 hb.setCurrentID("home");
401 hb.setDisplayed(true);
402 } catch (Exception ex)
404 ex.printStackTrace();
409 boolean toggleSeqs = !evt.isControlDown();
410 boolean toggleCols = !evt.isShiftDown();
411 toggleHiddenRegions(toggleSeqs, toggleCols);
414 case KeyEvent.VK_PAGE_UP:
415 if (viewport.wrapAlignment)
417 alignPanel.scrollUp(true);
421 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
422 - viewport.endSeq + viewport.startSeq);
425 case KeyEvent.VK_PAGE_DOWN:
426 if (viewport.wrapAlignment)
428 alignPanel.scrollUp(false);
432 alignPanel.setScrollValues(viewport.startRes, viewport.startSeq
433 + viewport.endSeq - viewport.startSeq);
439 public void keyReleased(KeyEvent evt)
441 switch (evt.getKeyCode())
443 case KeyEvent.VK_LEFT:
444 if (evt.isAltDown() || !viewport.cursorMode)
445 viewport.firePropertyChange("alignment", null, viewport
446 .getAlignment().getSequences());
449 case KeyEvent.VK_RIGHT:
450 if (evt.isAltDown() || !viewport.cursorMode)
451 viewport.firePropertyChange("alignment", null, viewport
452 .getAlignment().getSequences());
459 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
461 ap.alignFrame = this;
463 alignPanels.addElement(ap);
465 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
467 int aSize = alignPanels.size();
469 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
471 if (aSize == 1 && ap.av.viewName == null)
473 this.getContentPane().add(ap, BorderLayout.CENTER);
479 setInitialTabVisible();
482 expandViews.setEnabled(true);
483 gatherViews.setEnabled(true);
484 tabbedPane.addTab(ap.av.viewName, ap);
486 ap.setVisible(false);
493 ap.av.alignment.padGaps();
495 ap.av.updateConservation(ap);
496 ap.av.updateConsensus(ap);
500 public void setInitialTabVisible()
502 expandViews.setEnabled(true);
503 gatherViews.setEnabled(true);
504 tabbedPane.setVisible(true);
505 AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
506 tabbedPane.addTab(first.av.viewName, first);
507 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
510 public AlignViewport getViewport()
515 /* Set up intrinsic listeners for dynamically generated GUI bits. */
516 private void addServiceListeners()
518 final java.beans.PropertyChangeListener thisListener;
519 // Do this once to get current state
520 BuildWebServiceMenu();
521 Desktop.instance.addJalviewPropertyChangeListener("services",
522 thisListener=new java.beans.PropertyChangeListener()
524 public void propertyChange(PropertyChangeEvent evt)
526 // // System.out.println("Discoverer property change.");
527 // if (evt.getPropertyName().equals("services"))
529 SwingUtilities.invokeLater(new Runnable()
536 .println("Rebuild WS Menu for service change");
537 BuildWebServiceMenu();
544 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
546 public void internalFrameClosed(
547 javax.swing.event.InternalFrameEvent evt)
549 System.out.println("deregistering discoverer listener");
550 Desktop.instance.removeJalviewPropertyChangeListener("services",thisListener);
551 closeMenuItem_actionPerformed(true);
556 public void setGUINucleotide(boolean nucleotide)
558 showTranslation.setVisible(nucleotide);
559 conservationMenuItem.setEnabled(!nucleotide);
560 modifyConservation.setEnabled(!nucleotide);
561 showGroupConservation.setEnabled(!nucleotide);
562 // Remember AlignFrame always starts as protein
565 calculateMenu.remove(calculateMenu.getItemCount() - 2);
570 * set up menus for the currently viewport. This may be called after any
571 * operation that affects the data in the current view (selection changed,
572 * etc) to update the menus to reflect the new state.
574 public void setMenusForViewport()
576 setMenusFromViewport(viewport);
580 * Need to call this method when tabs are selected for multiple views, or when
581 * loading from Jalview2XML.java
586 void setMenusFromViewport(AlignViewport av)
588 padGapsMenuitem.setSelected(av.padGaps);
589 colourTextMenuItem.setSelected(av.showColourText);
590 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
591 conservationMenuItem.setSelected(av.getConservationSelected());
592 seqLimits.setSelected(av.getShowJVSuffix());
593 idRightAlign.setSelected(av.rightAlignIds);
594 centreColumnLabelsMenuItem.setState(av.centreColumnLabels);
595 renderGapsMenuItem.setSelected(av.renderGaps);
596 wrapMenuItem.setSelected(av.wrapAlignment);
597 scaleAbove.setVisible(av.wrapAlignment);
598 scaleLeft.setVisible(av.wrapAlignment);
599 scaleRight.setVisible(av.wrapAlignment);
600 annotationPanelMenuItem.setState(av.showAnnotation);
601 viewBoxesMenuItem.setSelected(av.showBoxes);
602 viewTextMenuItem.setSelected(av.showText);
603 showNonconservedMenuItem.setSelected(av.showUnconserved);
604 showGroupConsensus.setSelected(av.showGroupConsensus);
605 showGroupConservation.setSelected(av.showGroupConservation);
606 showConsensusHistogram.setSelected(av.showConsensusHistogram);
607 showSequenceLogo.setSelected(av.showSequenceLogo);
608 setColourSelected(ColourSchemeProperty.getColourName(av
609 .getGlobalColourScheme()));
611 showSeqFeatures.setSelected(av.showSequenceFeatures);
612 hiddenMarkers.setState(av.showHiddenMarkers);
613 applyToAllGroups.setState(av.colourAppliesToAllGroups);
614 showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
615 showDbRefsMenuitem.setSelected(av.isShowDbRefs());
617 setShowProductsEnabled();
622 Hashtable progressBars, progressBarHandlers;
627 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
629 public void setProgressBar(String message, long id)
631 if (progressBars == null)
633 progressBars = new Hashtable();
634 progressBarHandlers = new Hashtable();
637 JPanel progressPanel;
638 Long lId = new Long(id);
639 GridLayout layout = (GridLayout) statusPanel.getLayout();
640 if (progressBars.get(lId) != null)
642 progressPanel = (JPanel) progressBars.get(new Long(id));
643 statusPanel.remove(progressPanel);
644 progressBars.remove(lId);
645 progressPanel = null;
648 statusBar.setText(message);
650 if (progressBarHandlers.contains(lId))
652 progressBarHandlers.remove(lId);
654 layout.setRows(layout.getRows() - 1);
658 progressPanel = new JPanel(new BorderLayout(10, 5));
660 JProgressBar progressBar = new JProgressBar();
661 progressBar.setIndeterminate(true);
663 progressPanel.add(new JLabel(message), BorderLayout.WEST);
664 progressPanel.add(progressBar, BorderLayout.CENTER);
666 layout.setRows(layout.getRows() + 1);
667 statusPanel.add(progressPanel);
669 progressBars.put(lId, progressPanel);
672 setMenusForViewport();
676 public void registerHandler(final long id,
677 final IProgressIndicatorHandler handler)
679 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
682 "call setProgressBar before registering the progress bar's handler.");
684 progressBarHandlers.put(new Long(id), handler);
685 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
686 if (handler.canCancel())
688 JButton cancel = new JButton("Cancel");
689 final IProgressIndicator us = this;
690 cancel.addActionListener(new ActionListener()
693 public void actionPerformed(ActionEvent e)
695 handler.cancelActivity(id);
696 us.setProgressBar("Cancelled "
697 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
700 progressPanel.add(cancel, BorderLayout.EAST);
706 * @return true if any progress bars are still active
708 public boolean operationInProgress()
710 if (progressBars != null && progressBars.size() > 0)
718 * Added so Castor Mapping file can obtain Jalview Version
720 public String getVersion()
722 return jalview.bin.Cache.getProperty("VERSION");
725 public FeatureRenderer getFeatureRenderer()
727 return alignPanel.seqPanel.seqCanvas.getFeatureRenderer();
730 public void fetchSequence_actionPerformed(ActionEvent e)
732 new SequenceFetcher(this);
735 public void addFromFile_actionPerformed(ActionEvent e)
737 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
740 public void reload_actionPerformed(ActionEvent e)
742 if (fileName != null)
744 // TODO: work out how to recover feature settings for correct view(s) when
746 if (currentFileFormat.equals("Jalview"))
748 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
749 for (int i = 0; i < frames.length; i++)
751 if (frames[i] instanceof AlignFrame && frames[i] != this
752 && ((AlignFrame) frames[i]).fileName.equals(fileName))
756 frames[i].setSelected(true);
757 Desktop.instance.closeAssociatedWindows();
758 } catch (java.beans.PropertyVetoException ex)
764 Desktop.instance.closeAssociatedWindows();
766 FileLoader loader = new FileLoader();
767 String protocol = fileName.startsWith("http:") ? "URL" : "File";
768 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
772 Rectangle bounds = this.getBounds();
774 FileLoader loader = new FileLoader();
775 String protocol = fileName.startsWith("http:") ? "URL" : "File";
776 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
777 protocol, currentFileFormat);
779 newframe.setBounds(bounds);
780 if (featureSettings != null && featureSettings.isShowing())
782 final Rectangle fspos = featureSettings.frame.getBounds();
783 // TODO: need a 'show feature settings' function that takes bounds -
784 // need to refactor Desktop.addFrame
785 newframe.featureSettings_actionPerformed(null);
786 final FeatureSettings nfs = newframe.featureSettings;
787 SwingUtilities.invokeLater(new Runnable()
791 nfs.frame.setBounds(fspos);
794 this.featureSettings.close();
795 this.featureSettings = null;
797 this.closeMenuItem_actionPerformed(true);
802 public void addFromText_actionPerformed(ActionEvent e)
804 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
807 public void addFromURL_actionPerformed(ActionEvent e)
809 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
812 public void save_actionPerformed(ActionEvent e)
815 || (currentFileFormat == null || !jalview.io.FormatAdapter
816 .isValidIOFormat(currentFileFormat, true))
817 || fileName.startsWith("http"))
819 saveAs_actionPerformed(null);
823 saveAlignment(fileName, currentFileFormat);
833 public void saveAs_actionPerformed(ActionEvent e)
835 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
836 .getProperty("LAST_DIRECTORY"),
837 jalview.io.AppletFormatAdapter.WRITABLE_EXTENSIONS,
838 jalview.io.AppletFormatAdapter.WRITABLE_FNAMES,
839 currentFileFormat, false);
841 chooser.setFileView(new JalviewFileView());
842 chooser.setDialogTitle("Save Alignment to file");
843 chooser.setToolTipText("Save");
845 int value = chooser.showSaveDialog(this);
847 if (value == JalviewFileChooser.APPROVE_OPTION)
849 currentFileFormat = chooser.getSelectedFormat();
850 if (currentFileFormat == null)
852 JOptionPane.showInternalMessageDialog(Desktop.desktop,
853 "You must select a file format before saving!",
854 "File format not specified", JOptionPane.WARNING_MESSAGE);
855 value = chooser.showSaveDialog(this);
859 fileName = chooser.getSelectedFile().getPath();
861 jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
864 jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
865 if (currentFileFormat.indexOf(" ") > -1)
867 currentFileFormat = currentFileFormat.substring(0,
868 currentFileFormat.indexOf(" "));
870 saveAlignment(fileName, currentFileFormat);
874 public boolean saveAlignment(String file, String format)
876 boolean success = true;
878 if (format.equalsIgnoreCase("Jalview"))
880 String shortName = title;
882 if (shortName.indexOf(java.io.File.separatorChar) > -1)
884 shortName = shortName.substring(shortName
885 .lastIndexOf(java.io.File.separatorChar) + 1);
888 success = new Jalview2XML().SaveAlignment(this, file, shortName);
890 statusBar.setText("Successfully saved to file: " + fileName + " in "
891 + format + " format.");
896 if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
898 warningMessage("Cannot save file " + fileName + " using format "
899 + format, "Alignment output format not supported");
900 saveAs_actionPerformed(null);
901 // JBPNote need to have a raise_gui flag here
905 String[] omitHidden = null;
907 if (viewport.hasHiddenColumns)
909 int reply = JOptionPane
910 .showInternalConfirmDialog(
912 "The Alignment contains hidden columns."
913 + "\nDo you want to save only the visible alignment?",
914 "Save / Omit Hidden Columns",
915 JOptionPane.YES_NO_OPTION,
916 JOptionPane.QUESTION_MESSAGE);
918 if (reply == JOptionPane.YES_OPTION)
920 omitHidden = viewport.getViewAsString(false);
923 FormatAdapter f = new FormatAdapter();
924 String output = f.formatSequences(format,
925 (Alignment) viewport.alignment, // class cast exceptions will
926 // occur in the distant future
927 omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
937 java.io.PrintWriter out = new java.io.PrintWriter(
938 new java.io.FileWriter(file));
943 statusBar.setText("Successfully saved to file: " + fileName
944 + " in " + format + " format.");
945 } catch (Exception ex)
948 ex.printStackTrace();
955 JOptionPane.showInternalMessageDialog(this, "Couldn't save file: "
956 + fileName, "Error Saving File", JOptionPane.WARNING_MESSAGE);
962 private void warningMessage(String warning, String title)
964 if (new jalview.util.Platform().isHeadless())
966 System.err.println("Warning: " + title + "\nWarning: " + warning);
971 JOptionPane.showInternalMessageDialog(this, warning, title,
972 JOptionPane.WARNING_MESSAGE);
983 protected void outputText_actionPerformed(ActionEvent e)
985 String[] omitHidden = null;
987 if (viewport.hasHiddenColumns)
989 int reply = JOptionPane
990 .showInternalConfirmDialog(
992 "The Alignment contains hidden columns."
993 + "\nDo you want to output only the visible alignment?",
994 "Save / Omit Hidden Columns",
995 JOptionPane.YES_NO_OPTION,
996 JOptionPane.QUESTION_MESSAGE);
998 if (reply == JOptionPane.YES_OPTION)
1000 omitHidden = viewport.getViewAsString(false);
1004 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1005 cap.setForInput(null);
1006 Desktop.addInternalFrame(cap, "Alignment output - "
1007 + e.getActionCommand(), 600, 500);
1009 cap.setText(new FormatAdapter().formatSequences(e.getActionCommand(),
1010 viewport.alignment, omitHidden, viewport.colSel));
1019 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1021 new HTMLOutput(alignPanel, alignPanel.seqPanel.seqCanvas
1022 .getSequenceRenderer(), alignPanel.seqPanel.seqCanvas
1023 .getFeatureRenderer());
1026 public void createImageMap(File file, String image)
1028 alignPanel.makePNGImageMap(file, image);
1037 public void createPNG(File f)
1039 alignPanel.makePNG(f);
1048 public void createEPS(File f)
1050 alignPanel.makeEPS(f);
1053 public void pageSetup_actionPerformed(ActionEvent e)
1055 PrinterJob printJob = PrinterJob.getPrinterJob();
1056 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1065 public void printMenuItem_actionPerformed(ActionEvent e)
1067 // Putting in a thread avoids Swing painting problems
1068 PrintThread thread = new PrintThread(alignPanel);
1072 public void exportFeatures_actionPerformed(ActionEvent e)
1074 new AnnotationExporter().exportFeatures(alignPanel);
1077 public void exportAnnotations_actionPerformed(ActionEvent e)
1079 new AnnotationExporter().exportAnnotations(alignPanel,
1080 viewport.showAnnotation ? viewport.alignment
1081 .getAlignmentAnnotation() : null, viewport.alignment
1083 ((Alignment) viewport.alignment).alignmentProperties);
1086 public void associatedData_actionPerformed(ActionEvent e)
1088 // Pick the tree file
1089 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1090 .getProperty("LAST_DIRECTORY"));
1091 chooser.setFileView(new JalviewFileView());
1092 chooser.setDialogTitle("Load Jalview Annotations or Features File");
1093 chooser.setToolTipText("Load Jalview Annotations / Features file");
1095 int value = chooser.showOpenDialog(null);
1097 if (value == JalviewFileChooser.APPROVE_OPTION)
1099 String choice = chooser.getSelectedFile().getPath();
1100 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1101 loadJalviewDataFile(choice);
1107 * Close the current view or all views in the alignment frame. If the frame
1108 * only contains one view then the alignment will be removed from memory.
1110 * @param closeAllTabs
1112 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1114 if (alignPanels != null && alignPanels.size() < 2)
1116 closeAllTabs = true;
1121 if (alignPanels != null)
1125 if (this.isClosed())
1127 // really close all the windows - otherwise wait till
1128 // setClosed(true) is called
1129 for (int i = 0; i < alignPanels.size(); i++)
1131 AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
1138 closeView(alignPanel);
1144 this.setClosed(true);
1146 } catch (Exception ex)
1148 ex.printStackTrace();
1153 * close alignPanel2 and shuffle tabs appropriately.
1155 * @param alignPanel2
1157 public void closeView(AlignmentPanel alignPanel2)
1159 int index = tabbedPane.getSelectedIndex();
1160 int closedindex = tabbedPane.indexOfComponent(alignPanel2);
1161 alignPanels.removeElement(alignPanel2);
1163 // if (viewport == alignPanel2.av)
1167 alignPanel2.closePanel();
1170 tabbedPane.removeTabAt(closedindex);
1171 tabbedPane.validate();
1173 if (index > closedindex || index == tabbedPane.getTabCount())
1175 // modify currently selected tab index if necessary.
1179 this.tabSelectionChanged(index);
1185 void updateEditMenuBar()
1188 if (viewport.historyList.size() > 0)
1190 undoMenuItem.setEnabled(true);
1191 CommandI command = (CommandI) viewport.historyList.peek();
1192 undoMenuItem.setText("Undo " + command.getDescription());
1196 undoMenuItem.setEnabled(false);
1197 undoMenuItem.setText("Undo");
1200 if (viewport.redoList.size() > 0)
1202 redoMenuItem.setEnabled(true);
1204 CommandI command = (CommandI) viewport.redoList.peek();
1205 redoMenuItem.setText("Redo " + command.getDescription());
1209 redoMenuItem.setEnabled(false);
1210 redoMenuItem.setText("Redo");
1214 public void addHistoryItem(CommandI command)
1216 if (command.getSize() > 0)
1218 viewport.historyList.push(command);
1219 viewport.redoList.clear();
1220 updateEditMenuBar();
1221 viewport.hasHiddenColumns = (viewport.colSel != null
1222 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1223 .getHiddenColumns().size() > 0);
1229 * @return alignment objects for all views
1231 AlignmentI[] getViewAlignments()
1233 if (alignPanels != null)
1235 Enumeration e = alignPanels.elements();
1236 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1237 for (int i = 0; e.hasMoreElements(); i++)
1239 als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
1243 if (viewport != null)
1245 return new AlignmentI[]
1246 { viewport.alignment };
1257 protected void undoMenuItem_actionPerformed(ActionEvent e)
1259 if (viewport.historyList.empty())
1261 CommandI command = (CommandI) viewport.historyList.pop();
1262 viewport.redoList.push(command);
1263 command.undoCommand(getViewAlignments());
1265 AlignViewport originalSource = getOriginatingSource(command);
1266 updateEditMenuBar();
1268 if (originalSource != null)
1270 originalSource.hasHiddenColumns = (viewport.colSel != null
1271 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1272 .getHiddenColumns().size() > 0);
1273 originalSource.firePropertyChange("alignment", null,
1274 originalSource.alignment.getSequences());
1284 protected void redoMenuItem_actionPerformed(ActionEvent e)
1286 if (viewport.redoList.size() < 1)
1291 CommandI command = (CommandI) viewport.redoList.pop();
1292 viewport.historyList.push(command);
1293 command.doCommand(getViewAlignments());
1295 AlignViewport originalSource = getOriginatingSource(command);
1296 updateEditMenuBar();
1298 if (originalSource != null)
1300 originalSource.hasHiddenColumns = (viewport.colSel != null
1301 && viewport.colSel.getHiddenColumns() != null && viewport.colSel
1302 .getHiddenColumns().size() > 0);
1303 originalSource.firePropertyChange("alignment", null,
1304 originalSource.alignment.getSequences());
1308 AlignViewport getOriginatingSource(CommandI command)
1310 AlignViewport originalSource = null;
1311 // For sequence removal and addition, we need to fire
1312 // the property change event FROM the viewport where the
1313 // original alignment was altered
1314 AlignmentI al = null;
1315 if (command instanceof EditCommand)
1317 EditCommand editCommand = (EditCommand) command;
1318 al = editCommand.getAlignment();
1319 Vector comps = (Vector) PaintRefresher.components.get(viewport
1320 .getSequenceSetId());
1322 for (int i = 0; i < comps.size(); i++)
1324 if (comps.elementAt(i) instanceof AlignmentPanel)
1326 if (al == ((AlignmentPanel) comps.elementAt(i)).av.alignment)
1328 originalSource = ((AlignmentPanel) comps.elementAt(i)).av;
1335 if (originalSource == null)
1337 // The original view is closed, we must validate
1338 // the current view against the closed view first
1341 PaintRefresher.validateSequences(al, viewport.alignment);
1344 originalSource = viewport;
1347 return originalSource;
1356 public void moveSelectedSequences(boolean up)
1358 SequenceGroup sg = viewport.getSelectionGroup();
1367 for (int i = 1; i < viewport.alignment.getHeight(); i++)
1369 SequenceI seq = viewport.alignment.getSequenceAt(i);
1371 if (!sg.getSequences(null).contains(seq))
1376 SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
1378 if (sg.getSequences(null).contains(temp))
1383 viewport.alignment.getSequences().setElementAt(temp, i);
1384 viewport.alignment.getSequences().setElementAt(seq, i - 1);
1389 for (int i = viewport.alignment.getHeight() - 2; i > -1; i--)
1391 SequenceI seq = viewport.alignment.getSequenceAt(i);
1393 if (!sg.getSequences(null).contains(seq))
1398 SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
1400 if (sg.getSequences(null).contains(temp))
1405 viewport.alignment.getSequences().setElementAt(temp, i);
1406 viewport.alignment.getSequences().setElementAt(seq, i + 1);
1410 alignPanel.paintAlignment(true);
1413 synchronized void slideSequences(boolean right, int size)
1415 Vector sg = new Vector();
1416 if (viewport.cursorMode)
1418 sg.addElement(viewport.alignment
1419 .getSequenceAt(alignPanel.seqPanel.seqCanvas.cursorY));
1421 else if (viewport.getSelectionGroup() != null
1422 && viewport.getSelectionGroup().getSize() != viewport.alignment
1425 sg = viewport.getSelectionGroup().getSequences(
1426 viewport.hiddenRepSequences);
1434 Vector invertGroup = new Vector();
1436 for (int i = 0; i < viewport.alignment.getHeight(); i++)
1438 if (!sg.contains(viewport.alignment.getSequenceAt(i)))
1439 invertGroup.add(viewport.alignment.getSequenceAt(i));
1442 SequenceI[] seqs1 = new SequenceI[sg.size()];
1443 for (int i = 0; i < sg.size(); i++)
1444 seqs1[i] = (SequenceI) sg.elementAt(i);
1446 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1447 for (int i = 0; i < invertGroup.size(); i++)
1448 seqs2[i] = (SequenceI) invertGroup.elementAt(i);
1450 SlideSequencesCommand ssc;
1452 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1453 size, viewport.getGapCharacter());
1455 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1456 size, viewport.getGapCharacter());
1458 int groupAdjustment = 0;
1459 if (ssc.getGapsInsertedBegin() && right)
1461 if (viewport.cursorMode)
1462 alignPanel.seqPanel.moveCursor(size, 0);
1464 groupAdjustment = size;
1466 else if (!ssc.getGapsInsertedBegin() && !right)
1468 if (viewport.cursorMode)
1469 alignPanel.seqPanel.moveCursor(-size, 0);
1471 groupAdjustment = -size;
1474 if (groupAdjustment != 0)
1476 viewport.getSelectionGroup().setStartRes(
1477 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1478 viewport.getSelectionGroup().setEndRes(
1479 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1482 boolean appendHistoryItem = false;
1483 if (viewport.historyList != null && viewport.historyList.size() > 0
1484 && viewport.historyList.peek() instanceof SlideSequencesCommand)
1486 appendHistoryItem = ssc
1487 .appendSlideCommand((SlideSequencesCommand) viewport.historyList
1491 if (!appendHistoryItem)
1492 addHistoryItem(ssc);
1503 protected void copy_actionPerformed(ActionEvent e)
1506 if (viewport.getSelectionGroup() == null)
1510 // TODO: preserve the ordering of displayed alignment annotation in any
1511 // internal paste (particularly sequence associated annotation)
1512 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1513 String[] omitHidden = null;
1515 if (viewport.hasHiddenColumns)
1517 omitHidden = viewport.getViewAsString(true);
1520 String output = new FormatAdapter().formatSequences("Fasta", seqs,
1523 StringSelection ss = new StringSelection(output);
1527 jalview.gui.Desktop.internalCopy = true;
1528 // Its really worth setting the clipboard contents
1529 // to empty before setting the large StringSelection!!
1530 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
1531 new StringSelection(""), null);
1533 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1535 } catch (OutOfMemoryError er)
1537 new OOMWarning("copying region", er);
1541 Vector hiddenColumns = null;
1542 if (viewport.hasHiddenColumns)
1544 hiddenColumns = new Vector();
1545 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1546 .getSelectionGroup().getEndRes();
1547 for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns()
1550 int[] region = (int[]) viewport.getColumnSelection()
1551 .getHiddenColumns().elementAt(i);
1552 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1554 hiddenColumns.addElement(new int[]
1555 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1560 Desktop.jalviewClipboard = new Object[]
1561 { seqs, viewport.alignment.getDataset(), hiddenColumns };
1562 statusBar.setText("Copied " + seqs.length + " sequences to clipboard.");
1571 protected void pasteNew_actionPerformed(ActionEvent e)
1582 protected void pasteThis_actionPerformed(ActionEvent e)
1588 * Paste contents of Jalview clipboard
1590 * @param newAlignment
1591 * true to paste to a new alignment, otherwise add to this.
1593 void paste(boolean newAlignment)
1595 boolean externalPaste = true;
1598 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1599 Transferable contents = c.getContents(this);
1601 if (contents == null)
1609 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1610 if (str.length() < 1)
1615 format = new IdentifyFile().Identify(str, "Paste");
1617 } catch (OutOfMemoryError er)
1619 new OOMWarning("Out of memory pasting sequences!!", er);
1623 SequenceI[] sequences;
1624 boolean annotationAdded = false;
1625 AlignmentI alignment = null;
1627 if (Desktop.jalviewClipboard != null)
1629 // The clipboard was filled from within Jalview, we must use the
1631 // And dataset from the copied alignment
1632 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1633 // be doubly sure that we create *new* sequence objects.
1634 sequences = new SequenceI[newseq.length];
1635 for (int i = 0; i < newseq.length; i++)
1637 sequences[i] = new Sequence(newseq[i]);
1639 alignment = new Alignment(sequences);
1640 externalPaste = false;
1644 // parse the clipboard as an alignment.
1645 alignment = new FormatAdapter().readFile(str, "Paste", format);
1646 sequences = alignment.getSequencesArray();
1654 if (Desktop.jalviewClipboard != null)
1656 // dataset is inherited
1657 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1661 // new dataset is constructed
1662 alignment.setDataset(null);
1664 alwidth = alignment.getWidth() + 1;
1668 AlignmentI pastedal = alignment; // preserve pasted alignment object
1669 // Add pasted sequences and dataset into existing alignment.
1670 alignment = viewport.getAlignment();
1671 alwidth = alignment.getWidth() + 1;
1672 // decide if we need to import sequences from an existing dataset
1673 boolean importDs = Desktop.jalviewClipboard != null
1674 && Desktop.jalviewClipboard[1] != alignment.getDataset();
1675 // importDs==true instructs us to copy over new dataset sequences from
1676 // an existing alignment
1677 Vector newDs = (importDs) ? new Vector() : null; // used to create
1678 // minimum dataset set
1680 for (int i = 0; i < sequences.length; i++)
1684 newDs.addElement(null);
1686 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
1688 if (importDs && ds != null)
1690 if (!newDs.contains(ds))
1692 newDs.setElementAt(ds, i);
1693 ds = new Sequence(ds);
1694 // update with new dataset sequence
1695 sequences[i].setDatasetSequence(ds);
1699 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
1704 // copy and derive new dataset sequence
1705 sequences[i] = sequences[i].deriveSequence();
1706 alignment.getDataset().addSequence(
1707 sequences[i].getDatasetSequence());
1708 // TODO: avoid creation of duplicate dataset sequences with a
1709 // 'contains' method using SequenceI.equals()/SequenceI.contains()
1711 alignment.addSequence(sequences[i]); // merges dataset
1715 newDs.clear(); // tidy up
1717 if (pastedal.getAlignmentAnnotation() != null)
1719 // Add any annotation attached to alignment.
1720 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
1721 for (int i = 0; i < alann.length; i++)
1723 annotationAdded = true;
1724 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
1726 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
1727 newann.padAnnotation(alwidth);
1728 alignment.addAnnotation(newann);
1738 addHistoryItem(new EditCommand("Add sequences", EditCommand.PASTE,
1739 sequences, 0, alignment.getWidth(), alignment));
1741 // Add any annotations attached to sequences
1742 for (int i = 0; i < sequences.length; i++)
1744 if (sequences[i].getAnnotation() != null)
1746 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
1748 annotationAdded = true;
1749 sequences[i].getAnnotation()[a].adjustForAlignment();
1750 sequences[i].getAnnotation()[a].padAnnotation(alwidth);
1751 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
1756 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
1763 // propagate alignment changed.
1764 viewport.setEndSeq(alignment.getHeight());
1765 if (annotationAdded)
1767 // Duplicate sequence annotation in all views.
1768 AlignmentI[] alview = this.getViewAlignments();
1769 for (int i = 0; i < sequences.length; i++)
1771 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
1774 for (int avnum = 0; avnum < alview.length; avnum++)
1776 if (alview[avnum] != alignment)
1778 // duplicate in a view other than the one with input focus
1779 int avwidth = alview[avnum].getWidth() + 1;
1780 // this relies on sann being preserved after we
1781 // modify the sequence's annotation array for each duplication
1782 for (int a = 0; a < sann.length; a++)
1784 AlignmentAnnotation newann = new AlignmentAnnotation(
1786 sequences[i].addAlignmentAnnotation(newann);
1787 newann.padAnnotation(avwidth);
1788 alview[avnum].addAnnotation(newann); // annotation was
1789 // duplicated earlier
1790 alview[avnum].setAnnotationIndex(newann, a);
1795 buildSortByAnnotationScoresMenu();
1797 viewport.firePropertyChange("alignment", null, alignment
1803 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
1805 String newtitle = new String("Copied sequences");
1807 if (Desktop.jalviewClipboard != null
1808 && Desktop.jalviewClipboard[2] != null)
1810 Vector hc = (Vector) Desktop.jalviewClipboard[2];
1811 for (int i = 0; i < hc.size(); i++)
1813 int[] region = (int[]) hc.elementAt(i);
1814 af.viewport.hideColumns(region[0], region[1]);
1818 // >>>This is a fix for the moment, until a better solution is
1820 af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer()
1822 alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
1824 // TODO: maintain provenance of an alignment, rather than just make the
1825 // title a concatenation of operations.
1828 if (title.startsWith("Copied sequences"))
1834 newtitle = newtitle.concat("- from " + title);
1839 newtitle = new String("Pasted sequences");
1842 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
1847 } catch (Exception ex)
1849 ex.printStackTrace();
1850 System.out.println("Exception whilst pasting: " + ex);
1851 // could be anything being pasted in here
1862 protected void cut_actionPerformed(ActionEvent e)
1864 copy_actionPerformed(null);
1865 delete_actionPerformed(null);
1874 protected void delete_actionPerformed(ActionEvent evt)
1877 SequenceGroup sg = viewport.getSelectionGroup();
1883 Vector seqs = new Vector();
1885 for (int i = 0; i < sg.getSize(); i++)
1887 seq = sg.getSequenceAt(i);
1888 seqs.addElement(seq);
1891 // If the cut affects all sequences, remove highlighted columns
1892 if (sg.getSize() == viewport.alignment.getHeight())
1894 viewport.getColumnSelection().removeElements(sg.getStartRes(),
1895 sg.getEndRes() + 1);
1898 SequenceI[] cut = new SequenceI[seqs.size()];
1899 for (int i = 0; i < seqs.size(); i++)
1901 cut[i] = (SequenceI) seqs.elementAt(i);
1905 * //ADD HISTORY ITEM
1907 addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT, cut,
1908 sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
1909 viewport.alignment));
1911 viewport.setSelectionGroup(null);
1912 viewport.sendSelection();
1913 viewport.alignment.deleteGroup(sg);
1915 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
1917 if (viewport.getAlignment().getHeight() < 1)
1921 this.setClosed(true);
1922 } catch (Exception ex)
1934 protected void deleteGroups_actionPerformed(ActionEvent e)
1936 viewport.alignment.deleteAllGroups();
1937 viewport.sequenceColours = null;
1938 viewport.setSelectionGroup(null);
1939 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
1940 alignPanel.updateAnnotation();
1941 alignPanel.paintAlignment(true);
1950 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1952 SequenceGroup sg = new SequenceGroup();
1954 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
1956 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
1959 sg.setEndRes(viewport.alignment.getWidth() - 1);
1960 viewport.setSelectionGroup(sg);
1961 viewport.sendSelection();
1962 alignPanel.paintAlignment(true);
1963 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1972 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
1974 if (viewport.cursorMode)
1976 alignPanel.seqPanel.keyboardNo1 = null;
1977 alignPanel.seqPanel.keyboardNo2 = null;
1979 viewport.setSelectionGroup(null);
1980 viewport.getColumnSelection().clear();
1981 viewport.setSelectionGroup(null);
1982 alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
1983 alignPanel.idPanel.idCanvas.searchResults = null;
1984 alignPanel.paintAlignment(true);
1985 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
1994 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
1996 SequenceGroup sg = viewport.getSelectionGroup();
2000 selectAllSequenceMenuItem_actionPerformed(null);
2005 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2007 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2010 alignPanel.paintAlignment(true);
2011 viewport.sendSelection();
2012 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2015 public void invertColSel_actionPerformed(ActionEvent e)
2017 viewport.invertColumnSelection();
2018 alignPanel.paintAlignment(true);
2027 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2029 trimAlignment(true);
2038 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2040 trimAlignment(false);
2043 void trimAlignment(boolean trimLeft)
2045 ColumnSelection colSel = viewport.getColumnSelection();
2048 if (colSel.size() > 0)
2052 column = colSel.getMin();
2056 column = colSel.getMax();
2060 if (viewport.getSelectionGroup() != null)
2062 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2063 viewport.hiddenRepSequences);
2067 seqs = viewport.alignment.getSequencesArray();
2070 TrimRegionCommand trimRegion;
2073 trimRegion = new TrimRegionCommand("Remove Left",
2074 TrimRegionCommand.TRIM_LEFT, seqs, column,
2075 viewport.alignment, viewport.colSel,
2076 viewport.selectionGroup);
2077 viewport.setStartRes(0);
2081 trimRegion = new TrimRegionCommand("Remove Right",
2082 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2083 viewport.alignment, viewport.colSel,
2084 viewport.selectionGroup);
2087 statusBar.setText("Removed " + trimRegion.getSize() + " columns.");
2089 addHistoryItem(trimRegion);
2091 Vector groups = viewport.alignment.getGroups();
2093 for (int i = 0; i < groups.size(); i++)
2095 SequenceGroup sg = (SequenceGroup) groups.get(i);
2097 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2098 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2100 viewport.alignment.deleteGroup(sg);
2104 viewport.firePropertyChange("alignment", null, viewport
2105 .getAlignment().getSequences());
2115 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2117 int start = 0, end = viewport.alignment.getWidth() - 1;
2120 if (viewport.getSelectionGroup() != null)
2122 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2123 viewport.hiddenRepSequences);
2124 start = viewport.getSelectionGroup().getStartRes();
2125 end = viewport.getSelectionGroup().getEndRes();
2129 seqs = viewport.alignment.getSequencesArray();
2132 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2133 "Remove Gapped Columns", seqs, start, end, viewport.alignment);
2135 addHistoryItem(removeGapCols);
2137 statusBar.setText("Removed " + removeGapCols.getSize()
2138 + " empty columns.");
2140 // This is to maintain viewport position on first residue
2141 // of first sequence
2142 SequenceI seq = viewport.alignment.getSequenceAt(0);
2143 int startRes = seq.findPosition(viewport.startRes);
2144 // ShiftList shifts;
2145 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2146 // edit.alColumnChanges=shifts.getInverse();
2147 // if (viewport.hasHiddenColumns)
2148 // viewport.getColumnSelection().compensateForEdits(shifts);
2149 viewport.setStartRes(seq.findIndex(startRes) - 1);
2150 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2161 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2163 int start = 0, end = viewport.alignment.getWidth() - 1;
2166 if (viewport.getSelectionGroup() != null)
2168 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2169 viewport.hiddenRepSequences);
2170 start = viewport.getSelectionGroup().getStartRes();
2171 end = viewport.getSelectionGroup().getEndRes();
2175 seqs = viewport.alignment.getSequencesArray();
2178 // This is to maintain viewport position on first residue
2179 // of first sequence
2180 SequenceI seq = viewport.alignment.getSequenceAt(0);
2181 int startRes = seq.findPosition(viewport.startRes);
2183 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2184 viewport.alignment));
2186 viewport.setStartRes(seq.findIndex(startRes) - 1);
2188 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2199 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2201 viewport.padGaps = padGapsMenuitem.isSelected();
2202 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2208 // if (justifySeqs>0)
2210 // alignment.justify(justifySeqs!=RIGHT_JUSTIFY);
2222 public void findMenuItem_actionPerformed(ActionEvent e)
2227 public void newView_actionPerformed(ActionEvent e)
2229 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2232 newap.av.gatherViewsHere = false;
2234 if (viewport.viewName == null)
2236 viewport.viewName = "Original";
2239 newap.av.historyList = viewport.historyList;
2240 newap.av.redoList = viewport.redoList;
2242 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2243 String newViewName = "View " + index;
2245 Vector comps = (Vector) PaintRefresher.components.get(viewport
2246 .getSequenceSetId());
2247 Vector existingNames = new Vector();
2248 for (int i = 0; i < comps.size(); i++)
2250 if (comps.elementAt(i) instanceof AlignmentPanel)
2252 AlignmentPanel ap = (AlignmentPanel) comps.elementAt(i);
2253 if (!existingNames.contains(ap.av.viewName))
2255 existingNames.addElement(ap.av.viewName);
2260 while (existingNames.contains(newViewName))
2262 newViewName = "View " + (++index);
2265 newap.av.viewName = newViewName;
2267 addAlignmentPanel(newap, true);
2269 if (alignPanels.size() == 2)
2271 viewport.gatherViewsHere = true;
2273 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2276 public void expandViews_actionPerformed(ActionEvent e)
2278 Desktop.instance.explodeViews(this);
2281 public void gatherViews_actionPerformed(ActionEvent e)
2283 Desktop.instance.gatherViews(this);
2292 public void font_actionPerformed(ActionEvent e)
2294 new FontChooser(alignPanel);
2303 protected void seqLimit_actionPerformed(ActionEvent e)
2305 viewport.setShowJVSuffix(seqLimits.isSelected());
2307 alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel
2308 .calculateIdWidth());
2309 alignPanel.paintAlignment(true);
2312 public void idRightAlign_actionPerformed(ActionEvent e)
2314 viewport.rightAlignIds = idRightAlign.isSelected();
2315 alignPanel.paintAlignment(true);
2318 public void centreColumnLabels_actionPerformed(ActionEvent e)
2320 viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2321 alignPanel.paintAlignment(true);
2327 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2329 protected void followHighlight_actionPerformed()
2331 if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2333 alignPanel.scrollToPosition(
2334 alignPanel.seqPanel.seqCanvas.searchResults, false);
2344 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2346 viewport.setColourText(colourTextMenuItem.isSelected());
2347 alignPanel.paintAlignment(true);
2356 public void wrapMenuItem_actionPerformed(ActionEvent e)
2358 scaleAbove.setVisible(wrapMenuItem.isSelected());
2359 scaleLeft.setVisible(wrapMenuItem.isSelected());
2360 scaleRight.setVisible(wrapMenuItem.isSelected());
2361 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2362 alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2365 public void showAllSeqs_actionPerformed(ActionEvent e)
2367 viewport.showAllHiddenSeqs();
2370 public void showAllColumns_actionPerformed(ActionEvent e)
2372 viewport.showAllHiddenColumns();
2376 public void hideSelSequences_actionPerformed(ActionEvent e)
2378 viewport.hideAllSelectedSeqs();
2379 alignPanel.paintAlignment(true);
2383 * called by key handler and the hide all/show all menu items
2388 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2391 boolean hide = false;
2392 SequenceGroup sg = viewport.getSelectionGroup();
2393 if (!toggleSeqs && !toggleCols)
2395 // Hide everything by the current selection - this is a hack - we do the
2396 // invert and then hide
2397 // first check that there will be visible columns after the invert.
2398 if ((viewport.colSel != null && viewport.colSel.getSelected() != null && viewport.colSel
2399 .getSelected().size() > 0)
2400 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2403 // now invert the sequence set, if required - empty selection implies
2404 // that no hiding is required.
2407 invertSequenceMenuItem_actionPerformed(null);
2408 sg = viewport.getSelectionGroup();
2412 viewport.expandColSelection(sg, true);
2413 // finally invert the column selection and get the new sequence
2415 invertColSel_actionPerformed(null);
2422 if (sg != null && sg.getSize() != viewport.alignment.getHeight())
2424 hideSelSequences_actionPerformed(null);
2427 else if (!(toggleCols && viewport.colSel.getSelected().size() > 0))
2429 showAllSeqs_actionPerformed(null);
2435 if (viewport.colSel.getSelected().size() > 0)
2437 hideSelColumns_actionPerformed(null);
2440 viewport.selectionGroup = sg;
2445 showAllColumns_actionPerformed(null);
2454 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
2455 * event.ActionEvent)
2457 public void hideAllButSelection_actionPerformed(ActionEvent e)
2459 toggleHiddenRegions(false, false);
2466 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
2469 public void hideAllSelection_actionPerformed(ActionEvent e)
2471 SequenceGroup sg = viewport.getSelectionGroup();
2472 viewport.expandColSelection(sg, false);
2473 viewport.hideAllSelectedSeqs();
2474 viewport.hideSelectedColumns();
2475 alignPanel.paintAlignment(true);
2482 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
2485 public void showAllhidden_actionPerformed(ActionEvent e)
2487 viewport.showAllHiddenColumns();
2488 viewport.showAllHiddenSeqs();
2489 alignPanel.paintAlignment(true);
2492 public void hideSelColumns_actionPerformed(ActionEvent e)
2494 viewport.hideSelectedColumns();
2495 alignPanel.paintAlignment(true);
2498 public void hiddenMarkers_actionPerformed(ActionEvent e)
2500 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
2510 protected void scaleAbove_actionPerformed(ActionEvent e)
2512 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
2513 alignPanel.paintAlignment(true);
2522 protected void scaleLeft_actionPerformed(ActionEvent e)
2524 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
2525 alignPanel.paintAlignment(true);
2534 protected void scaleRight_actionPerformed(ActionEvent e)
2536 viewport.setScaleRightWrapped(scaleRight.isSelected());
2537 alignPanel.paintAlignment(true);
2546 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
2548 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
2549 alignPanel.paintAlignment(true);
2558 public void viewTextMenuItem_actionPerformed(ActionEvent e)
2560 viewport.setShowText(viewTextMenuItem.isSelected());
2561 alignPanel.paintAlignment(true);
2570 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
2572 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
2573 alignPanel.paintAlignment(true);
2576 public FeatureSettings featureSettings;
2578 public void featureSettings_actionPerformed(ActionEvent e)
2580 if (featureSettings != null)
2582 featureSettings.close();
2583 featureSettings = null;
2585 if (!showSeqFeatures.isSelected())
2587 // make sure features are actually displayed
2588 showSeqFeatures.setSelected(true);
2589 showSeqFeatures_actionPerformed(null);
2591 featureSettings = new FeatureSettings(this);
2595 * Set or clear 'Show Sequence Features'
2600 public void showSeqFeatures_actionPerformed(ActionEvent evt)
2602 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
2603 alignPanel.paintAlignment(true);
2604 if (alignPanel.getOverviewPanel() != null)
2606 alignPanel.getOverviewPanel().updateOverviewImage();
2611 * Set or clear 'Show Sequence Features'
2616 public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
2618 viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
2620 if (viewport.getShowSequenceFeaturesHeight())
2622 // ensure we're actually displaying features
2623 viewport.setShowSequenceFeatures(true);
2624 showSeqFeatures.setSelected(true);
2626 alignPanel.paintAlignment(true);
2627 if (alignPanel.getOverviewPanel() != null)
2629 alignPanel.getOverviewPanel().updateOverviewImage();
2639 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
2641 viewport.setShowAnnotation(annotationPanelMenuItem.isSelected());
2642 alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
2645 public void alignmentProperties()
2647 JEditorPane editPane = new JEditorPane("text/html", "");
2648 editPane.setEditable(false);
2649 StringBuffer contents = new StringBuffer("<html>");
2652 int min = Integer.MAX_VALUE, max = 0;
2653 for (int i = 0; i < viewport.alignment.getHeight(); i++)
2655 int size = viewport.alignment.getSequenceAt(i).getEnd()
2656 - viewport.alignment.getSequenceAt(i).getStart();
2663 avg = avg / (float) viewport.alignment.getHeight();
2665 contents.append("<br>Sequences: " + viewport.alignment.getHeight());
2666 contents.append("<br>Minimum Sequence Length: " + min);
2667 contents.append("<br>Maximum Sequence Length: " + max);
2668 contents.append("<br>Average Length: " + (int) avg);
2670 if (((Alignment) viewport.alignment).getProperties() != null)
2672 Hashtable props = ((Alignment) viewport.alignment).getProperties();
2673 Enumeration en = props.keys();
2674 contents.append("<br><br><table border=\"1\">");
2675 while (en.hasMoreElements())
2677 String key = en.nextElement().toString();
2678 StringBuffer val = new StringBuffer();
2679 String vals = props.get(key).toString();
2683 npos = vals.indexOf("\n", pos);
2686 val.append(vals.substring(pos));
2690 val.append(vals.substring(pos, npos));
2694 } while (npos != -1);
2696 .append("<tr><td>" + key + "</td><td>" + val + "</td></tr>");
2698 contents.append("</table>");
2700 editPane.setText(contents.toString() + "</html>");
2701 JInternalFrame frame = new JInternalFrame();
2702 frame.getContentPane().add(new JScrollPane(editPane));
2704 Desktop.instance.addInternalFrame(frame, "Alignment Properties: "
2705 + getTitle(), 500, 400);
2714 public void overviewMenuItem_actionPerformed(ActionEvent e)
2716 if (alignPanel.overviewPanel != null)
2721 JInternalFrame frame = new JInternalFrame();
2722 OverviewPanel overview = new OverviewPanel(alignPanel);
2723 frame.setContentPane(overview);
2724 Desktop.addInternalFrame(frame, "Overview " + this.getTitle(), frame
2725 .getWidth(), frame.getHeight());
2727 frame.setLayer(JLayeredPane.PALETTE_LAYER);
2729 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
2731 public void internalFrameClosed(
2732 javax.swing.event.InternalFrameEvent evt)
2734 alignPanel.setOverviewPanel(null);
2738 alignPanel.setOverviewPanel(overview);
2741 public void textColour_actionPerformed(ActionEvent e)
2743 new TextColourChooser().chooseColour(alignPanel, null);
2752 protected void noColourmenuItem_actionPerformed(ActionEvent e)
2763 public void clustalColour_actionPerformed(ActionEvent e)
2765 changeColour(new ClustalxColourScheme(
2766 viewport.alignment.getSequences(), viewport.alignment
2776 public void zappoColour_actionPerformed(ActionEvent e)
2778 changeColour(new ZappoColourScheme());
2787 public void taylorColour_actionPerformed(ActionEvent e)
2789 changeColour(new TaylorColourScheme());
2798 public void hydrophobicityColour_actionPerformed(ActionEvent e)
2800 changeColour(new HydrophobicColourScheme());
2809 public void helixColour_actionPerformed(ActionEvent e)
2811 changeColour(new HelixColourScheme());
2820 public void strandColour_actionPerformed(ActionEvent e)
2822 changeColour(new StrandColourScheme());
2831 public void turnColour_actionPerformed(ActionEvent e)
2833 changeColour(new TurnColourScheme());
2842 public void buriedColour_actionPerformed(ActionEvent e)
2844 changeColour(new BuriedColourScheme());
2853 public void nucleotideColour_actionPerformed(ActionEvent e)
2855 changeColour(new NucleotideColourScheme());
2858 public void annotationColour_actionPerformed(ActionEvent e)
2860 new AnnotationColourChooser(viewport, alignPanel);
2869 protected void applyToAllGroups_actionPerformed(ActionEvent e)
2871 viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
2880 public void changeColour(ColourSchemeI cs)
2886 if (viewport.getAbovePIDThreshold())
2888 threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
2891 cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2893 viewport.setGlobalColourScheme(cs);
2897 cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2900 if (viewport.getConservationSelected())
2903 Alignment al = (Alignment) viewport.alignment;
2904 Conservation c = new Conservation("All",
2905 ResidueProperties.propHash, 3, al.getSequences(), 0, al
2909 c.verdict(false, viewport.ConsPercGaps);
2911 cs.setConservation(c);
2913 cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
2918 cs.setConservation(null);
2921 cs.setConsensus(viewport.hconsensus);
2924 viewport.setGlobalColourScheme(cs);
2926 if (viewport.getColourAppliesToAllGroups())
2928 Vector groups = viewport.alignment.getGroups();
2930 for (int i = 0; i < groups.size(); i++)
2932 SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
2940 if (cs instanceof ClustalxColourScheme)
2942 sg.cs = new ClustalxColourScheme(sg
2943 .getSequences(viewport.hiddenRepSequences), sg.getWidth());
2945 else if (cs instanceof UserColourScheme)
2947 sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
2953 sg.cs = (ColourSchemeI) cs.getClass().newInstance();
2954 } catch (Exception ex)
2959 if (viewport.getAbovePIDThreshold()
2960 || cs instanceof PIDColourScheme
2961 || cs instanceof Blosum62ColourScheme)
2963 sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
2965 sg.cs.setConsensus(AAFrequency.calculate(sg
2966 .getSequences(viewport.hiddenRepSequences), sg
2967 .getStartRes(), sg.getEndRes() + 1));
2971 sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
2974 if (viewport.getConservationSelected())
2976 Conservation c = new Conservation("Group",
2977 ResidueProperties.propHash, 3, sg
2978 .getSequences(viewport.hiddenRepSequences), sg
2979 .getStartRes(), sg.getEndRes() + 1);
2981 c.verdict(false, viewport.ConsPercGaps);
2982 sg.cs.setConservation(c);
2986 sg.cs.setConservation(null);
2991 if (alignPanel.getOverviewPanel() != null)
2993 alignPanel.getOverviewPanel().updateOverviewImage();
2996 alignPanel.paintAlignment(true);
3005 protected void modifyPID_actionPerformed(ActionEvent e)
3007 if (viewport.getAbovePIDThreshold()
3008 && viewport.globalColourScheme != null)
3010 SliderPanel.setPIDSliderSource(alignPanel, viewport
3011 .getGlobalColourScheme(), "Background");
3012 SliderPanel.showPIDSlider();
3022 protected void modifyConservation_actionPerformed(ActionEvent e)
3024 if (viewport.getConservationSelected()
3025 && viewport.globalColourScheme != null)
3027 SliderPanel.setConservationSlider(alignPanel,
3028 viewport.globalColourScheme, "Background");
3029 SliderPanel.showConservationSlider();
3039 protected void conservationMenuItem_actionPerformed(ActionEvent e)
3041 viewport.setConservationSelected(conservationMenuItem.isSelected());
3043 viewport.setAbovePIDThreshold(false);
3044 abovePIDThreshold.setSelected(false);
3046 changeColour(viewport.getGlobalColourScheme());
3048 modifyConservation_actionPerformed(null);
3057 public void abovePIDThreshold_actionPerformed(ActionEvent e)
3059 viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3061 conservationMenuItem.setSelected(false);
3062 viewport.setConservationSelected(false);
3064 changeColour(viewport.getGlobalColourScheme());
3066 modifyPID_actionPerformed(null);
3075 public void userDefinedColour_actionPerformed(ActionEvent e)
3077 if (e.getActionCommand().equals("User Defined..."))
3079 new UserDefinedColours(alignPanel, null);
3083 UserColourScheme udc = (UserColourScheme) UserDefinedColours
3084 .getUserColourSchemes().get(e.getActionCommand());
3090 public void updateUserColourMenu()
3093 Component[] menuItems = colourMenu.getMenuComponents();
3094 int i, iSize = menuItems.length;
3095 for (i = 0; i < iSize; i++)
3097 if (menuItems[i].getName() != null
3098 && menuItems[i].getName().equals("USER_DEFINED"))
3100 colourMenu.remove(menuItems[i]);
3104 if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3106 java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3107 .getUserColourSchemes().keys();
3109 while (userColours.hasMoreElements())
3111 final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3112 userColours.nextElement().toString());
3113 radioItem.setName("USER_DEFINED");
3114 radioItem.addMouseListener(new MouseAdapter()
3116 public void mousePressed(MouseEvent evt)
3118 if (evt.isControlDown()
3119 || SwingUtilities.isRightMouseButton(evt))
3122 .removeActionListener(radioItem.getActionListeners()[0]);
3124 int option = JOptionPane.showInternalConfirmDialog(
3125 jalview.gui.Desktop.desktop,
3126 "Remove from default list?",
3127 "Remove user defined colour",
3128 JOptionPane.YES_NO_OPTION);
3129 if (option == JOptionPane.YES_OPTION)
3131 jalview.gui.UserDefinedColours
3132 .removeColourFromDefaults(radioItem.getText());
3133 colourMenu.remove(radioItem);
3137 radioItem.addActionListener(new ActionListener()
3139 public void actionPerformed(ActionEvent evt)
3141 userDefinedColour_actionPerformed(evt);
3148 radioItem.addActionListener(new ActionListener()
3150 public void actionPerformed(ActionEvent evt)
3152 userDefinedColour_actionPerformed(evt);
3156 colourMenu.insert(radioItem, 15);
3157 colours.add(radioItem);
3168 public void PIDColour_actionPerformed(ActionEvent e)
3170 changeColour(new PIDColourScheme());
3179 public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3181 changeColour(new Blosum62ColourScheme());
3190 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3192 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3193 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3194 .getAlignment().getSequenceAt(0), null);
3195 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3196 viewport.alignment));
3197 alignPanel.paintAlignment(true);
3206 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3208 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3209 AlignmentSorter.sortByID(viewport.getAlignment());
3210 addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
3211 alignPanel.paintAlignment(true);
3220 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3222 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3223 AlignmentSorter.sortByLength(viewport.getAlignment());
3224 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3225 viewport.alignment));
3226 alignPanel.paintAlignment(true);
3235 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3237 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3238 AlignmentSorter.sortByGroup(viewport.getAlignment());
3239 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3240 viewport.alignment));
3242 alignPanel.paintAlignment(true);
3251 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3253 new RedundancyPanel(alignPanel, this);
3262 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3264 if ((viewport.getSelectionGroup() == null)
3265 || (viewport.getSelectionGroup().getSize() < 2))
3267 JOptionPane.showInternalMessageDialog(this,
3268 "You must select at least 2 sequences.", "Invalid Selection",
3269 JOptionPane.WARNING_MESSAGE);
3273 JInternalFrame frame = new JInternalFrame();
3274 frame.setContentPane(new PairwiseAlignPanel(viewport));
3275 Desktop.addInternalFrame(frame, "Pairwise Alignment", 600, 500);
3285 public void PCAMenuItem_actionPerformed(ActionEvent e)
3287 if (((viewport.getSelectionGroup() != null)
3288 && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3289 .getSelectionGroup().getSize() > 0))
3290 || (viewport.getAlignment().getHeight() < 4))
3292 JOptionPane.showInternalMessageDialog(this,
3293 "Principal component analysis must take\n"
3294 + "at least 4 input sequences.",
3295 "Sequence selection insufficient",
3296 JOptionPane.WARNING_MESSAGE);
3301 new PCAPanel(alignPanel);
3304 public void autoCalculate_actionPerformed(ActionEvent e)
3306 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3307 if (viewport.autoCalculateConsensus)
3309 viewport.firePropertyChange("alignment", null, viewport
3310 .getAlignment().getSequences());
3320 public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3322 NewTreePanel("AV", "PID", "Average distance tree using PID");
3331 public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3333 NewTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3342 protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3344 NewTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3353 protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3355 NewTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3368 void NewTreePanel(String type, String pwType, String title)
3372 if (viewport.getSelectionGroup() != null)
3374 if (viewport.getSelectionGroup().getSize() < 3)
3379 "You need to have more than two sequences selected to build a tree!",
3380 "Not enough sequences", JOptionPane.WARNING_MESSAGE);
3385 SequenceGroup sg = viewport.getSelectionGroup();
3387 /* Decide if the selection is a column region */
3388 while (s < sg.getSize())
3390 if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
3396 "The selected region to create a tree may\nonly contain residues or gaps.\n"
3397 + "Try using the Pad function in the edit menu,\n"
3398 + "or one of the multiple sequence alignment web services.",
3399 "Sequences in selection are not aligned",
3400 JOptionPane.WARNING_MESSAGE);
3406 title = title + " on region";
3407 tp = new TreePanel(alignPanel, type, pwType);
3411 // are the visible sequences aligned?
3412 if (!viewport.alignment.isAligned(false))
3417 "The sequences must be aligned before creating a tree.\n"
3418 + "Try using the Pad function in the edit menu,\n"
3419 + "or one of the multiple sequence alignment web services.",
3420 "Sequences not aligned",
3421 JOptionPane.WARNING_MESSAGE);
3426 if (viewport.alignment.getHeight() < 2)
3431 tp = new TreePanel(alignPanel, type, pwType);
3436 if (viewport.viewName != null)
3438 title += viewport.viewName + " of ";
3441 title += this.title;
3443 Desktop.addInternalFrame(tp, title, 600, 500);
3454 public void addSortByOrderMenuItem(String title,
3455 final AlignmentOrder order)
3457 final JMenuItem item = new JMenuItem("by " + title);
3459 item.addActionListener(new java.awt.event.ActionListener()
3461 public void actionPerformed(ActionEvent e)
3463 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3465 // TODO: JBPNote - have to map order entries to curent SequenceI
3467 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3469 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3470 viewport.alignment));
3472 alignPanel.paintAlignment(true);
3478 * Add a new sort by annotation score menu item
3481 * the menu to add the option to
3483 * the label used to retrieve scores for each sequence on the
3486 public void addSortByAnnotScoreMenuItem(JMenu sort,
3487 final String scoreLabel)
3489 final JMenuItem item = new JMenuItem(scoreLabel);
3491 item.addActionListener(new java.awt.event.ActionListener()
3493 public void actionPerformed(ActionEvent e)
3495 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3496 AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport
3497 .getAlignment());// ,viewport.getSelectionGroup());
3498 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3499 viewport.alignment));
3500 alignPanel.paintAlignment(true);
3506 * last hash for alignment's annotation array - used to minimise cost of
3509 protected int _annotationScoreVectorHash;
3512 * search the alignment and rebuild the sort by annotation score submenu the
3513 * last alignment annotation vector hash is stored to minimize cost of
3514 * rebuilding in subsequence calls.
3517 public void buildSortByAnnotationScoresMenu()
3519 if (viewport.alignment.getAlignmentAnnotation() == null)
3524 if (viewport.alignment.getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3526 sortByAnnotScore.removeAll();
3527 // almost certainly a quicker way to do this - but we keep it simple
3528 Hashtable scoreSorts = new Hashtable();
3529 AlignmentAnnotation aann[];
3530 Enumeration sq = viewport.alignment.getSequences().elements();
3531 while (sq.hasMoreElements())
3533 aann = ((SequenceI) sq.nextElement()).getAnnotation();
3534 for (int i = 0; aann != null && i < aann.length; i++)
3536 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3538 scoreSorts.put(aann[i].label, aann[i].label);
3542 Enumeration labels = scoreSorts.keys();
3543 while (labels.hasMoreElements())
3545 addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels
3548 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3551 _annotationScoreVectorHash = viewport.alignment
3552 .getAlignmentAnnotation().hashCode();
3557 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3558 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3559 * call. Listeners are added to remove the menu item when the treePanel is
3560 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3564 * Displayed tree window.
3566 * SortBy menu item title.
3568 public void buildTreeMenu()
3570 sortByTreeMenu.removeAll();
3572 Vector comps = (Vector) PaintRefresher.components.get(viewport
3573 .getSequenceSetId());
3574 Vector treePanels = new Vector();
3575 int i, iSize = comps.size();
3576 for (i = 0; i < iSize; i++)
3578 if (comps.elementAt(i) instanceof TreePanel)
3580 treePanels.add(comps.elementAt(i));
3584 iSize = treePanels.size();
3588 sortByTreeMenu.setVisible(false);
3592 sortByTreeMenu.setVisible(true);
3594 for (i = 0; i < treePanels.size(); i++)
3596 TreePanel tp = (TreePanel) treePanels.elementAt(i);
3597 final JMenuItem item = new JMenuItem(tp.getTitle());
3598 final NJTree tree = ((TreePanel) treePanels.elementAt(i)).getTree();
3599 item.addActionListener(new java.awt.event.ActionListener()
3601 public void actionPerformed(ActionEvent e)
3603 SequenceI[] oldOrder = viewport.getAlignment()
3604 .getSequencesArray();
3605 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
3607 addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
3608 viewport.alignment));
3610 alignPanel.paintAlignment(true);
3614 sortByTreeMenu.add(item);
3619 * Work out whether the whole set of sequences or just the selected set will
3620 * be submitted for multiple alignment.
3623 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3625 // Now, check we have enough sequences
3626 AlignmentView msa = null;
3628 if ((viewport.getSelectionGroup() != null)
3629 && (viewport.getSelectionGroup().getSize() > 1))
3631 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3632 // some common interface!
3634 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3635 * SequenceI[sz = seqs.getSize(false)];
3637 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3638 * seqs.getSequenceAt(i); }
3640 msa = viewport.getAlignmentView(true);
3645 * Vector seqs = viewport.getAlignment().getSequences();
3647 * if (seqs.size() > 1) { msa = new SequenceI[seqs.size()];
3649 * for (int i = 0; i < seqs.size(); i++) { msa[i] = (SequenceI)
3650 * seqs.elementAt(i); } }
3652 msa = viewport.getAlignmentView(false);
3658 * Decides what is submitted to a secondary structure prediction service: the
3659 * first sequence in the alignment, or in the current selection, or, if the
3660 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3661 * region or the whole alignment. (where the first sequence in the set is the
3662 * one that the prediction will be for).
3664 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3666 AlignmentView seqs = null;
3668 if ((viewport.getSelectionGroup() != null)
3669 && (viewport.getSelectionGroup().getSize() > 0))
3671 seqs = viewport.getAlignmentView(true);
3675 seqs = viewport.getAlignmentView(false);
3677 // limit sequences - JBPNote in future - could spawn multiple prediction
3679 // TODO: viewport.alignment.isAligned is a global state - the local
3680 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3681 if (!viewport.alignment.isAligned(false))
3683 seqs.setSequences(new SeqCigar[]
3684 { seqs.getSequences()[0] });
3685 // TODO: if seqs.getSequences().length>1 then should really have warned
3698 protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
3700 // Pick the tree file
3701 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
3702 .getProperty("LAST_DIRECTORY"));
3703 chooser.setFileView(new JalviewFileView());
3704 chooser.setDialogTitle("Select a newick-like tree file");
3705 chooser.setToolTipText("Load a tree file");
3707 int value = chooser.showOpenDialog(null);
3709 if (value == JalviewFileChooser.APPROVE_OPTION)
3711 String choice = chooser.getSelectedFile().getPath();
3712 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
3713 jalview.io.NewickFile fin = null;
3716 fin = new jalview.io.NewickFile(choice, "File");
3717 viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
3718 } catch (Exception ex)
3720 JOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3721 "Problem reading tree file", JOptionPane.WARNING_MESSAGE);
3722 ex.printStackTrace();
3724 if (fin != null && fin.hasWarningMessage())
3726 JOptionPane.showMessageDialog(Desktop.desktop, fin
3727 .getWarningMessage(), "Possible problem with tree file",
3728 JOptionPane.WARNING_MESSAGE);
3733 public TreePanel ShowNewickTree(NewickFile nf, String title)
3735 return ShowNewickTree(nf, title, 600, 500, 4, 5);
3738 public TreePanel ShowNewickTree(NewickFile nf, String title,
3739 AlignmentView input)
3741 return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
3744 public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
3745 int h, int x, int y)
3747 return ShowNewickTree(nf, title, null, w, h, x, y);
3751 * Add a treeviewer for the tree extracted from a newick file object to the
3752 * current alignment view
3759 * Associated alignment input data (or null)
3768 * @return TreePanel handle
3770 public TreePanel ShowNewickTree(NewickFile nf, String title,
3771 AlignmentView input, int w, int h, int x, int y)
3773 TreePanel tp = null;
3779 if (nf.getTree() != null)
3781 tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
3787 tp.setLocation(x, y);
3790 Desktop.addInternalFrame(tp, title, w, h);
3792 } catch (Exception ex)
3794 ex.printStackTrace();
3800 private boolean buildingMenu = false;
3803 * Generates menu items and listener event actions for web service clients
3806 public void BuildWebServiceMenu()
3808 while (buildingMenu)
3812 System.err.println("Waiting for building menu to finish.");
3814 } catch (Exception e)
3819 buildingMenu = true;
3823 .println("Building ws menu again " + Thread.currentThread());
3824 // TODO: add support for context dependent disabling of services based on
3825 // alignment and current selection
3826 // TODO: add additional serviceHandle parameter to specify abstract
3828 // class independently of AbstractName
3829 // TODO: add in rediscovery GUI function to restart discoverer
3830 // TODO: group services by location as well as function and/or introduce
3831 // object broker mechanism.
3832 Vector wsmenu = new Vector();
3833 final IProgressIndicator af = this;
3834 if (Cache.getDefault("SHOW_JWS1_SERVICES", true)
3835 && Discoverer.services != null
3836 && (Discoverer.services.size() > 0))
3838 // TODO: refactor to allow list of AbstractName/Handler bindings to be
3839 // stored or retrieved from elsewhere
3840 Vector msaws = (Vector) Discoverer.services.get("MsaWS");
3841 Vector secstrpr = (Vector) Discoverer.services.get("SecStrPred");
3842 Vector seqsrch = (Vector) Discoverer.services.get("SeqSearch");
3843 // TODO: move GUI generation code onto service implementation - so a
3844 // client instance attaches itself to the GUI with method call like
3845 // jalview.ws.MsaWSClient.bind(servicehandle, Desktop.instance,
3849 // Add any Multiple Sequence Alignment Services
3850 final JMenu msawsmenu = new JMenu("Alignment");
3851 for (int i = 0, j = msaws.size(); i < j; i++)
3853 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) msaws
3855 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3856 .getServiceClient(sh);
3857 impl.attachWSMenuEntry(msawsmenu, this);
3860 wsmenu.add(msawsmenu);
3862 if (secstrpr != null)
3864 // Add any secondary structure prediction services
3865 final JMenu secstrmenu = new JMenu(
3866 "Secondary Structure Prediction");
3867 for (int i = 0, j = secstrpr.size(); i < j; i++)
3869 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
3871 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3872 .getServiceClient(sh);
3873 impl.attachWSMenuEntry(secstrmenu, this);
3875 wsmenu.add(secstrmenu);
3877 if (seqsrch != null)
3879 // Add any sequence search services
3880 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
3881 for (int i = 0, j = seqsrch.size(); i < j; i++)
3883 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) seqsrch
3885 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
3886 .getServiceClient(sh);
3887 impl.attachWSMenuEntry(seqsrchmenu, this);
3889 wsmenu.add(seqsrchmenu);
3893 // TODO: move into separate menu builder class.
3894 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
3896 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
3897 if (jws2servs != null)
3899 if (jws2servs.hasServices())
3901 JMenu jws2men = new JMenu("Jalview 2 Services");
3902 jws2servs.attachWSMenuEntry(jws2men, this);
3903 wsmenu.add(jws2men);
3907 resetWebServiceMenu();
3908 // finally, add the whole shebang onto the webservices menu
3909 if (wsmenu.size() > 0)
3911 for (int i = 0, j = wsmenu.size(); i < j; i++)
3913 webService.add((JMenu) wsmenu.get(i));
3918 this.webService.add(this.webServiceNoServices);
3920 } catch (Exception e)
3924 buildingMenu = false;
3928 * empty the web service menu and add any ad-hoc functions not dynamically
3932 private void resetWebServiceMenu()
3934 webService.removeAll();
3935 build_fetchdbmenu(webService);
3936 build_urlServiceMenu(webService);
3940 * construct any groupURL type service menu entries.
3944 private void build_urlServiceMenu(JMenu webService)
3946 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
3948 jalview.ws.EnfinEnvision2OneWay.getInstance().attachWSMenuEntry(
3954 * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
3955 * chooser = new JalviewFileChooser(jalview.bin.Cache.
3956 * getProperty("LAST_DIRECTORY"));
3958 * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
3959 * to Vamsas file"); chooser.setToolTipText("Export");
3961 * int value = chooser.showSaveDialog(this);
3963 * if (value == JalviewFileChooser.APPROVE_OPTION) {
3964 * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
3965 * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
3966 * chooser.getSelectedFile().getAbsolutePath(), this); } }
3969 * prototype of an automatically enabled/disabled analysis function
3972 protected void setShowProductsEnabled()
3974 SequenceI[] selection = viewport.getSequenceSelection();
3975 if (canShowProducts(selection, viewport.getSelectionGroup() != null,
3976 viewport.getAlignment().getDataset()))
3978 showProducts.setEnabled(true);
3983 showProducts.setEnabled(false);
3988 * search selection for sequence xRef products and build the show products
3993 * @return true if showProducts menu should be enabled.
3995 public boolean canShowProducts(SequenceI[] selection,
3996 boolean isRegionSelection, Alignment dataset)
3998 boolean showp = false;
4001 showProducts.removeAll();
4002 final boolean dna = viewport.getAlignment().isNucleotide();
4003 final Alignment ds = dataset;
4004 String[] ptypes = (selection == null || selection.length == 0) ? null
4005 : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4007 // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4008 // selection, dataset, true);
4009 final SequenceI[] sel = selection;
4010 for (int t = 0; ptypes != null && t < ptypes.length; t++)
4013 final boolean isRegSel = isRegionSelection;
4014 final AlignFrame af = this;
4015 final String source = ptypes[t];
4016 JMenuItem xtype = new JMenuItem(ptypes[t]);
4017 xtype.addActionListener(new ActionListener()
4020 public void actionPerformed(ActionEvent e)
4022 // TODO: new thread for this call with vis-delay
4023 af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4024 isRegSel, dna, source);
4028 showProducts.add(xtype);
4030 showProducts.setVisible(showp);
4031 showProducts.setEnabled(showp);
4032 } catch (Exception e)
4034 jalview.bin.Cache.log
4036 "canTranslate threw an exception - please report to help@jalview.org",
4043 protected void showProductsFor(SequenceI[] sel, Alignment ds,
4044 boolean isRegSel, boolean dna, String source)
4046 final boolean fisRegSel = isRegSel;
4047 final boolean fdna = dna;
4048 final String fsrc = source;
4049 final AlignFrame ths = this;
4050 final SequenceI[] fsel = sel;
4051 Runnable foo = new Runnable()
4056 final long sttime = System.currentTimeMillis();
4057 ths.setProgressBar("Searching for sequences from " + fsrc, sttime);
4060 Alignment ds = ths.getViewport().alignment.getDataset(); // update
4064 Alignment prods = CrossRef
4065 .findXrefSequences(fsel, fdna, fsrc, ds);
4068 SequenceI[] sprods = new SequenceI[prods.getHeight()];
4069 for (int s = 0; s < sprods.length; s++)
4071 sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4072 if (ds.getSequences() == null
4073 || !ds.getSequences().contains(
4074 sprods[s].getDatasetSequence()))
4075 ds.addSequence(sprods[s].getDatasetSequence());
4076 sprods[s].updatePDBIds();
4078 Alignment al = new Alignment(sprods);
4079 AlignedCodonFrame[] cf = prods.getCodonFrames();
4081 for (int s = 0; cf != null && s < cf.length; s++)
4083 al.addCodonFrame(cf[s]);
4086 AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4088 String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4089 + " for " + ((fisRegSel) ? "selected region of " : "")
4091 Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4096 System.err.println("No Sequences generated for xRef type "
4099 } catch (Exception e)
4101 jalview.bin.Cache.log.error(
4102 "Exception when finding crossreferences", e);
4103 } catch (OutOfMemoryError e)
4105 new OOMWarning("whilst fetching crossreferences", e);
4108 jalview.bin.Cache.log.error("Error when finding crossreferences",
4111 ths.setProgressBar("Finished searching for sequences from " + fsrc,
4116 Thread frunner = new Thread(foo);
4120 public boolean canShowTranslationProducts(SequenceI[] selection,
4121 AlignmentI alignment)
4126 return (jalview.analysis.Dna.canTranslate(selection, viewport
4127 .getViewAsVisibleContigs(true)));
4128 } catch (Exception e)
4130 jalview.bin.Cache.log
4132 "canTranslate threw an exception - please report to help@jalview.org",
4138 public void showProducts_actionPerformed(ActionEvent e)
4140 // /////////////////////////////
4141 // Collect Data to be translated/transferred
4143 SequenceI[] selection = viewport.getSequenceSelection();
4144 AlignmentI al = null;
4147 al = jalview.analysis.Dna.CdnaTranslate(selection, viewport
4148 .getViewAsVisibleContigs(true), viewport.getGapCharacter(),
4149 viewport.getAlignment().getDataset());
4150 } catch (Exception ex)
4153 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4160 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4161 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4165 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4166 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4167 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4171 public void showTranslation_actionPerformed(ActionEvent e)
4173 // /////////////////////////////
4174 // Collect Data to be translated/transferred
4176 SequenceI[] selection = viewport.getSequenceSelection();
4177 String[] seqstring = viewport.getViewAsString(true);
4178 AlignmentI al = null;
4181 al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring,
4182 viewport.getViewAsVisibleContigs(true), viewport
4183 .getGapCharacter(), viewport.alignment
4184 .getAlignmentAnnotation(), viewport.alignment
4185 .getWidth(), viewport.getAlignment().getDataset());
4186 } catch (Exception ex)
4189 jalview.bin.Cache.log.debug("Exception during translation.", ex);
4196 "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
4197 "Translation Failed", JOptionPane.WARNING_MESSAGE);
4201 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4202 Desktop.addInternalFrame(af, "Translation of " + this.getTitle(),
4203 DEFAULT_WIDTH, DEFAULT_HEIGHT);
4208 * Try to load a features file onto the alignment.
4211 * contents or path to retrieve file
4213 * access mode of file (see jalview.io.AlignFile)
4214 * @return true if features file was parsed corectly.
4216 public boolean parseFeaturesFile(String file, String type)
4218 boolean featuresFile = false;
4221 featuresFile = new FeaturesFile(file, type).parse(viewport.alignment
4222 .getDataset(), alignPanel.seqPanel.seqCanvas
4223 .getFeatureRenderer().featureColours, false);
4224 } catch (Exception ex)
4226 ex.printStackTrace();
4231 viewport.showSequenceFeatures = true;
4232 showSeqFeatures.setSelected(true);
4233 if (alignPanel.seqPanel.seqCanvas.fr != null)
4235 // update the min/max ranges where necessary
4236 alignPanel.seqPanel.seqCanvas.fr.findAllFeatures(true);
4238 if (featureSettings != null)
4240 featureSettings.setTableData();
4242 alignPanel.paintAlignment(true);
4245 return featuresFile;
4248 public void dragEnter(DropTargetDragEvent evt)
4252 public void dragExit(DropTargetEvent evt)
4256 public void dragOver(DropTargetDragEvent evt)
4260 public void dropActionChanged(DropTargetDragEvent evt)
4264 public void drop(DropTargetDropEvent evt)
4266 Transferable t = evt.getTransferable();
4267 java.util.List files = null;
4271 DataFlavor uriListFlavor = new DataFlavor(
4272 "text/uri-list;class=java.lang.String");
4273 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4275 // Works on Windows and MacOSX
4276 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4277 files = (java.util.List) t
4278 .getTransferData(DataFlavor.javaFileListFlavor);
4280 else if (t.isDataFlavorSupported(uriListFlavor))
4282 // This is used by Unix drag system
4283 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4284 String data = (String) t.getTransferData(uriListFlavor);
4285 files = new java.util.ArrayList(1);
4286 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
4287 data, "\r\n"); st.hasMoreTokens();)
4289 String s = st.nextToken();
4290 if (s.startsWith("#"))
4292 // the line is a comment (as per the RFC 2483)
4296 java.net.URI uri = new java.net.URI(s);
4297 // check to see if we can handle this kind of URI
4298 if (uri.getScheme().toLowerCase().startsWith("http"))
4300 files.add(uri.toString());
4304 // otherwise preserve old behaviour: catch all for file objects
4305 java.io.File file = new java.io.File(uri);
4306 files.add(file.toString());
4310 } catch (Exception e)
4312 e.printStackTrace();
4319 for (int i = 0; i < files.size(); i++)
4321 loadJalviewDataFile(files.get(i).toString());
4323 } catch (Exception ex)
4325 ex.printStackTrace();
4331 * Attempt to load a "dropped" file or URL string: First by testing whether
4332 * it's and Annotation file, then a JNet file, and finally a features file. If
4333 * all are false then the user may have dropped an alignment file onto this
4337 * either a filename or a URL string.
4339 public void loadJalviewDataFile(String file)
4343 String protocol = jalview.io.FormatAdapter.FILE;
4344 String f = file.toLowerCase();
4345 if (f.indexOf("http:") == 0 || f.indexOf("https:") == 0
4346 || f.indexOf("file:") == 0)
4348 protocol = jalview.io.FormatAdapter.URL;
4351 boolean isAnnotation = new AnnotationFile().readAnnotationFile(
4352 viewport.alignment, file, protocol);
4356 // try to see if its a JNet 'concise' style annotation file *before* we
4357 // try to parse it as a features file
4358 String format = new IdentifyFile().Identify(file, protocol);
4359 if (format.equalsIgnoreCase("JnetFile"))
4361 jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
4363 new JnetAnnotationMaker().add_annotation(predictions, viewport
4364 .getAlignment(), 0, false);
4365 isAnnotation = true;
4369 // try to parse it as a features file
4370 boolean isGroupsFile = parseFeaturesFile(file, protocol);
4371 // if it wasn't a features file then we just treat it as a general
4372 // alignment file to load into the current view.
4375 new FileLoader().LoadFile(viewport, file, protocol, format);
4379 alignPanel.paintAlignment(true);
4386 alignPanel.adjustAnnotationHeight();
4387 viewport.updateSequenceIdColours();
4388 buildSortByAnnotationScoresMenu();
4389 alignPanel.paintAlignment(true);
4391 } catch (Exception ex)
4393 ex.printStackTrace();
4397 public void tabSelectionChanged(int index)
4401 alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
4402 viewport = alignPanel.av;
4403 setMenusFromViewport(viewport);
4407 public void tabbedPane_mousePressed(MouseEvent e)
4409 if (SwingUtilities.isRightMouseButton(e))
4411 String reply = JOptionPane.showInternalInputDialog(this,
4412 "Enter View Name", "Edit View Name",
4413 JOptionPane.QUESTION_MESSAGE);
4417 viewport.viewName = reply;
4418 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4423 public AlignViewport getCurrentView()
4429 * Open the dialog for regex description parsing.
4431 protected void extractScores_actionPerformed(ActionEvent e)
4433 ParseProperties pp = new jalview.analysis.ParseProperties(
4434 viewport.alignment);
4435 // TODO: verify regex and introduce GUI dialog for version 2.5
4436 // if (pp.getScoresFromDescription("col", "score column ",
4437 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4439 if (pp.getScoresFromDescription("description column",
4440 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4442 buildSortByAnnotationScoresMenu();
4450 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4453 protected void showDbRefs_actionPerformed(ActionEvent e)
4455 viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
4461 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4464 protected void showNpFeats_actionPerformed(ActionEvent e)
4466 viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
4470 * find the viewport amongst the tabs in this alignment frame and close that
4475 public boolean closeView(AlignViewport av)
4479 this.closeMenuItem_actionPerformed(false);
4482 Component[] comp = tabbedPane.getComponents();
4483 for (int i = 0; comp != null && i < comp.length; i++)
4485 if (comp[i] instanceof AlignmentPanel)
4487 if (((AlignmentPanel) comp[i]).av == av)
4490 closeView((AlignmentPanel) comp[i]);
4498 protected void build_fetchdbmenu(JMenu webService)
4500 // Temporary hack - DBRef Fetcher always top level ws entry.
4501 // TODO We probably want to store a sequence database checklist in
4502 // preferences and have checkboxes.. rather than individual sources selected
4504 JMenu rfetch = new JMenu("Fetch DB References");
4506 .setToolTipText("Retrieve and parse sequence database records for the alignment or the currently selected sequences");
4507 webService.add(rfetch);
4509 JMenuItem fetchr = new JMenuItem("Standard Databases");
4511 .setToolTipText("Fetch from EMBL/EMBLCDS or Uniprot/PDB and any selected DAS sources");
4512 fetchr.addActionListener(new ActionListener()
4515 public void actionPerformed(ActionEvent e)
4517 new Thread(new Runnable()
4522 new jalview.ws.DBRefFetcher(alignPanel.av
4523 .getSequenceSelection(), alignPanel.alignFrame)
4524 .fetchDBRefs(false);
4532 JMenu dfetch = new JMenu();
4534 jalview.ws.SequenceFetcher sf = SequenceFetcher
4535 .getSequenceFetcherSingleton(this);
4536 String[] otherdb = sf.getOrderedSupportedSources();
4537 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4538 // jalview.util.QuickSort.sort(otherdb, otherdb);
4539 int comp = 0, mcomp = 15;
4540 String mname = null;
4541 if (otherdb != null && otherdb.length > 0)
4543 for (int i = 0; i < otherdb.length; i++)
4545 String dbname = sf.getSourceProxy(otherdb[i]).getDbName();
4548 mname = "from '" + dbname + "'";
4550 fetchr = new JMenuItem(otherdb[i]);
4551 final String[] dassource = new String[]
4553 fetchr.addActionListener(new ActionListener()
4556 public void actionPerformed(ActionEvent e)
4558 new Thread(new Runnable()
4563 new jalview.ws.DBRefFetcher(alignPanel.av
4564 .getSequenceSelection(), alignPanel.alignFrame,
4565 dassource).fetchDBRefs(false);
4571 fetchr.setToolTipText("Retrieve from " + dbname);
4573 if (comp++ == mcomp || i == (otherdb.length - 1))
4575 dfetch.setText(mname + " to '" + dbname + "'");
4577 dfetch = new JMenu();
4586 * Left justify the whole alignment.
4588 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
4590 AlignmentI al = viewport.getAlignment();
4592 viewport.firePropertyChange("alignment", null, al);
4596 * Right justify the whole alignment.
4598 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
4600 AlignmentI al = viewport.getAlignment();
4602 viewport.firePropertyChange("alignment", null, al);
4605 public void setShowSeqFeatures(boolean b)
4607 showSeqFeatures.setSelected(true);
4608 viewport.setShowSequenceFeatures(true);
4615 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
4616 * awt.event.ActionEvent)
4618 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
4620 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
4621 alignPanel.paintAlignment(true);
4628 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
4631 protected void showGroupConsensus_actionPerformed(ActionEvent e)
4633 viewport.setShowGroupConsensus(showGroupConsensus.getState());
4634 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4642 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
4643 * .event.ActionEvent)
4645 protected void showGroupConservation_actionPerformed(ActionEvent e)
4647 viewport.setShowGroupConservation(showGroupConservation.getState());
4648 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4655 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
4656 * .event.ActionEvent)
4658 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
4660 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
4661 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4668 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
4669 * .event.ActionEvent)
4671 protected void showSequenceLogo_actionPerformed(ActionEvent e)
4673 viewport.setShowSequenceLogo(showSequenceLogo.getState());
4674 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4677 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
4679 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
4686 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
4687 * .event.ActionEvent)
4689 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
4691 if (viewport.getSelectionGroup() != null)
4693 SequenceGroup[] gps = jalview.analysis.Grouping.makeGroupsFrom(
4694 viewport.getSequenceSelection(), viewport.getAlignmentView(
4695 true).getSequenceStrings(viewport.getGapCharacter()),
4696 viewport.alignment.getGroups());
4697 viewport.alignment.deleteAllGroups();
4698 viewport.sequenceColours = null;
4699 viewport.setSelectionGroup(null);
4700 // set view properties for each group
4701 for (int g = 0; g < gps.length; g++)
4703 gps[g].setShowNonconserved(viewport.getShowUnconserved());
4704 gps[g].setshowSequenceLogo(viewport.isShowSequenceLogo());
4705 viewport.alignment.addGroup(gps[g]);
4706 Color col = new Color((int) (Math.random() * 255), (int) (Math
4707 .random() * 255), (int) (Math.random() * 255));
4708 col = col.brighter();
4709 for (Enumeration sq = gps[g].getSequences(null).elements(); sq
4710 .hasMoreElements(); viewport.setSequenceColour(
4711 (SequenceI) sq.nextElement(), col))
4714 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
4715 alignPanel.updateAnnotation();
4716 alignPanel.paintAlignment(true);
4721 class PrintThread extends Thread
4725 public PrintThread(AlignmentPanel ap)
4730 static PageFormat pf;
4734 PrinterJob printJob = PrinterJob.getPrinterJob();
4738 printJob.setPrintable(ap, pf);
4742 printJob.setPrintable(ap);
4745 if (printJob.printDialog())
4750 } catch (Exception PrintException)
4752 PrintException.printStackTrace();