2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.SimilarityParamsI;
39 import jalview.bin.Cache;
40 import jalview.bin.Jalview;
41 import jalview.commands.CommandI;
42 import jalview.commands.EditCommand;
43 import jalview.commands.EditCommand.Action;
44 import jalview.commands.OrderCommand;
45 import jalview.commands.RemoveGapColCommand;
46 import jalview.commands.RemoveGapsCommand;
47 import jalview.commands.SlideSequencesCommand;
48 import jalview.commands.TrimRegionCommand;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.hmmer.HMMAlign;
67 import jalview.hmmer.HMMBuild;
68 import jalview.hmmer.HMMERParamStore;
69 import jalview.hmmer.HMMERPreset;
70 import jalview.hmmer.HMMSearch;
71 import jalview.hmmer.HmmerCommand;
72 import jalview.hmmer.JackHMMER;
73 import jalview.io.AlignmentProperties;
74 import jalview.io.AnnotationFile;
75 import jalview.io.BackupFiles;
76 import jalview.io.BioJsHTMLOutput;
77 import jalview.io.DataSourceType;
78 import jalview.io.FileFormat;
79 import jalview.io.FileFormatI;
80 import jalview.io.FileFormats;
81 import jalview.io.FileLoader;
82 import jalview.io.FileParse;
83 import jalview.io.FormatAdapter;
84 import jalview.io.HtmlSvgOutput;
85 import jalview.io.IdentifyFile;
86 import jalview.io.JPredFile;
87 import jalview.io.JalviewFileChooser;
88 import jalview.io.JalviewFileView;
89 import jalview.io.JnetAnnotationMaker;
90 import jalview.io.NewickFile;
91 import jalview.io.ScoreMatrixFile;
92 import jalview.io.TCoffeeScoreFile;
93 import jalview.io.vcf.VCFLoader;
94 import jalview.jbgui.GAlignFrame;
95 import jalview.schemes.ColourSchemeI;
96 import jalview.schemes.ColourSchemes;
97 import jalview.schemes.ResidueColourScheme;
98 import jalview.schemes.TCoffeeColourScheme;
99 import jalview.util.MessageManager;
100 import jalview.viewmodel.AlignmentViewport;
101 import jalview.viewmodel.ViewportRanges;
102 import jalview.ws.DBRefFetcher;
103 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
104 import jalview.ws.jws1.Discoverer;
105 import jalview.ws.jws2.Jws2Discoverer;
106 import jalview.ws.jws2.jabaws2.Jws2Instance;
107 import jalview.ws.params.ArgumentI;
108 import jalview.ws.params.ParamDatastoreI;
109 import jalview.ws.params.WsParamSetI;
110 import jalview.ws.seqfetcher.DbSourceProxy;
112 import java.awt.BorderLayout;
113 import java.awt.Component;
114 import java.awt.Rectangle;
115 import java.awt.Toolkit;
116 import java.awt.datatransfer.Clipboard;
117 import java.awt.datatransfer.DataFlavor;
118 import java.awt.datatransfer.StringSelection;
119 import java.awt.datatransfer.Transferable;
120 import java.awt.dnd.DnDConstants;
121 import java.awt.dnd.DropTargetDragEvent;
122 import java.awt.dnd.DropTargetDropEvent;
123 import java.awt.dnd.DropTargetEvent;
124 import java.awt.dnd.DropTargetListener;
125 import java.awt.event.ActionEvent;
126 import java.awt.event.ActionListener;
127 import java.awt.event.FocusAdapter;
128 import java.awt.event.FocusEvent;
129 import java.awt.event.ItemEvent;
130 import java.awt.event.ItemListener;
131 import java.awt.event.KeyAdapter;
132 import java.awt.event.KeyEvent;
133 import java.awt.event.MouseEvent;
134 import java.awt.print.PageFormat;
135 import java.awt.print.PrinterJob;
136 import java.beans.PropertyChangeEvent;
138 import java.io.FileWriter;
139 import java.io.IOException;
140 import java.io.PrintWriter;
142 import java.util.ArrayList;
143 import java.util.Arrays;
144 import java.util.Deque;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Set;
148 import java.util.Vector;
150 import javax.swing.ButtonGroup;
151 import javax.swing.JCheckBoxMenuItem;
152 import javax.swing.JEditorPane;
153 import javax.swing.JFileChooser;
154 import javax.swing.JInternalFrame;
155 import javax.swing.JLayeredPane;
156 import javax.swing.JMenu;
157 import javax.swing.JMenuItem;
158 import javax.swing.JOptionPane;
159 import javax.swing.JScrollPane;
160 import javax.swing.SwingUtilities;
166 * @version $Revision$
168 public class AlignFrame extends GAlignFrame implements DropTargetListener,
169 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
171 public static final int DEFAULT_WIDTH = 700;
173 public static final int DEFAULT_HEIGHT = 500;
176 * The currently displayed panel (selected tabbed view if more than one)
178 public AlignmentPanel alignPanel;
180 AlignViewport viewport;
182 public AlignViewControllerI avc;
184 List<AlignmentPanel> alignPanels = new ArrayList<>();
187 * Last format used to load or save alignments in this window
189 FileFormatI currentFileFormat = null;
192 * Current filename for this alignment
194 String fileName = null;
198 * Creates a new AlignFrame object with specific width and height.
204 public AlignFrame(AlignmentI al, int width, int height)
206 this(al, null, width, height);
210 * Creates a new AlignFrame object with specific width, height and
216 * @param sequenceSetId
218 public AlignFrame(AlignmentI al, int width, int height,
219 String sequenceSetId)
221 this(al, null, width, height, sequenceSetId);
225 * Creates a new AlignFrame object with specific width, height and
231 * @param sequenceSetId
234 public AlignFrame(AlignmentI al, int width, int height,
235 String sequenceSetId, String viewId)
237 this(al, null, width, height, sequenceSetId, viewId);
241 * new alignment window with hidden columns
245 * @param hiddenColumns
246 * ColumnSelection or null
248 * Width of alignment frame
252 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
255 this(al, hiddenColumns, width, height, null);
259 * Create alignment frame for al with hiddenColumns, a specific width and
260 * height, and specific sequenceId
263 * @param hiddenColumns
266 * @param sequenceSetId
269 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
270 int height, String sequenceSetId)
272 this(al, hiddenColumns, width, height, sequenceSetId, null);
276 * Create alignment frame for al with hiddenColumns, a specific width and
277 * height, and specific sequenceId
280 * @param hiddenColumns
283 * @param sequenceSetId
288 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
289 int height, String sequenceSetId, String viewId)
291 setSize(width, height);
293 if (al.getDataset() == null)
298 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
300 alignPanel = new AlignmentPanel(this, viewport);
302 addAlignmentPanel(alignPanel, true);
306 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
307 HiddenColumns hiddenColumns, int width, int height)
309 setSize(width, height);
311 if (al.getDataset() == null)
316 viewport = new AlignViewport(al, hiddenColumns);
318 if (hiddenSeqs != null && hiddenSeqs.length > 0)
320 viewport.hideSequence(hiddenSeqs);
322 alignPanel = new AlignmentPanel(this, viewport);
323 addAlignmentPanel(alignPanel, true);
328 * Make a new AlignFrame from existing alignmentPanels
335 public AlignFrame(AlignmentPanel ap)
339 addAlignmentPanel(ap, false);
344 * initalise the alignframe from the underlying viewport data and the
349 if (!Jalview.isHeadlessMode())
351 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
354 avc = new jalview.controller.AlignViewController(this, viewport,
356 if (viewport.getAlignmentConservationAnnotation() == null)
358 // BLOSUM62Colour.setEnabled(false);
359 conservationMenuItem.setEnabled(false);
360 modifyConservation.setEnabled(false);
361 // PIDColour.setEnabled(false);
362 // abovePIDThreshold.setEnabled(false);
363 // modifyPID.setEnabled(false);
366 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
369 if (sortby.equals("Id"))
371 sortIDMenuItem_actionPerformed(null);
373 else if (sortby.equals("Pairwise Identity"))
375 sortPairwiseMenuItem_actionPerformed(null);
379 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
381 setMenusFromViewport(viewport);
382 buildSortByAnnotationScoresMenu();
383 calculateTree.addActionListener(new ActionListener()
387 public void actionPerformed(ActionEvent e)
394 if (Desktop.desktop != null)
396 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
397 addServiceListeners();
401 if (viewport.getWrapAlignment())
403 wrapMenuItem_actionPerformed(null);
406 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
408 this.overviewMenuItem_actionPerformed(null);
413 final List<AlignmentPanel> selviews = new ArrayList<>();
414 final List<AlignmentPanel> origview = new ArrayList<>();
415 final String menuLabel = MessageManager
416 .getString("label.copy_format_from");
417 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
418 new ViewSetProvider()
422 public AlignmentPanel[] getAllAlignmentPanels()
425 origview.add(alignPanel);
426 // make an array of all alignment panels except for this one
427 List<AlignmentPanel> aps = new ArrayList<>(
428 Arrays.asList(Desktop.getAlignmentPanels(null)));
429 aps.remove(AlignFrame.this.alignPanel);
430 return aps.toArray(new AlignmentPanel[aps.size()]);
432 }, selviews, new ItemListener()
436 public void itemStateChanged(ItemEvent e)
438 if (origview.size() > 0)
440 final AlignmentPanel ap = origview.get(0);
443 * Copy the ViewStyle of the selected panel to 'this one'.
444 * Don't change value of 'scaleProteinAsCdna' unless copying
447 ViewStyleI vs = selviews.get(0).getAlignViewport()
449 boolean fromSplitFrame = selviews.get(0)
450 .getAlignViewport().getCodingComplement() != null;
453 vs.setScaleProteinAsCdna(ap.getAlignViewport()
454 .getViewStyle().isScaleProteinAsCdna());
456 ap.getAlignViewport().setViewStyle(vs);
459 * Also rescale ViewStyle of SplitFrame complement if there is
460 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
461 * the whole ViewStyle (allow cDNA protein to have different
464 AlignViewportI complement = ap.getAlignViewport()
465 .getCodingComplement();
466 if (complement != null && vs.isScaleProteinAsCdna())
468 AlignFrame af = Desktop.getAlignFrameFor(complement);
469 ((SplitFrame) af.getSplitViewContainer())
471 af.setMenusForViewport();
475 ap.setSelected(true);
476 ap.alignFrame.setMenusForViewport();
481 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
482 .indexOf("devel") > -1
483 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
484 .indexOf("test") > -1)
486 formatMenu.add(vsel);
488 addFocusListener(new FocusAdapter()
491 public void focusGained(FocusEvent e)
493 Jalview.setCurrentAlignFrame(AlignFrame.this);
500 * Change the filename and format for the alignment, and enable the 'reload'
501 * button functionality.
508 public void setFileName(String file, FileFormatI format)
511 setFileFormat(format);
512 reload.setEnabled(true);
516 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
519 void addKeyListener()
521 addKeyListener(new KeyAdapter()
524 public void keyPressed(KeyEvent evt)
526 if (viewport.cursorMode
527 && ((evt.getKeyCode() >= KeyEvent.VK_0
528 && evt.getKeyCode() <= KeyEvent.VK_9)
529 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
530 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
531 && Character.isDigit(evt.getKeyChar()))
533 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
536 switch (evt.getKeyCode())
539 case 27: // escape key
540 deselectAllSequenceMenuItem_actionPerformed(null);
544 case KeyEvent.VK_DOWN:
545 if (evt.isAltDown() || !viewport.cursorMode)
547 moveSelectedSequences(false);
549 if (viewport.cursorMode)
551 alignPanel.getSeqPanel().moveCursor(0, 1);
556 if (evt.isAltDown() || !viewport.cursorMode)
558 moveSelectedSequences(true);
560 if (viewport.cursorMode)
562 alignPanel.getSeqPanel().moveCursor(0, -1);
567 case KeyEvent.VK_LEFT:
568 if (evt.isAltDown() || !viewport.cursorMode)
570 slideSequences(false,
571 alignPanel.getSeqPanel().getKeyboardNo1());
575 alignPanel.getSeqPanel().moveCursor(-1, 0);
580 case KeyEvent.VK_RIGHT:
581 if (evt.isAltDown() || !viewport.cursorMode)
583 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
587 alignPanel.getSeqPanel().moveCursor(1, 0);
591 case KeyEvent.VK_SPACE:
592 if (viewport.cursorMode)
594 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
595 || evt.isShiftDown() || evt.isAltDown());
599 // case KeyEvent.VK_A:
600 // if (viewport.cursorMode)
602 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
603 // //System.out.println("A");
607 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
608 * System.out.println("closing bracket"); } break;
610 case KeyEvent.VK_DELETE:
611 case KeyEvent.VK_BACK_SPACE:
612 if (!viewport.cursorMode)
614 cut_actionPerformed(null);
618 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
619 || evt.isShiftDown() || evt.isAltDown());
625 if (viewport.cursorMode)
627 alignPanel.getSeqPanel().setCursorRow();
631 if (viewport.cursorMode && !evt.isControlDown())
633 alignPanel.getSeqPanel().setCursorColumn();
637 if (viewport.cursorMode)
639 alignPanel.getSeqPanel().setCursorPosition();
643 case KeyEvent.VK_ENTER:
644 case KeyEvent.VK_COMMA:
645 if (viewport.cursorMode)
647 alignPanel.getSeqPanel().setCursorRowAndColumn();
652 if (viewport.cursorMode)
654 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
658 if (viewport.cursorMode)
660 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
665 viewport.cursorMode = !viewport.cursorMode;
666 statusBar.setText(MessageManager
667 .formatMessage("label.keyboard_editing_mode", new String[]
668 { (viewport.cursorMode ? "on" : "off") }));
669 if (viewport.cursorMode)
671 ViewportRanges ranges = viewport.getRanges();
672 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
674 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
677 alignPanel.getSeqPanel().seqCanvas.repaint();
683 Help.showHelpWindow();
684 } catch (Exception ex)
686 ex.printStackTrace();
691 boolean toggleSeqs = !evt.isControlDown();
692 boolean toggleCols = !evt.isShiftDown();
693 toggleHiddenRegions(toggleSeqs, toggleCols);
698 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
699 boolean modifyExisting = true; // always modify, don't clear
700 // evt.isShiftDown();
701 boolean invertHighlighted = evt.isAltDown();
702 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
706 case KeyEvent.VK_PAGE_UP:
707 viewport.getRanges().pageUp();
709 case KeyEvent.VK_PAGE_DOWN:
710 viewport.getRanges().pageDown();
716 public void keyReleased(KeyEvent evt)
718 switch (evt.getKeyCode())
720 case KeyEvent.VK_LEFT:
721 if (evt.isAltDown() || !viewport.cursorMode)
723 viewport.firePropertyChange("alignment", null,
724 viewport.getAlignment().getSequences());
728 case KeyEvent.VK_RIGHT:
729 if (evt.isAltDown() || !viewport.cursorMode)
731 viewport.firePropertyChange("alignment", null,
732 viewport.getAlignment().getSequences());
740 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
742 ap.alignFrame = this;
743 avc = new jalview.controller.AlignViewController(this, viewport,
748 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
750 int aSize = alignPanels.size();
752 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
754 if (aSize == 1 && ap.av.getViewName() == null)
756 this.getContentPane().add(ap, BorderLayout.CENTER);
762 setInitialTabVisible();
765 expandViews.setEnabled(true);
766 gatherViews.setEnabled(true);
767 tabbedPane.addTab(ap.av.getViewName(), ap);
769 ap.setVisible(false);
774 if (ap.av.isPadGaps())
776 ap.av.getAlignment().padGaps();
778 ap.av.updateConservation(ap);
779 ap.av.updateConsensus(ap);
780 ap.av.updateStrucConsensus(ap);
781 ap.av.initInformationWorker(ap);
785 public void setInitialTabVisible()
787 expandViews.setEnabled(true);
788 gatherViews.setEnabled(true);
789 tabbedPane.setVisible(true);
790 AlignmentPanel first = alignPanels.get(0);
791 tabbedPane.addTab(first.av.getViewName(), first);
792 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
795 public AlignViewport getViewport()
800 /* Set up intrinsic listeners for dynamically generated GUI bits. */
801 private void addServiceListeners()
803 final java.beans.PropertyChangeListener thisListener;
804 Desktop.instance.addJalviewPropertyChangeListener("services",
805 thisListener = new java.beans.PropertyChangeListener()
808 public void propertyChange(PropertyChangeEvent evt)
810 // // System.out.println("Discoverer property change.");
811 // if (evt.getPropertyName().equals("services"))
813 SwingUtilities.invokeLater(new Runnable()
820 "Rebuild WS Menu for service change");
821 BuildWebServiceMenu();
828 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
831 public void internalFrameClosed(
832 javax.swing.event.InternalFrameEvent evt)
834 // System.out.println("deregistering discoverer listener");
835 Desktop.instance.removeJalviewPropertyChangeListener("services",
837 closeMenuItem_actionPerformed(true);
840 // Finally, build the menu once to get current service state
841 new Thread(new Runnable()
846 BuildWebServiceMenu();
852 * Configure menu items that vary according to whether the alignment is
853 * nucleotide or protein
855 public void setGUINucleotide()
857 AlignmentI al = getViewport().getAlignment();
858 boolean nucleotide = al.isNucleotide();
860 loadVcf.setVisible(nucleotide);
861 showTranslation.setVisible(nucleotide);
862 showReverse.setVisible(nucleotide);
863 showReverseComplement.setVisible(nucleotide);
864 conservationMenuItem.setEnabled(!nucleotide);
866 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
867 showGroupConservation.setEnabled(!nucleotide);
869 showComplementMenuItem
870 .setText(nucleotide ? MessageManager.getString("label.protein")
871 : MessageManager.getString("label.nucleotide"));
875 * set up menus for the current viewport. This may be called after any
876 * operation that affects the data in the current view (selection changed,
877 * etc) to update the menus to reflect the new state.
880 public void setMenusForViewport()
882 setMenusFromViewport(viewport);
886 * Need to call this method when tabs are selected for multiple views, or when
887 * loading from Jalview2XML.java
892 public void setMenusFromViewport(AlignViewport av)
894 padGapsMenuitem.setSelected(av.isPadGaps());
895 colourTextMenuItem.setSelected(av.isShowColourText());
896 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
897 modifyPID.setEnabled(abovePIDThreshold.isSelected());
898 conservationMenuItem.setSelected(av.getConservationSelected());
899 modifyConservation.setEnabled(conservationMenuItem.isSelected());
900 seqLimits.setSelected(av.getShowJVSuffix());
901 idRightAlign.setSelected(av.isRightAlignIds());
902 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
903 renderGapsMenuItem.setSelected(av.isRenderGaps());
904 wrapMenuItem.setSelected(av.getWrapAlignment());
905 scaleAbove.setVisible(av.getWrapAlignment());
906 scaleLeft.setVisible(av.getWrapAlignment());
907 scaleRight.setVisible(av.getWrapAlignment());
908 annotationPanelMenuItem.setState(av.isShowAnnotation());
910 * Show/hide annotations only enabled if annotation panel is shown
912 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
913 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
914 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
915 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
916 viewBoxesMenuItem.setSelected(av.getShowBoxes());
917 viewTextMenuItem.setSelected(av.getShowText());
918 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
919 showGroupConsensus.setSelected(av.isShowGroupConsensus());
920 showGroupConservation.setSelected(av.isShowGroupConservation());
921 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
922 showSequenceLogo.setSelected(av.isShowSequenceLogo());
923 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
924 showInformationHistogram.setSelected(av.isShowInformationHistogram());
925 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
926 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
928 ColourMenuHelper.setColourSelected(colourMenu,
929 av.getGlobalColourScheme());
931 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
932 hiddenMarkers.setState(av.getShowHiddenMarkers());
933 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
934 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
935 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
936 autoCalculate.setSelected(av.autoCalculateConsensus);
937 sortByTree.setSelected(av.sortByTree);
938 listenToViewSelections.setSelected(av.followSelection);
940 showProducts.setEnabled(canShowProducts());
941 setGroovyEnabled(Desktop.getGroovyConsole() != null);
947 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
951 public void setGroovyEnabled(boolean b)
953 runGroovy.setEnabled(b);
956 private IProgressIndicator progressBar;
961 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
964 public void setProgressBar(String message, long id)
966 progressBar.setProgressBar(message, id);
970 public void registerHandler(final long id,
971 final IProgressIndicatorHandler handler)
973 progressBar.registerHandler(id, handler);
978 * @return true if any progress bars are still active
981 public boolean operationInProgress()
983 return progressBar.operationInProgress();
987 * Sets the text of the status bar. Note that setting a null or empty value
988 * will cause the status bar to be hidden, with possibly undesirable flicker
989 * of the screen layout.
992 public void setStatus(String text)
994 statusBar.setText(text == null || text.isEmpty() ? " " : text);
998 * Added so Castor Mapping file can obtain Jalview Version
1000 public String getVersion()
1002 return jalview.bin.Cache.getProperty("VERSION");
1005 public FeatureRenderer getFeatureRenderer()
1007 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1011 public void fetchSequence_actionPerformed(ActionEvent e)
1013 new jalview.gui.SequenceFetcher(this);
1017 public void addFromFile_actionPerformed(ActionEvent e)
1019 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1023 public void hmmBuild_actionPerformed(boolean withDefaults)
1025 if (!alignmentIsSufficient(1))
1031 * get default parameters, and optionally show a dialog
1032 * to allow them to be modified
1034 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1035 List<ArgumentI> args = store.getServiceParameters();
1039 WsParamSetI set = new HMMERPreset();
1040 WsJobParameters params = new WsJobParameters(store, set, args);
1041 if (params.showRunDialog())
1043 args = params.getJobParams();
1047 return; // user cancelled
1050 new Thread(new HMMBuild(this, args)).start();
1054 public void hmmAlign_actionPerformed(boolean withDefaults)
1056 if (!(checkForHMM() && alignmentIsSufficient(2)))
1062 * get default parameters, and optionally show a dialog
1063 * to allow them to be modified
1065 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1066 List<ArgumentI> args = store.getServiceParameters();
1070 WsParamSetI set = new HMMERPreset();
1071 WsJobParameters params = new WsJobParameters(store, set, args);
1072 if (params.showRunDialog())
1074 args = params.getJobParams();
1078 return; // user cancelled
1081 new Thread(new HMMAlign(this, args)).start();
1085 public void hmmSearch_actionPerformed(boolean withDefaults)
1093 * get default parameters, and (if requested) show
1094 * dialog to allow modification
1096 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1097 List<ArgumentI> args = store.getServiceParameters();
1101 WsParamSetI set = new HMMERPreset();
1102 WsJobParameters params = new WsJobParameters(store, set, args);
1103 if (params.showRunDialog())
1105 args = params.getJobParams();
1109 return; // user cancelled
1112 new Thread(new HMMSearch(this, args)).start();
1113 alignPanel.repaint();
1117 public void jackhmmer_actionPerformed(boolean withDefaults)
1121 * get default parameters, and (if requested) show
1122 * dialog to allow modification
1125 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1126 List<ArgumentI> args = store.getServiceParameters();
1130 WsParamSetI set = new HMMERPreset();
1131 WsJobParameters params = new WsJobParameters(store, set, args);
1132 if (params.showRunDialog())
1134 args = params.getJobParams();
1138 return; // user cancelled
1141 new Thread(new JackHMMER(this, args)).start();
1142 alignPanel.repaint();
1147 * Checks if the alignment has at least one hidden Markov model, if not shows
1148 * a dialog advising to run hmmbuild or load an HMM profile
1152 private boolean checkForHMM()
1154 if (viewport.getAlignment().getHmmSequences().isEmpty())
1156 JOptionPane.showMessageDialog(this,
1157 MessageManager.getString("warn.no_hmm"));
1164 protected void filterByEValue_actionPerformed()
1166 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1170 protected void filterByScore_actionPerformed()
1172 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1175 private double inputDouble(String message)
1179 while(d == null || d <= 0)
1181 str = JOptionPane.showInputDialog(this.alignPanel, message);
1184 d = Double.valueOf(str);
1186 catch (NumberFormatException e)
1194 * Checks if the alignment contains the required number of sequences.
1199 public boolean alignmentIsSufficient(int required)
1201 if (getViewport().getAlignment().getSequences().size() < required)
1203 JOptionPane.showMessageDialog(this,
1204 MessageManager.getString("label.not_enough_sequences"));
1211 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1212 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1213 * comma-separated list)
1216 public void addDatabase_actionPerformed() throws IOException
1218 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1220 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1223 String path = openFileChooser(false);
1224 if (path != null && new File(path).exists())
1226 IdentifyFile identifier = new IdentifyFile();
1227 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1228 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1229 || format == FileFormat.Pfam)
1231 String currentDbPaths = Cache
1232 .getProperty(Preferences.HMMSEARCH_DBS);
1233 currentDbPaths += Preferences.COMMA + path;
1234 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1238 JOptionPane.showMessageDialog(this,
1239 MessageManager.getString("warn.invalid_format"));
1245 * Opens a file chooser, optionally restricted to selecting folders
1246 * (directories) only. Answers the path to the selected file or folder, or
1247 * null if none is chosen.
1252 protected String openFileChooser(boolean forFolder)
1254 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1255 String choice = null;
1256 JFileChooser chooser = new JFileChooser();
1259 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1261 chooser.setDialogTitle(
1262 MessageManager.getString("label.open_local_file"));
1263 chooser.setToolTipText(MessageManager.getString("action.open"));
1265 int value = chooser.showOpenDialog(this);
1267 if (value == JFileChooser.APPROVE_OPTION)
1269 choice = chooser.getSelectedFile().getPath();
1275 public void reload_actionPerformed(ActionEvent e)
1277 if (fileName != null)
1279 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1280 // originating file's format
1281 // TODO: work out how to recover feature settings for correct view(s) when
1282 // file is reloaded.
1283 if (FileFormat.Jalview.equals(currentFileFormat))
1285 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1286 for (int i = 0; i < frames.length; i++)
1288 if (frames[i] instanceof AlignFrame && frames[i] != this
1289 && ((AlignFrame) frames[i]).fileName != null
1290 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1294 frames[i].setSelected(true);
1295 Desktop.instance.closeAssociatedWindows();
1296 } catch (java.beans.PropertyVetoException ex)
1302 Desktop.instance.closeAssociatedWindows();
1304 FileLoader loader = new FileLoader();
1305 DataSourceType protocol = fileName.startsWith("http:")
1306 ? DataSourceType.URL
1307 : DataSourceType.FILE;
1308 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1312 Rectangle bounds = this.getBounds();
1314 FileLoader loader = new FileLoader();
1315 DataSourceType protocol = fileName.startsWith("http:")
1316 ? DataSourceType.URL
1317 : DataSourceType.FILE;
1318 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1319 protocol, currentFileFormat);
1321 newframe.setBounds(bounds);
1322 if (featureSettings != null && featureSettings.isShowing())
1324 final Rectangle fspos = featureSettings.frame.getBounds();
1325 // TODO: need a 'show feature settings' function that takes bounds -
1326 // need to refactor Desktop.addFrame
1327 newframe.featureSettings_actionPerformed(null);
1328 final FeatureSettings nfs = newframe.featureSettings;
1329 SwingUtilities.invokeLater(new Runnable()
1334 nfs.frame.setBounds(fspos);
1337 this.featureSettings.close();
1338 this.featureSettings = null;
1340 this.closeMenuItem_actionPerformed(true);
1346 public void addFromText_actionPerformed(ActionEvent e)
1349 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1353 public void addFromURL_actionPerformed(ActionEvent e)
1355 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1359 public void save_actionPerformed(ActionEvent e)
1361 if (fileName == null || (currentFileFormat == null)
1362 || fileName.startsWith("http"))
1364 saveAs_actionPerformed(null);
1368 saveAlignment(fileName, currentFileFormat);
1379 public void saveAs_actionPerformed(ActionEvent e)
1381 String format = currentFileFormat == null ? null
1382 : currentFileFormat.getName();
1383 JalviewFileChooser chooser = JalviewFileChooser
1384 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1386 chooser.setFileView(new JalviewFileView());
1387 chooser.setDialogTitle(
1388 MessageManager.getString("label.save_alignment_to_file"));
1389 chooser.setToolTipText(MessageManager.getString("action.save"));
1391 int value = chooser.showSaveDialog(this);
1393 if (value == JalviewFileChooser.APPROVE_OPTION)
1395 currentFileFormat = chooser.getSelectedFormat();
1396 while (currentFileFormat == null)
1398 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1399 MessageManager.getString(
1400 "label.select_file_format_before_saving"),
1401 MessageManager.getString("label.file_format_not_specified"),
1402 JvOptionPane.WARNING_MESSAGE);
1403 currentFileFormat = chooser.getSelectedFormat();
1404 value = chooser.showSaveDialog(this);
1405 if (value != JalviewFileChooser.APPROVE_OPTION)
1411 fileName = chooser.getSelectedFile().getPath();
1413 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1415 Cache.setProperty("LAST_DIRECTORY", fileName);
1416 saveAlignment(fileName, currentFileFormat);
1420 public boolean saveAlignment(String file, FileFormatI format)
1422 boolean success = true;
1424 if (FileFormat.Jalview.equals(format))
1426 String shortName = title;
1428 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1430 shortName = shortName.substring(
1431 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1434 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1437 statusBar.setText(MessageManager.formatMessage(
1438 "label.successfully_saved_to_file_in_format", new Object[]
1439 { fileName, format }));
1444 AlignmentExportData exportData = getAlignmentForExport(format,
1446 if (exportData.getSettings().isCancelled())
1450 FormatAdapter f = new FormatAdapter(alignPanel,
1451 exportData.getSettings());
1452 String output = f.formatSequences(format, exportData.getAlignment(), // class
1456 // occur in the distant future
1457 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1458 f.getCacheSuffixDefault(format),
1459 viewport.getAlignment().getHiddenColumns());
1467 // create backupfiles object and get new temp filename destination
1468 BackupFiles backupfiles = new BackupFiles(file);
1472 PrintWriter out = new PrintWriter(
1473 new FileWriter(backupfiles.getTempFilePath()));
1477 this.setTitle(file);
1478 statusBar.setText(MessageManager.formatMessage(
1479 "label.successfully_saved_to_file_in_format", new Object[]
1480 { fileName, format.getName() }));
1481 } catch (Exception ex)
1484 ex.printStackTrace();
1487 backupfiles.setWriteSuccess(success);
1488 // do the backup file roll and rename the temp file to actual file
1489 success = backupfiles.rollBackupsAndRenameTempFile();
1496 JvOptionPane.showInternalMessageDialog(this, MessageManager
1497 .formatMessage("label.couldnt_save_file", new Object[]
1499 MessageManager.getString("label.error_saving_file"),
1500 JvOptionPane.WARNING_MESSAGE);
1506 private void warningMessage(String warning, String title)
1508 if (new jalview.util.Platform().isHeadless())
1510 System.err.println("Warning: " + title + "\nWarning: " + warning);
1515 JvOptionPane.showInternalMessageDialog(this, warning, title,
1516 JvOptionPane.WARNING_MESSAGE);
1528 protected void outputText_actionPerformed(ActionEvent e)
1530 FileFormatI fileFormat = FileFormats.getInstance()
1531 .forName(e.getActionCommand());
1532 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1534 if (exportData.getSettings().isCancelled())
1538 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1539 cap.setForInput(null);
1542 FileFormatI format = fileFormat;
1543 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1544 .formatSequences(format, exportData.getAlignment(),
1545 exportData.getOmitHidden(),
1546 exportData.getStartEndPostions(),
1547 viewport.getAlignment().getHiddenColumns()));
1548 Desktop.addInternalFrame(cap, MessageManager
1549 .formatMessage("label.alignment_output_command", new Object[]
1550 { e.getActionCommand() }), 600, 500);
1551 } catch (OutOfMemoryError oom)
1553 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1560 public static AlignmentExportData getAlignmentForExport(
1561 FileFormatI format, AlignViewportI viewport,
1562 AlignExportSettingI exportSettings)
1564 AlignmentI alignmentToExport = null;
1565 AlignExportSettingI settings = exportSettings;
1566 String[] omitHidden = null;
1568 HiddenSequences hiddenSeqs = viewport.getAlignment()
1569 .getHiddenSequences();
1571 alignmentToExport = viewport.getAlignment();
1573 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1574 if (settings == null)
1576 settings = new AlignExportSettings(hasHiddenSeqs,
1577 viewport.hasHiddenColumns(), format);
1579 // settings.isExportAnnotations();
1581 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1583 omitHidden = viewport.getViewAsString(false,
1584 settings.isExportHiddenSequences());
1587 int[] alignmentStartEnd = new int[2];
1588 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1590 alignmentToExport = hiddenSeqs.getFullAlignment();
1594 alignmentToExport = viewport.getAlignment();
1596 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1597 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1598 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1599 omitHidden, alignmentStartEnd, settings);
1610 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1612 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1613 htmlSVG.exportHTML(null);
1617 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1619 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1620 bjs.exportHTML(null);
1623 public void createImageMap(File file, String image)
1625 alignPanel.makePNGImageMap(file, image);
1635 public void createPNG(File f)
1637 alignPanel.makePNG(f);
1647 public void createEPS(File f)
1649 alignPanel.makeEPS(f);
1653 public void createSVG(File f)
1655 alignPanel.makeSVG(f);
1659 public void pageSetup_actionPerformed(ActionEvent e)
1661 PrinterJob printJob = PrinterJob.getPrinterJob();
1662 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1672 public void printMenuItem_actionPerformed(ActionEvent e)
1674 // Putting in a thread avoids Swing painting problems
1675 PrintThread thread = new PrintThread(alignPanel);
1680 public void exportFeatures_actionPerformed(ActionEvent e)
1682 new AnnotationExporter(alignPanel).exportFeatures();
1686 public void exportAnnotations_actionPerformed(ActionEvent e)
1688 new AnnotationExporter(alignPanel).exportAnnotations();
1692 public void associatedData_actionPerformed(ActionEvent e)
1693 throws IOException, InterruptedException
1695 // Pick the tree file
1696 JalviewFileChooser chooser = new JalviewFileChooser(
1697 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1698 chooser.setFileView(new JalviewFileView());
1699 chooser.setDialogTitle(
1700 MessageManager.getString("label.load_jalview_annotations"));
1701 chooser.setToolTipText(
1702 MessageManager.getString("label.load_jalview_annotations"));
1704 int value = chooser.showOpenDialog(null);
1706 if (value == JalviewFileChooser.APPROVE_OPTION)
1708 String choice = chooser.getSelectedFile().getPath();
1709 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1710 loadJalviewDataFile(choice, null, null, null);
1716 * Close the current view or all views in the alignment frame. If the frame
1717 * only contains one view then the alignment will be removed from memory.
1719 * @param closeAllTabs
1722 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1724 if (alignPanels != null && alignPanels.size() < 2)
1726 closeAllTabs = true;
1731 if (alignPanels != null)
1735 if (this.isClosed())
1737 // really close all the windows - otherwise wait till
1738 // setClosed(true) is called
1739 for (int i = 0; i < alignPanels.size(); i++)
1741 AlignmentPanel ap = alignPanels.get(i);
1748 closeView(alignPanel);
1755 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1756 * be called recursively, with the frame now in 'closed' state
1758 this.setClosed(true);
1760 } catch (Exception ex)
1762 ex.printStackTrace();
1767 * Close the specified panel and close up tabs appropriately.
1769 * @param panelToClose
1771 public void closeView(AlignmentPanel panelToClose)
1773 int index = tabbedPane.getSelectedIndex();
1774 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1775 alignPanels.remove(panelToClose);
1776 panelToClose.closePanel();
1777 panelToClose = null;
1779 tabbedPane.removeTabAt(closedindex);
1780 tabbedPane.validate();
1782 if (index > closedindex || index == tabbedPane.getTabCount())
1784 // modify currently selected tab index if necessary.
1788 this.tabSelectionChanged(index);
1794 void updateEditMenuBar()
1797 if (viewport.getHistoryList().size() > 0)
1799 undoMenuItem.setEnabled(true);
1800 CommandI command = viewport.getHistoryList().peek();
1801 undoMenuItem.setText(MessageManager
1802 .formatMessage("label.undo_command", new Object[]
1803 { command.getDescription() }));
1807 undoMenuItem.setEnabled(false);
1808 undoMenuItem.setText(MessageManager.getString("action.undo"));
1811 if (viewport.getRedoList().size() > 0)
1813 redoMenuItem.setEnabled(true);
1815 CommandI command = viewport.getRedoList().peek();
1816 redoMenuItem.setText(MessageManager
1817 .formatMessage("label.redo_command", new Object[]
1818 { command.getDescription() }));
1822 redoMenuItem.setEnabled(false);
1823 redoMenuItem.setText(MessageManager.getString("action.redo"));
1828 public void addHistoryItem(CommandI command)
1830 if (command.getSize() > 0)
1832 viewport.addToHistoryList(command);
1833 viewport.clearRedoList();
1834 updateEditMenuBar();
1835 viewport.updateHiddenColumns();
1836 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1837 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1838 // viewport.getColumnSelection()
1839 // .getHiddenColumns().size() > 0);
1845 * @return alignment objects for all views
1847 AlignmentI[] getViewAlignments()
1849 if (alignPanels != null)
1851 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1853 for (AlignmentPanel ap : alignPanels)
1855 als[i++] = ap.av.getAlignment();
1859 if (viewport != null)
1861 return new AlignmentI[] { viewport.getAlignment() };
1873 protected void undoMenuItem_actionPerformed(ActionEvent e)
1875 if (viewport.getHistoryList().isEmpty())
1879 CommandI command = viewport.getHistoryList().pop();
1880 viewport.addToRedoList(command);
1881 command.undoCommand(getViewAlignments());
1883 AlignmentViewport originalSource = getOriginatingSource(command);
1884 updateEditMenuBar();
1886 if (originalSource != null)
1888 if (originalSource != viewport)
1891 "Implementation worry: mismatch of viewport origin for undo");
1893 originalSource.updateHiddenColumns();
1894 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1896 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1897 // viewport.getColumnSelection()
1898 // .getHiddenColumns().size() > 0);
1899 originalSource.firePropertyChange("alignment", null,
1900 originalSource.getAlignment().getSequences());
1911 protected void redoMenuItem_actionPerformed(ActionEvent e)
1913 if (viewport.getRedoList().size() < 1)
1918 CommandI command = viewport.getRedoList().pop();
1919 viewport.addToHistoryList(command);
1920 command.doCommand(getViewAlignments());
1922 AlignmentViewport originalSource = getOriginatingSource(command);
1923 updateEditMenuBar();
1925 if (originalSource != null)
1928 if (originalSource != viewport)
1931 "Implementation worry: mismatch of viewport origin for redo");
1933 originalSource.updateHiddenColumns();
1934 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1936 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1937 // viewport.getColumnSelection()
1938 // .getHiddenColumns().size() > 0);
1939 originalSource.firePropertyChange("alignment", null,
1940 originalSource.getAlignment().getSequences());
1944 AlignmentViewport getOriginatingSource(CommandI command)
1946 AlignmentViewport originalSource = null;
1947 // For sequence removal and addition, we need to fire
1948 // the property change event FROM the viewport where the
1949 // original alignment was altered
1950 AlignmentI al = null;
1951 if (command instanceof EditCommand)
1953 EditCommand editCommand = (EditCommand) command;
1954 al = editCommand.getAlignment();
1955 List<Component> comps = PaintRefresher.components
1956 .get(viewport.getSequenceSetId());
1958 for (Component comp : comps)
1960 if (comp instanceof AlignmentPanel)
1962 if (al == ((AlignmentPanel) comp).av.getAlignment())
1964 originalSource = ((AlignmentPanel) comp).av;
1971 if (originalSource == null)
1973 // The original view is closed, we must validate
1974 // the current view against the closed view first
1977 PaintRefresher.validateSequences(al, viewport.getAlignment());
1980 originalSource = viewport;
1983 return originalSource;
1992 public void moveSelectedSequences(boolean up)
1994 SequenceGroup sg = viewport.getSelectionGroup();
2000 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2001 viewport.getHiddenRepSequences(), up);
2002 alignPanel.paintAlignment(true, false);
2005 synchronized void slideSequences(boolean right, int size)
2007 List<SequenceI> sg = new ArrayList<>();
2008 if (viewport.cursorMode)
2010 sg.add(viewport.getAlignment()
2011 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2013 else if (viewport.getSelectionGroup() != null
2014 && viewport.getSelectionGroup().getSize() != viewport
2015 .getAlignment().getHeight())
2017 sg = viewport.getSelectionGroup()
2018 .getSequences(viewport.getHiddenRepSequences());
2026 List<SequenceI> invertGroup = new ArrayList<>();
2028 for (SequenceI seq : viewport.getAlignment().getSequences())
2030 if (!sg.contains(seq))
2032 invertGroup.add(seq);
2036 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2038 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2039 for (int i = 0; i < invertGroup.size(); i++)
2041 seqs2[i] = invertGroup.get(i);
2044 SlideSequencesCommand ssc;
2047 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2048 viewport.getGapCharacter());
2052 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2053 viewport.getGapCharacter());
2056 int groupAdjustment = 0;
2057 if (ssc.getGapsInsertedBegin() && right)
2059 if (viewport.cursorMode)
2061 alignPanel.getSeqPanel().moveCursor(size, 0);
2065 groupAdjustment = size;
2068 else if (!ssc.getGapsInsertedBegin() && !right)
2070 if (viewport.cursorMode)
2072 alignPanel.getSeqPanel().moveCursor(-size, 0);
2076 groupAdjustment = -size;
2080 if (groupAdjustment != 0)
2082 viewport.getSelectionGroup().setStartRes(
2083 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2084 viewport.getSelectionGroup().setEndRes(
2085 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2089 * just extend the last slide command if compatible; but not if in
2090 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2092 boolean appendHistoryItem = false;
2093 Deque<CommandI> historyList = viewport.getHistoryList();
2094 boolean inSplitFrame = getSplitViewContainer() != null;
2095 if (!inSplitFrame && historyList != null && historyList.size() > 0
2096 && historyList.peek() instanceof SlideSequencesCommand)
2098 appendHistoryItem = ssc.appendSlideCommand(
2099 (SlideSequencesCommand) historyList.peek());
2102 if (!appendHistoryItem)
2104 addHistoryItem(ssc);
2117 protected void copy_actionPerformed(ActionEvent e)
2119 if (viewport.getSelectionGroup() == null)
2123 // TODO: preserve the ordering of displayed alignment annotation in any
2124 // internal paste (particularly sequence associated annotation)
2125 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2126 String[] omitHidden = null;
2128 if (viewport.hasHiddenColumns())
2130 omitHidden = viewport.getViewAsString(true);
2133 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2134 seqs, omitHidden, null);
2136 StringSelection ss = new StringSelection(output);
2140 jalview.gui.Desktop.internalCopy = true;
2141 // Its really worth setting the clipboard contents
2142 // to empty before setting the large StringSelection!!
2143 Toolkit.getDefaultToolkit().getSystemClipboard()
2144 .setContents(new StringSelection(""), null);
2146 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2148 } catch (OutOfMemoryError er)
2150 new OOMWarning("copying region", er);
2154 HiddenColumns hiddenColumns = null;
2155 if (viewport.hasHiddenColumns())
2157 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2158 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2160 // create new HiddenColumns object with copy of hidden regions
2161 // between startRes and endRes, offset by startRes
2162 hiddenColumns = new HiddenColumns(
2163 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2164 hiddenCutoff, hiddenOffset);
2167 Desktop.jalviewClipboard = new Object[] { seqs,
2168 viewport.getAlignment().getDataset(), hiddenColumns };
2169 statusBar.setText(MessageManager.formatMessage(
2170 "label.copied_sequences_to_clipboard", new Object[]
2171 { Integer.valueOf(seqs.length).toString() }));
2179 * @throws InterruptedException
2180 * @throws IOException
2183 protected void pasteNew_actionPerformed(ActionEvent e)
2184 throws IOException, InterruptedException
2194 * @throws InterruptedException
2195 * @throws IOException
2198 protected void pasteThis_actionPerformed(ActionEvent e)
2199 throws IOException, InterruptedException
2205 * Paste contents of Jalview clipboard
2207 * @param newAlignment
2208 * true to paste to a new alignment, otherwise add to this.
2209 * @throws InterruptedException
2210 * @throws IOException
2212 void paste(boolean newAlignment) throws IOException, InterruptedException
2214 boolean externalPaste = true;
2217 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2218 Transferable contents = c.getContents(this);
2220 if (contents == null)
2229 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2230 if (str.length() < 1)
2235 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2237 } catch (OutOfMemoryError er)
2239 new OOMWarning("Out of memory pasting sequences!!", er);
2243 SequenceI[] sequences;
2244 boolean annotationAdded = false;
2245 AlignmentI alignment = null;
2247 if (Desktop.jalviewClipboard != null)
2249 // The clipboard was filled from within Jalview, we must use the
2251 // And dataset from the copied alignment
2252 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2253 // be doubly sure that we create *new* sequence objects.
2254 sequences = new SequenceI[newseq.length];
2255 for (int i = 0; i < newseq.length; i++)
2257 sequences[i] = new Sequence(newseq[i]);
2259 alignment = new Alignment(sequences);
2260 externalPaste = false;
2264 // parse the clipboard as an alignment.
2265 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2267 sequences = alignment.getSequencesArray();
2271 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2277 if (Desktop.jalviewClipboard != null)
2279 // dataset is inherited
2280 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2284 // new dataset is constructed
2285 alignment.setDataset(null);
2287 alwidth = alignment.getWidth() + 1;
2291 AlignmentI pastedal = alignment; // preserve pasted alignment object
2292 // Add pasted sequences and dataset into existing alignment.
2293 alignment = viewport.getAlignment();
2294 alwidth = alignment.getWidth() + 1;
2295 // decide if we need to import sequences from an existing dataset
2296 boolean importDs = Desktop.jalviewClipboard != null
2297 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2298 // importDs==true instructs us to copy over new dataset sequences from
2299 // an existing alignment
2300 Vector newDs = (importDs) ? new Vector() : null; // used to create
2301 // minimum dataset set
2303 for (int i = 0; i < sequences.length; i++)
2307 newDs.addElement(null);
2309 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2311 if (importDs && ds != null)
2313 if (!newDs.contains(ds))
2315 newDs.setElementAt(ds, i);
2316 ds = new Sequence(ds);
2317 // update with new dataset sequence
2318 sequences[i].setDatasetSequence(ds);
2322 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2327 // copy and derive new dataset sequence
2328 sequences[i] = sequences[i].deriveSequence();
2329 alignment.getDataset()
2330 .addSequence(sequences[i].getDatasetSequence());
2331 // TODO: avoid creation of duplicate dataset sequences with a
2332 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2334 alignment.addSequence(sequences[i]); // merges dataset
2338 newDs.clear(); // tidy up
2340 if (alignment.getAlignmentAnnotation() != null)
2342 for (AlignmentAnnotation alan : alignment
2343 .getAlignmentAnnotation())
2345 if (alan.graphGroup > fgroup)
2347 fgroup = alan.graphGroup;
2351 if (pastedal.getAlignmentAnnotation() != null)
2353 // Add any annotation attached to alignment.
2354 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2355 for (int i = 0; i < alann.length; i++)
2357 annotationAdded = true;
2358 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2360 AlignmentAnnotation newann = new AlignmentAnnotation(
2362 if (newann.graphGroup > -1)
2364 if (newGraphGroups.size() <= newann.graphGroup
2365 || newGraphGroups.get(newann.graphGroup) == null)
2367 for (int q = newGraphGroups
2368 .size(); q <= newann.graphGroup; q++)
2370 newGraphGroups.add(q, null);
2372 newGraphGroups.set(newann.graphGroup,
2373 Integer.valueOf(++fgroup));
2375 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2379 newann.padAnnotation(alwidth);
2380 alignment.addAnnotation(newann);
2390 addHistoryItem(new EditCommand(
2391 MessageManager.getString("label.add_sequences"),
2392 Action.PASTE, sequences, 0, alignment.getWidth(),
2395 // Add any annotations attached to sequences
2396 for (int i = 0; i < sequences.length; i++)
2398 if (sequences[i].getAnnotation() != null)
2400 AlignmentAnnotation newann;
2401 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2403 annotationAdded = true;
2404 newann = sequences[i].getAnnotation()[a];
2405 newann.adjustForAlignment();
2406 newann.padAnnotation(alwidth);
2407 if (newann.graphGroup > -1)
2409 if (newann.graphGroup > -1)
2411 if (newGraphGroups.size() <= newann.graphGroup
2412 || newGraphGroups.get(newann.graphGroup) == null)
2414 for (int q = newGraphGroups
2415 .size(); q <= newann.graphGroup; q++)
2417 newGraphGroups.add(q, null);
2419 newGraphGroups.set(newann.graphGroup,
2420 Integer.valueOf(++fgroup));
2422 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2426 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2430 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2438 // propagate alignment changed.
2439 viewport.getRanges().setEndSeq(alignment.getHeight());
2440 if (annotationAdded)
2442 // Duplicate sequence annotation in all views.
2443 AlignmentI[] alview = this.getViewAlignments();
2444 for (int i = 0; i < sequences.length; i++)
2446 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2451 for (int avnum = 0; avnum < alview.length; avnum++)
2453 if (alview[avnum] != alignment)
2455 // duplicate in a view other than the one with input focus
2456 int avwidth = alview[avnum].getWidth() + 1;
2457 // this relies on sann being preserved after we
2458 // modify the sequence's annotation array for each duplication
2459 for (int a = 0; a < sann.length; a++)
2461 AlignmentAnnotation newann = new AlignmentAnnotation(
2463 sequences[i].addAlignmentAnnotation(newann);
2464 newann.padAnnotation(avwidth);
2465 alview[avnum].addAnnotation(newann); // annotation was
2466 // duplicated earlier
2467 // TODO JAL-1145 graphGroups are not updated for sequence
2468 // annotation added to several views. This may cause
2470 alview[avnum].setAnnotationIndex(newann, a);
2475 buildSortByAnnotationScoresMenu();
2477 viewport.firePropertyChange("alignment", null,
2478 alignment.getSequences());
2479 if (alignPanels != null)
2481 for (AlignmentPanel ap : alignPanels)
2483 ap.validateAnnotationDimensions(false);
2488 alignPanel.validateAnnotationDimensions(false);
2494 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2496 String newtitle = new String("Copied sequences");
2498 if (Desktop.jalviewClipboard != null
2499 && Desktop.jalviewClipboard[2] != null)
2501 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2502 af.viewport.setHiddenColumns(hc);
2505 // >>>This is a fix for the moment, until a better solution is
2507 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2508 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2509 .getFeatureRenderer());
2511 // TODO: maintain provenance of an alignment, rather than just make the
2512 // title a concatenation of operations.
2515 if (title.startsWith("Copied sequences"))
2521 newtitle = newtitle.concat("- from " + title);
2526 newtitle = new String("Pasted sequences");
2529 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2534 } catch (Exception ex)
2536 ex.printStackTrace();
2537 System.out.println("Exception whilst pasting: " + ex);
2538 // could be anything being pasted in here
2543 protected void expand_newalign(ActionEvent e)
2547 AlignmentI alignment = AlignmentUtils
2548 .expandContext(getViewport().getAlignment(), -1);
2549 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2551 String newtitle = new String("Flanking alignment");
2553 if (Desktop.jalviewClipboard != null
2554 && Desktop.jalviewClipboard[2] != null)
2556 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2557 af.viewport.setHiddenColumns(hc);
2560 // >>>This is a fix for the moment, until a better solution is
2562 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2563 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2564 .getFeatureRenderer());
2566 // TODO: maintain provenance of an alignment, rather than just make the
2567 // title a concatenation of operations.
2569 if (title.startsWith("Copied sequences"))
2575 newtitle = newtitle.concat("- from " + title);
2579 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2581 } catch (Exception ex)
2583 ex.printStackTrace();
2584 System.out.println("Exception whilst pasting: " + ex);
2585 // could be anything being pasted in here
2586 } catch (OutOfMemoryError oom)
2588 new OOMWarning("Viewing flanking region of alignment", oom);
2599 protected void cut_actionPerformed(ActionEvent e)
2601 copy_actionPerformed(null);
2602 delete_actionPerformed(null);
2612 protected void delete_actionPerformed(ActionEvent evt)
2615 SequenceGroup sg = viewport.getSelectionGroup();
2622 * If the cut affects all sequences, warn, remove highlighted columns
2624 if (sg.getSize() == viewport.getAlignment().getHeight())
2626 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2627 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2628 if (isEntireAlignWidth)
2630 int confirm = JvOptionPane.showConfirmDialog(this,
2631 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2632 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2633 JvOptionPane.OK_CANCEL_OPTION);
2635 if (confirm == JvOptionPane.CANCEL_OPTION
2636 || confirm == JvOptionPane.CLOSED_OPTION)
2641 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2642 sg.getEndRes() + 1);
2644 SequenceI[] cut = sg.getSequences()
2645 .toArray(new SequenceI[sg.getSize()]);
2647 addHistoryItem(new EditCommand(
2648 MessageManager.getString("label.cut_sequences"), Action.CUT,
2649 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2650 viewport.getAlignment()));
2652 viewport.setSelectionGroup(null);
2653 viewport.sendSelection();
2654 viewport.getAlignment().deleteGroup(sg);
2656 viewport.firePropertyChange("alignment", null,
2657 viewport.getAlignment().getSequences());
2658 if (viewport.getAlignment().getHeight() < 1)
2662 this.setClosed(true);
2663 } catch (Exception ex)
2676 protected void deleteGroups_actionPerformed(ActionEvent e)
2678 if (avc.deleteGroups())
2680 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2681 alignPanel.updateAnnotation();
2682 alignPanel.paintAlignment(true, true);
2693 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2695 SequenceGroup sg = new SequenceGroup(
2696 viewport.getAlignment().getSequences());
2698 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2699 viewport.setSelectionGroup(sg);
2700 viewport.isSelectionGroupChanged(true);
2701 viewport.sendSelection();
2702 // JAL-2034 - should delegate to
2703 // alignPanel to decide if overview needs
2705 alignPanel.paintAlignment(false, false);
2706 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2716 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2718 if (viewport.cursorMode)
2720 alignPanel.getSeqPanel().keyboardNo1 = null;
2721 alignPanel.getSeqPanel().keyboardNo2 = null;
2723 viewport.setSelectionGroup(null);
2724 viewport.getColumnSelection().clear();
2725 viewport.setSelectionGroup(null);
2726 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2727 // JAL-2034 - should delegate to
2728 // alignPanel to decide if overview needs
2730 alignPanel.paintAlignment(false, false);
2731 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2732 viewport.sendSelection();
2742 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2744 SequenceGroup sg = viewport.getSelectionGroup();
2748 selectAllSequenceMenuItem_actionPerformed(null);
2753 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2755 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2757 // JAL-2034 - should delegate to
2758 // alignPanel to decide if overview needs
2761 alignPanel.paintAlignment(true, false);
2762 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2763 viewport.sendSelection();
2767 public void invertColSel_actionPerformed(ActionEvent e)
2769 viewport.invertColumnSelection();
2770 alignPanel.paintAlignment(true, false);
2771 viewport.sendSelection();
2781 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2783 trimAlignment(true);
2793 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2795 trimAlignment(false);
2798 void trimAlignment(boolean trimLeft)
2800 ColumnSelection colSel = viewport.getColumnSelection();
2803 if (!colSel.isEmpty())
2807 column = colSel.getMin();
2811 column = colSel.getMax();
2815 if (viewport.getSelectionGroup() != null)
2817 seqs = viewport.getSelectionGroup()
2818 .getSequencesAsArray(viewport.getHiddenRepSequences());
2822 seqs = viewport.getAlignment().getSequencesArray();
2825 TrimRegionCommand trimRegion;
2828 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2829 column, viewport.getAlignment());
2830 viewport.getRanges().setStartRes(0);
2834 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2835 column, viewport.getAlignment());
2838 statusBar.setText(MessageManager
2839 .formatMessage("label.removed_columns", new String[]
2840 { Integer.valueOf(trimRegion.getSize()).toString() }));
2842 addHistoryItem(trimRegion);
2844 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2846 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2847 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2849 viewport.getAlignment().deleteGroup(sg);
2853 viewport.firePropertyChange("alignment", null,
2854 viewport.getAlignment().getSequences());
2865 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2867 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2870 if (viewport.getSelectionGroup() != null)
2872 seqs = viewport.getSelectionGroup()
2873 .getSequencesAsArray(viewport.getHiddenRepSequences());
2874 start = viewport.getSelectionGroup().getStartRes();
2875 end = viewport.getSelectionGroup().getEndRes();
2879 seqs = viewport.getAlignment().getSequencesArray();
2882 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2883 "Remove Gapped Columns", seqs, start, end,
2884 viewport.getAlignment());
2886 addHistoryItem(removeGapCols);
2888 statusBar.setText(MessageManager
2889 .formatMessage("label.removed_empty_columns", new Object[]
2890 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2892 // This is to maintain viewport position on first residue
2893 // of first sequence
2894 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2895 ViewportRanges ranges = viewport.getRanges();
2896 int startRes = seq.findPosition(ranges.getStartRes());
2897 // ShiftList shifts;
2898 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2899 // edit.alColumnChanges=shifts.getInverse();
2900 // if (viewport.hasHiddenColumns)
2901 // viewport.getColumnSelection().compensateForEdits(shifts);
2902 ranges.setStartRes(seq.findIndex(startRes) - 1);
2903 viewport.firePropertyChange("alignment", null,
2904 viewport.getAlignment().getSequences());
2915 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2917 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2920 if (viewport.getSelectionGroup() != null)
2922 seqs = viewport.getSelectionGroup()
2923 .getSequencesAsArray(viewport.getHiddenRepSequences());
2924 start = viewport.getSelectionGroup().getStartRes();
2925 end = viewport.getSelectionGroup().getEndRes();
2929 seqs = viewport.getAlignment().getSequencesArray();
2932 // This is to maintain viewport position on first residue
2933 // of first sequence
2934 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2935 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2937 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2938 viewport.getAlignment()));
2940 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2942 viewport.firePropertyChange("alignment", null,
2943 viewport.getAlignment().getSequences());
2954 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2956 viewport.setPadGaps(padGapsMenuitem.isSelected());
2957 viewport.firePropertyChange("alignment", null,
2958 viewport.getAlignment().getSequences());
2968 public void findMenuItem_actionPerformed(ActionEvent e)
2974 * Create a new view of the current alignment.
2977 public void newView_actionPerformed(ActionEvent e)
2979 newView(null, true);
2983 * Creates and shows a new view of the current alignment.
2986 * title of newly created view; if null, one will be generated
2987 * @param copyAnnotation
2988 * if true then duplicate all annnotation, groups and settings
2989 * @return new alignment panel, already displayed.
2991 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2994 * Create a new AlignmentPanel (with its own, new Viewport)
2996 AlignmentPanel newap = new jalview.project.Jalview2XML()
2997 .copyAlignPanel(alignPanel);
2998 if (!copyAnnotation)
3001 * remove all groups and annotation except for the automatic stuff
3003 newap.av.getAlignment().deleteAllGroups();
3004 newap.av.getAlignment().deleteAllAnnotations(false);
3007 newap.av.setGatherViewsHere(false);
3009 if (viewport.getViewName() == null)
3011 viewport.setViewName(MessageManager
3012 .getString("label.view_name_original"));
3016 * Views share the same edits undo and redo stacks
3018 newap.av.setHistoryList(viewport.getHistoryList());
3019 newap.av.setRedoList(viewport.getRedoList());
3022 * copy any visualisation settings that are not saved in the project
3024 newap.av.setColourAppliesToAllGroups(
3025 viewport.getColourAppliesToAllGroups());
3028 * Views share the same mappings; need to deregister any new mappings
3029 * created by copyAlignPanel, and register the new reference to the shared
3032 newap.av.replaceMappings(viewport.getAlignment());
3035 * start up cDNA consensus (if applicable) now mappings are in place
3037 if (newap.av.initComplementConsensus())
3039 newap.refresh(true); // adjust layout of annotations
3042 newap.av.setViewName(getNewViewName(viewTitle));
3044 addAlignmentPanel(newap, true);
3045 newap.alignmentChanged();
3047 if (alignPanels.size() == 2)
3049 viewport.setGatherViewsHere(true);
3051 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3056 * Make a new name for the view, ensuring it is unique within the current
3057 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3058 * these now use viewId. Unique view names are still desirable for usability.)
3063 protected String getNewViewName(String viewTitle)
3065 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3066 boolean addFirstIndex = false;
3067 if (viewTitle == null || viewTitle.trim().length() == 0)
3069 viewTitle = MessageManager.getString("action.view");
3070 addFirstIndex = true;
3074 index = 1;// we count from 1 if given a specific name
3076 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3078 List<Component> comps = PaintRefresher.components
3079 .get(viewport.getSequenceSetId());
3081 List<String> existingNames = getExistingViewNames(comps);
3083 while (existingNames.contains(newViewName))
3085 newViewName = viewTitle + " " + (++index);
3091 * Returns a list of distinct view names found in the given list of
3092 * components. View names are held on the viewport of an AlignmentPanel.
3097 protected List<String> getExistingViewNames(List<Component> comps)
3099 List<String> existingNames = new ArrayList<>();
3100 for (Component comp : comps)
3102 if (comp instanceof AlignmentPanel)
3104 AlignmentPanel ap = (AlignmentPanel) comp;
3105 if (!existingNames.contains(ap.av.getViewName()))
3107 existingNames.add(ap.av.getViewName());
3111 return existingNames;
3115 * Explode tabbed views into separate windows.
3118 public void expandViews_actionPerformed(ActionEvent e)
3120 Desktop.explodeViews(this);
3124 * Gather views in separate windows back into a tabbed presentation.
3127 public void gatherViews_actionPerformed(ActionEvent e)
3129 Desktop.instance.gatherViews(this);
3139 public void font_actionPerformed(ActionEvent e)
3141 new FontChooser(alignPanel);
3151 protected void seqLimit_actionPerformed(ActionEvent e)
3153 viewport.setShowJVSuffix(seqLimits.isSelected());
3155 alignPanel.getIdPanel().getIdCanvas()
3156 .setPreferredSize(alignPanel.calculateIdWidth());
3157 alignPanel.paintAlignment(true, false);
3161 public void idRightAlign_actionPerformed(ActionEvent e)
3163 viewport.setRightAlignIds(idRightAlign.isSelected());
3164 alignPanel.paintAlignment(false, false);
3168 public void centreColumnLabels_actionPerformed(ActionEvent e)
3170 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3171 alignPanel.paintAlignment(false, false);
3177 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3180 protected void followHighlight_actionPerformed()
3183 * Set the 'follow' flag on the Viewport (and scroll to position if now
3186 final boolean state = this.followHighlightMenuItem.getState();
3187 viewport.setFollowHighlight(state);
3190 alignPanel.scrollToPosition(viewport.getSearchResults());
3201 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3203 viewport.setColourText(colourTextMenuItem.isSelected());
3204 alignPanel.paintAlignment(false, false);
3214 public void wrapMenuItem_actionPerformed(ActionEvent e)
3216 scaleAbove.setVisible(wrapMenuItem.isSelected());
3217 scaleLeft.setVisible(wrapMenuItem.isSelected());
3218 scaleRight.setVisible(wrapMenuItem.isSelected());
3219 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3220 alignPanel.updateLayout();
3224 public void showAllSeqs_actionPerformed(ActionEvent e)
3226 viewport.showAllHiddenSeqs();
3230 public void showAllColumns_actionPerformed(ActionEvent e)
3232 viewport.showAllHiddenColumns();
3233 alignPanel.paintAlignment(true, true);
3234 viewport.sendSelection();
3238 public void hideSelSequences_actionPerformed(ActionEvent e)
3240 viewport.hideAllSelectedSeqs();
3244 * called by key handler and the hide all/show all menu items
3249 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3252 boolean hide = false;
3253 SequenceGroup sg = viewport.getSelectionGroup();
3254 if (!toggleSeqs && !toggleCols)
3256 // Hide everything by the current selection - this is a hack - we do the
3257 // invert and then hide
3258 // first check that there will be visible columns after the invert.
3259 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3260 && sg.getStartRes() <= sg.getEndRes()))
3262 // now invert the sequence set, if required - empty selection implies
3263 // that no hiding is required.
3266 invertSequenceMenuItem_actionPerformed(null);
3267 sg = viewport.getSelectionGroup();
3271 viewport.expandColSelection(sg, true);
3272 // finally invert the column selection and get the new sequence
3274 invertColSel_actionPerformed(null);
3281 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3283 hideSelSequences_actionPerformed(null);
3286 else if (!(toggleCols && viewport.hasSelectedColumns()))
3288 showAllSeqs_actionPerformed(null);
3294 if (viewport.hasSelectedColumns())
3296 hideSelColumns_actionPerformed(null);
3299 viewport.setSelectionGroup(sg);
3304 showAllColumns_actionPerformed(null);
3313 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3314 * event.ActionEvent)
3317 public void hideAllButSelection_actionPerformed(ActionEvent e)
3319 toggleHiddenRegions(false, false);
3320 viewport.sendSelection();
3327 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3331 public void hideAllSelection_actionPerformed(ActionEvent e)
3333 SequenceGroup sg = viewport.getSelectionGroup();
3334 viewport.expandColSelection(sg, false);
3335 viewport.hideAllSelectedSeqs();
3336 viewport.hideSelectedColumns();
3337 alignPanel.updateLayout();
3338 alignPanel.paintAlignment(true, true);
3339 viewport.sendSelection();
3346 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3350 public void showAllhidden_actionPerformed(ActionEvent e)
3352 viewport.showAllHiddenColumns();
3353 viewport.showAllHiddenSeqs();
3354 alignPanel.paintAlignment(true, true);
3355 viewport.sendSelection();
3359 public void hideSelColumns_actionPerformed(ActionEvent e)
3361 viewport.hideSelectedColumns();
3362 alignPanel.updateLayout();
3363 alignPanel.paintAlignment(true, true);
3364 viewport.sendSelection();
3368 public void hiddenMarkers_actionPerformed(ActionEvent e)
3370 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3381 protected void scaleAbove_actionPerformed(ActionEvent e)
3383 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3384 alignPanel.updateLayout();
3385 alignPanel.paintAlignment(true, false);
3395 protected void scaleLeft_actionPerformed(ActionEvent e)
3397 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3398 alignPanel.updateLayout();
3399 alignPanel.paintAlignment(true, false);
3409 protected void scaleRight_actionPerformed(ActionEvent e)
3411 viewport.setScaleRightWrapped(scaleRight.isSelected());
3412 alignPanel.updateLayout();
3413 alignPanel.paintAlignment(true, false);
3423 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3425 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3426 alignPanel.paintAlignment(false, false);
3436 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3438 viewport.setShowText(viewTextMenuItem.isSelected());
3439 alignPanel.paintAlignment(false, false);
3449 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3451 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3452 alignPanel.paintAlignment(false, false);
3455 public FeatureSettings featureSettings;
3458 public FeatureSettingsControllerI getFeatureSettingsUI()
3460 return featureSettings;
3464 public void featureSettings_actionPerformed(ActionEvent e)
3466 if (featureSettings != null)
3468 featureSettings.close();
3469 featureSettings = null;
3471 if (!showSeqFeatures.isSelected())
3473 // make sure features are actually displayed
3474 showSeqFeatures.setSelected(true);
3475 showSeqFeatures_actionPerformed(null);
3477 featureSettings = new FeatureSettings(this);
3481 * Set or clear 'Show Sequence Features'
3487 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3489 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3490 alignPanel.paintAlignment(true, true);
3494 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3495 * the annotations panel as a whole.
3497 * The options to show/hide all annotations should be enabled when the panel
3498 * is shown, and disabled when the panel is hidden.
3503 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3505 final boolean setVisible = annotationPanelMenuItem.isSelected();
3506 viewport.setShowAnnotation(setVisible);
3507 this.showAllSeqAnnotations.setEnabled(setVisible);
3508 this.hideAllSeqAnnotations.setEnabled(setVisible);
3509 this.showAllAlAnnotations.setEnabled(setVisible);
3510 this.hideAllAlAnnotations.setEnabled(setVisible);
3511 alignPanel.updateLayout();
3515 public void alignmentProperties()
3517 JEditorPane editPane = new JEditorPane("text/html", "");
3518 editPane.setEditable(false);
3519 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3522 MessageManager.formatMessage("label.html_content", new Object[]
3523 { contents.toString() }));
3524 JInternalFrame frame = new JInternalFrame();
3525 frame.getContentPane().add(new JScrollPane(editPane));
3527 Desktop.addInternalFrame(frame, MessageManager
3528 .formatMessage("label.alignment_properties", new Object[]
3529 { getTitle() }), 500, 400);
3539 public void overviewMenuItem_actionPerformed(ActionEvent e)
3541 if (alignPanel.overviewPanel != null)
3546 JInternalFrame frame = new JInternalFrame();
3547 final OverviewPanel overview = new OverviewPanel(alignPanel);
3548 frame.setContentPane(overview);
3549 Desktop.addInternalFrame(frame, MessageManager
3550 .formatMessage("label.overview_params", new Object[]
3551 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3554 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3555 frame.addInternalFrameListener(
3556 new javax.swing.event.InternalFrameAdapter()
3559 public void internalFrameClosed(
3560 javax.swing.event.InternalFrameEvent evt)
3563 alignPanel.setOverviewPanel(null);
3566 if (getKeyListeners().length > 0)
3568 frame.addKeyListener(getKeyListeners()[0]);
3571 alignPanel.setOverviewPanel(overview);
3575 public void textColour_actionPerformed()
3577 new TextColourChooser().chooseColour(alignPanel, null);
3581 * public void covariationColour_actionPerformed() {
3583 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3587 public void annotationColour_actionPerformed()
3589 new AnnotationColourChooser(viewport, alignPanel);
3593 public void annotationColumn_actionPerformed(ActionEvent e)
3595 new AnnotationColumnChooser(viewport, alignPanel);
3599 * Action on the user checking or unchecking the option to apply the selected
3600 * colour scheme to all groups. If unchecked, groups may have their own
3601 * independent colour schemes.
3606 public void applyToAllGroups_actionPerformed(boolean selected)
3608 viewport.setColourAppliesToAllGroups(selected);
3612 * Action on user selecting a colour from the colour menu
3615 * the name (not the menu item label!) of the colour scheme
3618 public void changeColour_actionPerformed(String name)
3621 * 'User Defined' opens a panel to configure or load a
3622 * user-defined colour scheme
3624 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3626 new UserDefinedColours(alignPanel);
3631 * otherwise set the chosen colour scheme (or null for 'None')
3633 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3635 viewport.getAlignment(), viewport.getHiddenRepSequences());
3640 * Actions on setting or changing the alignment colour scheme
3645 public void changeColour(ColourSchemeI cs)
3647 // TODO: pull up to controller method
3648 ColourMenuHelper.setColourSelected(colourMenu, cs);
3650 viewport.setGlobalColourScheme(cs);
3652 alignPanel.paintAlignment(true, true);
3656 * Show the PID threshold slider panel
3659 protected void modifyPID_actionPerformed()
3661 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3662 alignPanel.getViewName());
3663 SliderPanel.showPIDSlider();
3667 * Show the Conservation slider panel
3670 protected void modifyConservation_actionPerformed()
3672 SliderPanel.setConservationSlider(alignPanel,
3673 viewport.getResidueShading(), alignPanel.getViewName());
3674 SliderPanel.showConservationSlider();
3678 * Action on selecting or deselecting (Colour) By Conservation
3681 public void conservationMenuItem_actionPerformed(boolean selected)
3683 modifyConservation.setEnabled(selected);
3684 viewport.setConservationSelected(selected);
3685 viewport.getResidueShading().setConservationApplied(selected);
3687 changeColour(viewport.getGlobalColourScheme());
3690 modifyConservation_actionPerformed();
3694 SliderPanel.hideConservationSlider();
3699 * Action on selecting or deselecting (Colour) Above PID Threshold
3702 public void abovePIDThreshold_actionPerformed(boolean selected)
3704 modifyPID.setEnabled(selected);
3705 viewport.setAbovePIDThreshold(selected);
3708 viewport.getResidueShading().setThreshold(0,
3709 viewport.isIgnoreGapsConsensus());
3712 changeColour(viewport.getGlobalColourScheme());
3715 modifyPID_actionPerformed();
3719 SliderPanel.hidePIDSlider();
3730 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3732 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3733 AlignmentSorter.sortByPID(viewport.getAlignment(),
3734 viewport.getAlignment().getSequenceAt(0));
3735 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3736 viewport.getAlignment()));
3737 alignPanel.paintAlignment(true, false);
3747 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3749 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3750 AlignmentSorter.sortByID(viewport.getAlignment());
3752 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3753 alignPanel.paintAlignment(true, false);
3763 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3765 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3766 AlignmentSorter.sortByLength(viewport.getAlignment());
3767 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3768 viewport.getAlignment()));
3769 alignPanel.paintAlignment(true, false);
3779 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3781 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3782 AlignmentSorter.sortByGroup(viewport.getAlignment());
3783 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3784 viewport.getAlignment()));
3786 alignPanel.paintAlignment(true, false);
3796 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3798 new RedundancyPanel(alignPanel, this);
3808 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3810 if ((viewport.getSelectionGroup() == null)
3811 || (viewport.getSelectionGroup().getSize() < 2))
3813 JvOptionPane.showInternalMessageDialog(this,
3814 MessageManager.getString(
3815 "label.you_must_select_least_two_sequences"),
3816 MessageManager.getString("label.invalid_selection"),
3817 JvOptionPane.WARNING_MESSAGE);
3821 JInternalFrame frame = new JInternalFrame();
3822 frame.setContentPane(new PairwiseAlignPanel(viewport));
3823 Desktop.addInternalFrame(frame,
3824 MessageManager.getString("action.pairwise_alignment"), 600,
3830 public void autoCalculate_actionPerformed(ActionEvent e)
3832 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3833 if (viewport.autoCalculateConsensus)
3835 viewport.firePropertyChange("alignment", null,
3836 viewport.getAlignment().getSequences());
3841 public void sortByTreeOption_actionPerformed(ActionEvent e)
3843 viewport.sortByTree = sortByTree.isSelected();
3847 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3849 viewport.followSelection = listenToViewSelections.isSelected();
3853 * Constructs a tree panel and adds it to the desktop
3856 * tree type (NJ or AV)
3858 * name of score model used to compute the tree
3860 * parameters for the distance or similarity calculation
3862 void newTreePanel(String type, String modelName,
3863 SimilarityParamsI options)
3865 String frameTitle = "";
3868 boolean onSelection = false;
3869 if (viewport.getSelectionGroup() != null
3870 && viewport.getSelectionGroup().getSize() > 0)
3872 SequenceGroup sg = viewport.getSelectionGroup();
3874 /* Decide if the selection is a column region */
3875 for (SequenceI _s : sg.getSequences())
3877 if (_s.getLength() < sg.getEndRes())
3879 JvOptionPane.showMessageDialog(Desktop.desktop,
3880 MessageManager.getString(
3881 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3882 MessageManager.getString(
3883 "label.sequences_selection_not_aligned"),
3884 JvOptionPane.WARNING_MESSAGE);
3893 if (viewport.getAlignment().getHeight() < 2)
3899 tp = new TreePanel(alignPanel, type, modelName, options);
3900 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3902 frameTitle += " from ";
3904 if (viewport.getViewName() != null)
3906 frameTitle += viewport.getViewName() + " of ";
3909 frameTitle += this.title;
3911 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3922 public void addSortByOrderMenuItem(String title,
3923 final AlignmentOrder order)
3925 final JMenuItem item = new JMenuItem(MessageManager
3926 .formatMessage("action.by_title_param", new Object[]
3929 item.addActionListener(new java.awt.event.ActionListener()
3932 public void actionPerformed(ActionEvent e)
3934 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3936 // TODO: JBPNote - have to map order entries to curent SequenceI
3938 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3940 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3941 viewport.getAlignment()));
3943 alignPanel.paintAlignment(true, false);
3949 * Add a new sort by annotation score menu item
3952 * the menu to add the option to
3954 * the label used to retrieve scores for each sequence on the
3957 public void addSortByAnnotScoreMenuItem(JMenu sort,
3958 final String scoreLabel)
3960 final JMenuItem item = new JMenuItem(scoreLabel);
3962 item.addActionListener(new java.awt.event.ActionListener()
3965 public void actionPerformed(ActionEvent e)
3967 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3968 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3969 viewport.getAlignment());// ,viewport.getSelectionGroup());
3970 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3971 viewport.getAlignment()));
3972 alignPanel.paintAlignment(true, false);
3978 * last hash for alignment's annotation array - used to minimise cost of
3981 protected int _annotationScoreVectorHash;
3984 * search the alignment and rebuild the sort by annotation score submenu the
3985 * last alignment annotation vector hash is stored to minimize cost of
3986 * rebuilding in subsequence calls.
3990 public void buildSortByAnnotationScoresMenu()
3992 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3997 if (viewport.getAlignment().getAlignmentAnnotation()
3998 .hashCode() == _annotationScoreVectorHash)
4003 sortByAnnotScore.removeAll();
4004 Set<String> scoreSorts = new HashSet<>();
4005 for (SequenceI sqa : viewport.getAlignment().getSequences())
4007 AlignmentAnnotation[] anns = sqa.getAnnotation();
4008 for (int i = 0; anns != null && i < anns.length; i++)
4010 AlignmentAnnotation aa = anns[i];
4011 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4013 scoreSorts.add(aa.label);
4017 for (String label : scoreSorts)
4019 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4021 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4023 _annotationScoreVectorHash = viewport.getAlignment()
4024 .getAlignmentAnnotation().hashCode();
4028 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4029 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4030 * call. Listeners are added to remove the menu item when the treePanel is
4031 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4035 public void buildTreeSortMenu()
4037 sortByTreeMenu.removeAll();
4039 List<Component> comps = PaintRefresher.components
4040 .get(viewport.getSequenceSetId());
4041 List<TreePanel> treePanels = new ArrayList<>();
4042 for (Component comp : comps)
4044 if (comp instanceof TreePanel)
4046 treePanels.add((TreePanel) comp);
4050 if (treePanels.size() < 1)
4052 sortByTreeMenu.setVisible(false);
4056 sortByTreeMenu.setVisible(true);
4058 for (final TreePanel tp : treePanels)
4060 final JMenuItem item = new JMenuItem(tp.getTitle());
4061 item.addActionListener(new java.awt.event.ActionListener()
4064 public void actionPerformed(ActionEvent e)
4066 tp.sortByTree_actionPerformed();
4067 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4072 sortByTreeMenu.add(item);
4076 public boolean sortBy(AlignmentOrder alorder, String undoname)
4078 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4079 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4080 if (undoname != null)
4082 addHistoryItem(new OrderCommand(undoname, oldOrder,
4083 viewport.getAlignment()));
4085 alignPanel.paintAlignment(true, false);
4090 * Work out whether the whole set of sequences or just the selected set will
4091 * be submitted for multiple alignment.
4094 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4096 // Now, check we have enough sequences
4097 AlignmentView msa = null;
4099 if ((viewport.getSelectionGroup() != null)
4100 && (viewport.getSelectionGroup().getSize() > 1))
4102 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4103 // some common interface!
4105 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4106 * SequenceI[sz = seqs.getSize(false)];
4108 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4109 * seqs.getSequenceAt(i); }
4111 msa = viewport.getAlignmentView(true);
4113 else if (viewport.getSelectionGroup() != null
4114 && viewport.getSelectionGroup().getSize() == 1)
4116 int option = JvOptionPane.showConfirmDialog(this,
4117 MessageManager.getString("warn.oneseq_msainput_selection"),
4118 MessageManager.getString("label.invalid_selection"),
4119 JvOptionPane.OK_CANCEL_OPTION);
4120 if (option == JvOptionPane.OK_OPTION)
4122 msa = viewport.getAlignmentView(false);
4127 msa = viewport.getAlignmentView(false);
4133 * Decides what is submitted to a secondary structure prediction service: the
4134 * first sequence in the alignment, or in the current selection, or, if the
4135 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4136 * region or the whole alignment. (where the first sequence in the set is the
4137 * one that the prediction will be for).
4139 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4141 AlignmentView seqs = null;
4143 if ((viewport.getSelectionGroup() != null)
4144 && (viewport.getSelectionGroup().getSize() > 0))
4146 seqs = viewport.getAlignmentView(true);
4150 seqs = viewport.getAlignmentView(false);
4152 // limit sequences - JBPNote in future - could spawn multiple prediction
4154 // TODO: viewport.getAlignment().isAligned is a global state - the local
4155 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4156 if (!viewport.getAlignment().isAligned(false))
4158 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4159 // TODO: if seqs.getSequences().length>1 then should really have warned
4173 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4175 // Pick the tree file
4176 JalviewFileChooser chooser = new JalviewFileChooser(
4177 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4178 chooser.setFileView(new JalviewFileView());
4179 chooser.setDialogTitle(
4180 MessageManager.getString("label.select_newick_like_tree_file"));
4181 chooser.setToolTipText(
4182 MessageManager.getString("label.load_tree_file"));
4184 int value = chooser.showOpenDialog(null);
4186 if (value == JalviewFileChooser.APPROVE_OPTION)
4188 String filePath = chooser.getSelectedFile().getPath();
4189 Cache.setProperty("LAST_DIRECTORY", filePath);
4190 NewickFile fin = null;
4193 fin = new NewickFile(filePath, DataSourceType.FILE);
4194 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4195 } catch (Exception ex)
4197 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4198 MessageManager.getString("label.problem_reading_tree_file"),
4199 JvOptionPane.WARNING_MESSAGE);
4200 ex.printStackTrace();
4202 if (fin != null && fin.hasWarningMessage())
4204 JvOptionPane.showMessageDialog(Desktop.desktop,
4205 fin.getWarningMessage(),
4207 .getString("label.possible_problem_with_tree_file"),
4208 JvOptionPane.WARNING_MESSAGE);
4213 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4215 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4218 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4219 int h, int x, int y)
4221 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4225 * Add a treeviewer for the tree extracted from a Newick file object to the
4226 * current alignment view
4233 * Associated alignment input data (or null)
4242 * @return TreePanel handle
4244 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4245 AlignmentView input, int w, int h, int x, int y)
4247 TreePanel tp = null;
4253 if (nf.getTree() != null)
4255 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4261 tp.setLocation(x, y);
4264 Desktop.addInternalFrame(tp, treeTitle, w, h);
4266 } catch (Exception ex)
4268 ex.printStackTrace();
4274 private boolean buildingMenu = false;
4277 * Generates menu items and listener event actions for web service clients
4280 public void BuildWebServiceMenu()
4282 while (buildingMenu)
4286 System.err.println("Waiting for building menu to finish.");
4288 } catch (Exception e)
4292 final AlignFrame me = this;
4293 buildingMenu = true;
4294 new Thread(new Runnable()
4299 final List<JMenuItem> legacyItems = new ArrayList<>();
4302 // System.err.println("Building ws menu again "
4303 // + Thread.currentThread());
4304 // TODO: add support for context dependent disabling of services based
4306 // alignment and current selection
4307 // TODO: add additional serviceHandle parameter to specify abstract
4309 // class independently of AbstractName
4310 // TODO: add in rediscovery GUI function to restart discoverer
4311 // TODO: group services by location as well as function and/or
4313 // object broker mechanism.
4314 final Vector<JMenu> wsmenu = new Vector<>();
4315 final IProgressIndicator af = me;
4318 * do not i18n these strings - they are hard-coded in class
4319 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4320 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4322 final JMenu msawsmenu = new JMenu("Alignment");
4323 final JMenu secstrmenu = new JMenu(
4324 "Secondary Structure Prediction");
4325 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4326 final JMenu analymenu = new JMenu("Analysis");
4327 final JMenu dismenu = new JMenu("Protein Disorder");
4328 // JAL-940 - only show secondary structure prediction services from
4329 // the legacy server
4330 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4332 Discoverer.services != null && (Discoverer.services.size() > 0))
4334 // TODO: refactor to allow list of AbstractName/Handler bindings to
4336 // stored or retrieved from elsewhere
4337 // No MSAWS used any more:
4338 // Vector msaws = null; // (Vector)
4339 // Discoverer.services.get("MsaWS");
4340 Vector secstrpr = (Vector) Discoverer.services
4342 if (secstrpr != null)
4344 // Add any secondary structure prediction services
4345 for (int i = 0, j = secstrpr.size(); i < j; i++)
4347 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4349 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4350 .getServiceClient(sh);
4351 int p = secstrmenu.getItemCount();
4352 impl.attachWSMenuEntry(secstrmenu, me);
4353 int q = secstrmenu.getItemCount();
4354 for (int litm = p; litm < q; litm++)
4356 legacyItems.add(secstrmenu.getItem(litm));
4362 // Add all submenus in the order they should appear on the web
4364 wsmenu.add(msawsmenu);
4365 wsmenu.add(secstrmenu);
4366 wsmenu.add(dismenu);
4367 wsmenu.add(analymenu);
4368 // No search services yet
4369 // wsmenu.add(seqsrchmenu);
4371 javax.swing.SwingUtilities.invokeLater(new Runnable()
4378 webService.removeAll();
4379 // first, add discovered services onto the webservices menu
4380 if (wsmenu.size() > 0)
4382 for (int i = 0, j = wsmenu.size(); i < j; i++)
4384 webService.add(wsmenu.get(i));
4389 webService.add(me.webServiceNoServices);
4391 // TODO: move into separate menu builder class.
4392 boolean new_sspred = false;
4393 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4395 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4396 if (jws2servs != null)
4398 if (jws2servs.hasServices())
4400 jws2servs.attachWSMenuEntry(webService, me);
4401 for (Jws2Instance sv : jws2servs.getServices())
4403 if (sv.description.toLowerCase().contains("jpred"))
4405 for (JMenuItem jmi : legacyItems)
4407 jmi.setVisible(false);
4413 if (jws2servs.isRunning())
4415 JMenuItem tm = new JMenuItem(
4416 "Still discovering JABA Services");
4417 tm.setEnabled(false);
4422 build_urlServiceMenu(me.webService);
4423 build_fetchdbmenu(webService);
4424 for (JMenu item : wsmenu)
4426 if (item.getItemCount() == 0)
4428 item.setEnabled(false);
4432 item.setEnabled(true);
4435 } catch (Exception e)
4438 "Exception during web service menu building process.",
4443 } catch (Exception e)
4446 buildingMenu = false;
4453 * construct any groupURL type service menu entries.
4457 private void build_urlServiceMenu(JMenu webService)
4459 // TODO: remove this code when 2.7 is released
4460 // DEBUG - alignmentView
4462 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4463 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4465 * @Override public void actionPerformed(ActionEvent e) {
4466 * jalview.datamodel.AlignmentView
4467 * .testSelectionViews(af.viewport.getAlignment(),
4468 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4470 * }); webService.add(testAlView);
4472 // TODO: refactor to RestClient discoverer and merge menu entries for
4473 // rest-style services with other types of analysis/calculation service
4474 // SHmmr test client - still being implemented.
4475 // DEBUG - alignmentView
4477 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4480 client.attachWSMenuEntry(
4481 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4487 * Searches the alignment sequences for xRefs and builds the Show
4488 * Cross-References menu (formerly called Show Products), with database
4489 * sources for which cross-references are found (protein sources for a
4490 * nucleotide alignment and vice versa)
4492 * @return true if Show Cross-references menu should be enabled
4494 public boolean canShowProducts()
4496 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4497 AlignmentI dataset = viewport.getAlignment().getDataset();
4499 showProducts.removeAll();
4500 final boolean dna = viewport.getAlignment().isNucleotide();
4502 if (seqs == null || seqs.length == 0)
4504 // nothing to see here.
4508 boolean showp = false;
4511 List<String> ptypes = new CrossRef(seqs, dataset)
4512 .findXrefSourcesForSequences(dna);
4514 for (final String source : ptypes)
4517 final AlignFrame af = this;
4518 JMenuItem xtype = new JMenuItem(source);
4519 xtype.addActionListener(new ActionListener()
4522 public void actionPerformed(ActionEvent e)
4524 showProductsFor(af.viewport.getSequenceSelection(), dna,
4528 showProducts.add(xtype);
4530 showProducts.setVisible(showp);
4531 showProducts.setEnabled(showp);
4532 } catch (Exception e)
4535 "canShowProducts threw an exception - please report to help@jalview.org",
4543 * Finds and displays cross-references for the selected sequences (protein
4544 * products for nucleotide sequences, dna coding sequences for peptides).
4547 * the sequences to show cross-references for
4549 * true if from a nucleotide alignment (so showing proteins)
4551 * the database to show cross-references for
4553 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4554 final String source)
4556 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4561 * Construct and display a new frame containing the translation of this
4562 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4565 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4567 AlignmentI al = null;
4570 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4572 al = dna.translateCdna(codeTable);
4573 } catch (Exception ex)
4575 jalview.bin.Cache.log.error(
4576 "Exception during translation. Please report this !", ex);
4577 final String msg = MessageManager.getString(
4578 "label.error_when_translating_sequences_submit_bug_report");
4579 final String errorTitle = MessageManager
4580 .getString("label.implementation_error")
4581 + MessageManager.getString("label.translation_failed");
4582 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4583 JvOptionPane.ERROR_MESSAGE);
4586 if (al == null || al.getHeight() == 0)
4588 final String msg = MessageManager.getString(
4589 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4590 final String errorTitle = MessageManager
4591 .getString("label.translation_failed");
4592 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4593 JvOptionPane.WARNING_MESSAGE);
4597 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4598 af.setFileFormat(this.currentFileFormat);
4599 final String newTitle = MessageManager
4600 .formatMessage("label.translation_of_params", new Object[]
4601 { this.getTitle(), codeTable.getId() });
4602 af.setTitle(newTitle);
4603 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4605 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4606 viewport.openSplitFrame(af, new Alignment(seqs));
4610 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4617 * Set the file format
4621 public void setFileFormat(FileFormatI format)
4623 this.currentFileFormat = format;
4627 * Try to load a features file onto the alignment.
4630 * contents or path to retrieve file
4632 * access mode of file (see jalview.io.AlignFile)
4633 * @return true if features file was parsed correctly.
4635 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4637 return avc.parseFeaturesFile(file, sourceType,
4638 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4643 public void refreshFeatureUI(boolean enableIfNecessary)
4645 // note - currently this is only still here rather than in the controller
4646 // because of the featureSettings hard reference that is yet to be
4648 if (enableIfNecessary)
4650 viewport.setShowSequenceFeatures(true);
4651 showSeqFeatures.setSelected(true);
4657 public void dragEnter(DropTargetDragEvent evt)
4662 public void dragExit(DropTargetEvent evt)
4667 public void dragOver(DropTargetDragEvent evt)
4672 public void dropActionChanged(DropTargetDragEvent evt)
4677 public void drop(DropTargetDropEvent evt)
4679 // JAL-1552 - acceptDrop required before getTransferable call for
4680 // Java's Transferable for native dnd
4681 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4682 Transferable t = evt.getTransferable();
4683 final AlignFrame thisaf = this;
4684 final List<String> files = new ArrayList<>();
4685 List<DataSourceType> protocols = new ArrayList<>();
4689 Desktop.transferFromDropTarget(files, protocols, evt, t);
4690 } catch (Exception e)
4692 e.printStackTrace();
4696 new Thread(new Runnable()
4703 // check to see if any of these files have names matching sequences
4706 SequenceIdMatcher idm = new SequenceIdMatcher(
4707 viewport.getAlignment().getSequencesArray());
4709 * Object[] { String,SequenceI}
4711 ArrayList<Object[]> filesmatched = new ArrayList<>();
4712 ArrayList<String> filesnotmatched = new ArrayList<>();
4713 for (int i = 0; i < files.size(); i++)
4715 String file = files.get(i).toString();
4717 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4718 if (protocol == DataSourceType.FILE)
4720 File fl = new File(file);
4721 pdbfn = fl.getName();
4723 else if (protocol == DataSourceType.URL)
4725 URL url = new URL(file);
4726 pdbfn = url.getFile();
4728 if (pdbfn.length() > 0)
4730 // attempt to find a match in the alignment
4731 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4732 int l = 0, c = pdbfn.indexOf(".");
4733 while (mtch == null && c != -1)
4738 } while ((c = pdbfn.indexOf(".", l)) > l);
4741 pdbfn = pdbfn.substring(0, l);
4743 mtch = idm.findAllIdMatches(pdbfn);
4747 FileFormatI type = null;
4750 type = new IdentifyFile().identify(file, protocol);
4751 } catch (Exception ex)
4755 if (type != null && type.isStructureFile())
4757 filesmatched.add(new Object[] { file, protocol, mtch });
4761 // File wasn't named like one of the sequences or wasn't a PDB
4763 filesnotmatched.add(file);
4767 if (filesmatched.size() > 0)
4769 boolean autoAssociate = Cache
4770 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4773 String msg = MessageManager.formatMessage(
4774 "label.automatically_associate_structure_files_with_sequences_same_name",
4776 { Integer.valueOf(filesmatched.size())
4778 String ttl = MessageManager.getString(
4779 "label.automatically_associate_structure_files_by_name");
4780 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4781 ttl, JvOptionPane.YES_NO_OPTION);
4782 autoAssociate = choice == JvOptionPane.YES_OPTION;
4786 for (Object[] fm : filesmatched)
4788 // try and associate
4789 // TODO: may want to set a standard ID naming formalism for
4790 // associating PDB files which have no IDs.
4791 for (SequenceI toassoc : (SequenceI[]) fm[2])
4793 PDBEntry pe = new AssociatePdbFileWithSeq()
4794 .associatePdbWithSeq((String) fm[0],
4795 (DataSourceType) fm[1], toassoc, false,
4799 System.err.println("Associated file : "
4800 + ((String) fm[0]) + " with "
4801 + toassoc.getDisplayId(true));
4805 // TODO: do we need to update overview ? only if features are
4807 alignPanel.paintAlignment(true, false);
4813 * add declined structures as sequences
4815 for (Object[] o : filesmatched)
4817 filesnotmatched.add((String) o[0]);
4821 if (filesnotmatched.size() > 0)
4823 if (assocfiles > 0 && (Cache.getDefault(
4824 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4825 || JvOptionPane.showConfirmDialog(thisaf,
4826 "<html>" + MessageManager.formatMessage(
4827 "label.ignore_unmatched_dropped_files_info",
4830 filesnotmatched.size())
4833 MessageManager.getString(
4834 "label.ignore_unmatched_dropped_files"),
4835 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4839 for (String fn : filesnotmatched)
4841 loadJalviewDataFile(fn, null, null, null);
4845 } catch (Exception ex)
4847 ex.printStackTrace();
4855 * Attempt to load a "dropped" file or URL string, by testing in turn for
4857 * <li>an Annotation file</li>
4858 * <li>a JNet file</li>
4859 * <li>a features file</li>
4860 * <li>else try to interpret as an alignment file</li>
4864 * either a filename or a URL string.
4865 * @throws InterruptedException
4866 * @throws IOException
4868 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4869 FileFormatI format, SequenceI assocSeq)
4873 if (sourceType == null)
4875 sourceType = FormatAdapter.checkProtocol(file);
4877 // if the file isn't identified, or not positively identified as some
4878 // other filetype (PFAM is default unidentified alignment file type) then
4879 // try to parse as annotation.
4880 boolean isAnnotation = (format == null
4881 || FileFormat.Pfam.equals(format))
4882 ? new AnnotationFile().annotateAlignmentView(viewport,
4888 // first see if its a T-COFFEE score file
4889 TCoffeeScoreFile tcf = null;
4892 tcf = new TCoffeeScoreFile(file, sourceType);
4895 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4899 new TCoffeeColourScheme(viewport.getAlignment()));
4900 isAnnotation = true;
4901 statusBar.setText(MessageManager.getString(
4902 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4906 // some problem - if no warning its probable that the ID matching
4907 // process didn't work
4908 JvOptionPane.showMessageDialog(Desktop.desktop,
4909 tcf.getWarningMessage() == null
4910 ? MessageManager.getString(
4911 "label.check_file_matches_sequence_ids_alignment")
4912 : tcf.getWarningMessage(),
4913 MessageManager.getString(
4914 "label.problem_reading_tcoffee_score_file"),
4915 JvOptionPane.WARNING_MESSAGE);
4922 } catch (Exception x)
4925 "Exception when processing data source as T-COFFEE score file",
4931 // try to see if its a JNet 'concise' style annotation file *before*
4933 // try to parse it as a features file
4936 format = new IdentifyFile().identify(file, sourceType);
4938 if (FileFormat.ScoreMatrix == format)
4940 ScoreMatrixFile sm = new ScoreMatrixFile(
4941 new FileParse(file, sourceType));
4943 // todo: i18n this message
4944 statusBar.setText(MessageManager.formatMessage(
4945 "label.successfully_loaded_matrix",
4946 sm.getMatrixName()));
4948 else if (FileFormat.Jnet.equals(format))
4950 JPredFile predictions = new JPredFile(file, sourceType);
4951 new JnetAnnotationMaker();
4952 JnetAnnotationMaker.add_annotation(predictions,
4953 viewport.getAlignment(), 0, false);
4954 viewport.getAlignment().setupJPredAlignment();
4955 isAnnotation = true;
4957 // else if (IdentifyFile.FeaturesFile.equals(format))
4958 else if (FileFormat.Features.equals(format))
4960 if (parseFeaturesFile(file, sourceType))
4962 alignPanel.paintAlignment(true, true);
4967 new FileLoader().LoadFile(viewport, file, sourceType, format);
4973 alignPanel.adjustAnnotationHeight();
4974 viewport.updateSequenceIdColours();
4975 buildSortByAnnotationScoresMenu();
4976 alignPanel.paintAlignment(true, true);
4978 } catch (Exception ex)
4980 ex.printStackTrace();
4981 } catch (OutOfMemoryError oom)
4986 } catch (Exception x)
4991 + (sourceType != null
4992 ? (sourceType == DataSourceType.PASTE
4994 : "using " + sourceType + " from "
4998 ? "(parsing as '" + format + "' file)"
5000 oom, Desktop.desktop);
5005 * Method invoked by the ChangeListener on the tabbed pane, in other words
5006 * when a different tabbed pane is selected by the user or programmatically.
5009 public void tabSelectionChanged(int index)
5013 alignPanel = alignPanels.get(index);
5014 viewport = alignPanel.av;
5015 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5016 setMenusFromViewport(viewport);
5020 * 'focus' any colour slider that is open to the selected viewport
5022 if (viewport.getConservationSelected())
5024 SliderPanel.setConservationSlider(alignPanel,
5025 viewport.getResidueShading(), alignPanel.getViewName());
5029 SliderPanel.hideConservationSlider();
5031 if (viewport.getAbovePIDThreshold())
5033 SliderPanel.setPIDSliderSource(alignPanel,
5034 viewport.getResidueShading(), alignPanel.getViewName());
5038 SliderPanel.hidePIDSlider();
5042 * If there is a frame linked to this one in a SplitPane, switch it to the
5043 * same view tab index. No infinite recursion of calls should happen, since
5044 * tabSelectionChanged() should not get invoked on setting the selected
5045 * index to an unchanged value. Guard against setting an invalid index
5046 * before the new view peer tab has been created.
5048 final AlignViewportI peer = viewport.getCodingComplement();
5051 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5052 .getAlignPanel().alignFrame;
5053 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5055 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5061 * On right mouse click on view tab, prompt for and set new view name.
5064 public void tabbedPane_mousePressed(MouseEvent e)
5066 if (e.isPopupTrigger())
5068 String msg = MessageManager.getString("label.enter_view_name");
5069 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5070 JvOptionPane.QUESTION_MESSAGE);
5074 viewport.setViewName(reply);
5075 // TODO warn if reply is in getExistingViewNames()?
5076 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5081 public AlignViewport getCurrentView()
5087 * Open the dialog for regex description parsing.
5090 protected void extractScores_actionPerformed(ActionEvent e)
5092 ParseProperties pp = new jalview.analysis.ParseProperties(
5093 viewport.getAlignment());
5094 // TODO: verify regex and introduce GUI dialog for version 2.5
5095 // if (pp.getScoresFromDescription("col", "score column ",
5096 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5098 if (pp.getScoresFromDescription("description column",
5099 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5101 buildSortByAnnotationScoresMenu();
5109 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5113 protected void showDbRefs_actionPerformed(ActionEvent e)
5115 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5121 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5125 protected void showNpFeats_actionPerformed(ActionEvent e)
5127 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5131 * find the viewport amongst the tabs in this alignment frame and close that
5136 public boolean closeView(AlignViewportI av)
5140 this.closeMenuItem_actionPerformed(false);
5143 Component[] comp = tabbedPane.getComponents();
5144 for (int i = 0; comp != null && i < comp.length; i++)
5146 if (comp[i] instanceof AlignmentPanel)
5148 if (((AlignmentPanel) comp[i]).av == av)
5151 closeView((AlignmentPanel) comp[i]);
5159 protected void build_fetchdbmenu(JMenu webService)
5161 // Temporary hack - DBRef Fetcher always top level ws entry.
5162 // TODO We probably want to store a sequence database checklist in
5163 // preferences and have checkboxes.. rather than individual sources selected
5165 final JMenu rfetch = new JMenu(
5166 MessageManager.getString("action.fetch_db_references"));
5167 rfetch.setToolTipText(MessageManager.getString(
5168 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5169 webService.add(rfetch);
5171 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5172 MessageManager.getString("option.trim_retrieved_seqs"));
5173 trimrs.setToolTipText(
5174 MessageManager.getString("label.trim_retrieved_sequences"));
5176 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5177 trimrs.addActionListener(new ActionListener()
5180 public void actionPerformed(ActionEvent e)
5182 trimrs.setSelected(trimrs.isSelected());
5183 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5184 Boolean.valueOf(trimrs.isSelected()).toString());
5188 JMenuItem fetchr = new JMenuItem(
5189 MessageManager.getString("label.standard_databases"));
5190 fetchr.setToolTipText(
5191 MessageManager.getString("label.fetch_embl_uniprot"));
5192 fetchr.addActionListener(new ActionListener()
5196 public void actionPerformed(ActionEvent e)
5198 new Thread(new Runnable()
5203 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5204 .getAlignment().isNucleotide();
5205 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5206 alignPanel.av.getSequenceSelection(),
5207 alignPanel.alignFrame, null,
5208 alignPanel.alignFrame.featureSettings, isNucleotide);
5209 dbRefFetcher.addListener(new FetchFinishedListenerI()
5212 public void finished()
5214 AlignFrame.this.setMenusForViewport();
5217 dbRefFetcher.fetchDBRefs(false);
5225 final AlignFrame me = this;
5226 new Thread(new Runnable()
5231 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5232 .getSequenceFetcherSingleton(me);
5233 javax.swing.SwingUtilities.invokeLater(new Runnable()
5238 String[] dbclasses = sf.getOrderedSupportedSources();
5239 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5240 // jalview.util.QuickSort.sort(otherdb, otherdb);
5241 List<DbSourceProxy> otherdb;
5242 JMenu dfetch = new JMenu();
5243 JMenu ifetch = new JMenu();
5244 JMenuItem fetchr = null;
5245 int comp = 0, icomp = 0, mcomp = 15;
5246 String mname = null;
5248 for (String dbclass : dbclasses)
5250 otherdb = sf.getSourceProxy(dbclass);
5251 // add a single entry for this class, or submenu allowing 'fetch
5253 if (otherdb == null || otherdb.size() < 1)
5257 // List<DbSourceProxy> dbs=otherdb;
5258 // otherdb=new ArrayList<DbSourceProxy>();
5259 // for (DbSourceProxy db:dbs)
5261 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5265 mname = "From " + dbclass;
5267 if (otherdb.size() == 1)
5269 final DbSourceProxy[] dassource = otherdb
5270 .toArray(new DbSourceProxy[0]);
5271 DbSourceProxy src = otherdb.get(0);
5272 fetchr = new JMenuItem(src.getDbSource());
5273 fetchr.addActionListener(new ActionListener()
5277 public void actionPerformed(ActionEvent e)
5279 new Thread(new Runnable()
5285 boolean isNucleotide = alignPanel.alignFrame
5286 .getViewport().getAlignment()
5288 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5289 alignPanel.av.getSequenceSelection(),
5290 alignPanel.alignFrame, dassource,
5291 alignPanel.alignFrame.featureSettings,
5294 .addListener(new FetchFinishedListenerI()
5297 public void finished()
5299 AlignFrame.this.setMenusForViewport();
5302 dbRefFetcher.fetchDBRefs(false);
5308 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5309 MessageManager.formatMessage(
5310 "label.fetch_retrieve_from", new Object[]
5311 { src.getDbName() })));
5317 final DbSourceProxy[] dassource = otherdb
5318 .toArray(new DbSourceProxy[0]);
5320 DbSourceProxy src = otherdb.get(0);
5321 fetchr = new JMenuItem(MessageManager
5322 .formatMessage("label.fetch_all_param", new Object[]
5323 { src.getDbSource() }));
5324 fetchr.addActionListener(new ActionListener()
5327 public void actionPerformed(ActionEvent e)
5329 new Thread(new Runnable()
5335 boolean isNucleotide = alignPanel.alignFrame
5336 .getViewport().getAlignment()
5338 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5339 alignPanel.av.getSequenceSelection(),
5340 alignPanel.alignFrame, dassource,
5341 alignPanel.alignFrame.featureSettings,
5344 .addListener(new FetchFinishedListenerI()
5347 public void finished()
5349 AlignFrame.this.setMenusForViewport();
5352 dbRefFetcher.fetchDBRefs(false);
5358 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5359 MessageManager.formatMessage(
5360 "label.fetch_retrieve_from_all_sources",
5362 { Integer.valueOf(otherdb.size())
5364 src.getDbSource(), src.getDbName() })));
5367 // and then build the rest of the individual menus
5368 ifetch = new JMenu(MessageManager.formatMessage(
5369 "label.source_from_db_source", new Object[]
5370 { src.getDbSource() }));
5372 String imname = null;
5374 for (DbSourceProxy sproxy : otherdb)
5376 String dbname = sproxy.getDbName();
5377 String sname = dbname.length() > 5
5378 ? dbname.substring(0, 5) + "..."
5380 String msname = dbname.length() > 10
5381 ? dbname.substring(0, 10) + "..."
5385 imname = MessageManager
5386 .formatMessage("label.from_msname", new Object[]
5389 fetchr = new JMenuItem(msname);
5390 final DbSourceProxy[] dassrc = { sproxy };
5391 fetchr.addActionListener(new ActionListener()
5395 public void actionPerformed(ActionEvent e)
5397 new Thread(new Runnable()
5403 boolean isNucleotide = alignPanel.alignFrame
5404 .getViewport().getAlignment()
5406 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5407 alignPanel.av.getSequenceSelection(),
5408 alignPanel.alignFrame, dassrc,
5409 alignPanel.alignFrame.featureSettings,
5412 .addListener(new FetchFinishedListenerI()
5415 public void finished()
5417 AlignFrame.this.setMenusForViewport();
5420 dbRefFetcher.fetchDBRefs(false);
5426 fetchr.setToolTipText(
5427 "<html>" + MessageManager.formatMessage(
5428 "label.fetch_retrieve_from", new Object[]
5432 if (++icomp >= mcomp || i == (otherdb.size()))
5434 ifetch.setText(MessageManager.formatMessage(
5435 "label.source_to_target", imname, sname));
5437 ifetch = new JMenu();
5445 if (comp >= mcomp || dbi >= (dbclasses.length))
5447 dfetch.setText(MessageManager.formatMessage(
5448 "label.source_to_target", mname, dbclass));
5450 dfetch = new JMenu();
5463 * Left justify the whole alignment.
5466 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5468 AlignmentI al = viewport.getAlignment();
5470 viewport.firePropertyChange("alignment", null, al);
5474 * Right justify the whole alignment.
5477 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5479 AlignmentI al = viewport.getAlignment();
5481 viewport.firePropertyChange("alignment", null, al);
5485 public void setShowSeqFeatures(boolean b)
5487 showSeqFeatures.setSelected(b);
5488 viewport.setShowSequenceFeatures(b);
5495 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5496 * awt.event.ActionEvent)
5499 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5501 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5502 alignPanel.paintAlignment(false, false);
5509 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5513 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5515 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5516 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5524 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5525 * .event.ActionEvent)
5528 protected void showGroupConservation_actionPerformed(ActionEvent e)
5530 viewport.setShowGroupConservation(showGroupConservation.getState());
5531 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5538 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5539 * .event.ActionEvent)
5542 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5544 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5545 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5552 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5553 * .event.ActionEvent)
5556 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5558 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5559 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5563 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5565 showSequenceLogo.setState(true);
5566 viewport.setShowSequenceLogo(true);
5567 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5568 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5572 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5574 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5581 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5582 * .event.ActionEvent)
5585 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5587 if (avc.makeGroupsFromSelection())
5589 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5590 alignPanel.updateAnnotation();
5591 alignPanel.paintAlignment(true,
5592 viewport.needToUpdateStructureViews());
5596 public void clearAlignmentSeqRep()
5598 // TODO refactor alignmentseqrep to controller
5599 if (viewport.getAlignment().hasSeqrep())
5601 viewport.getAlignment().setSeqrep(null);
5602 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5603 alignPanel.updateAnnotation();
5604 alignPanel.paintAlignment(true, true);
5609 protected void createGroup_actionPerformed(ActionEvent e)
5611 if (avc.createGroup())
5613 if (applyAutoAnnotationSettings.isSelected())
5615 alignPanel.updateAnnotation(true, false);
5617 alignPanel.alignmentChanged();
5622 protected void unGroup_actionPerformed(ActionEvent e)
5626 alignPanel.alignmentChanged();
5631 * make the given alignmentPanel the currently selected tab
5633 * @param alignmentPanel
5635 public void setDisplayedView(AlignmentPanel alignmentPanel)
5637 if (!viewport.getSequenceSetId()
5638 .equals(alignmentPanel.av.getSequenceSetId()))
5640 throw new Error(MessageManager.getString(
5641 "error.implementation_error_cannot_show_view_alignment_frame"));
5643 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5644 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5646 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5651 * Action on selection of menu options to Show or Hide annotations.
5654 * @param forSequences
5655 * update sequence-related annotations
5656 * @param forAlignment
5657 * update non-sequence-related annotations
5660 protected void setAnnotationsVisibility(boolean visible,
5661 boolean forSequences, boolean forAlignment)
5663 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5664 .getAlignmentAnnotation();
5669 for (AlignmentAnnotation aa : anns)
5672 * don't display non-positional annotations on an alignment
5674 if (aa.annotations == null)
5678 boolean apply = (aa.sequenceRef == null && forAlignment)
5679 || (aa.sequenceRef != null && forSequences);
5682 aa.visible = visible;
5685 alignPanel.validateAnnotationDimensions(true);
5686 alignPanel.alignmentChanged();
5690 * Store selected annotation sort order for the view and repaint.
5693 protected void sortAnnotations_actionPerformed()
5695 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5697 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5698 alignPanel.paintAlignment(false, false);
5703 * @return alignment panels in this alignment frame
5705 public List<? extends AlignmentViewPanel> getAlignPanels()
5707 // alignPanels is never null
5708 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5713 * Open a new alignment window, with the cDNA associated with this (protein)
5714 * alignment, aligned as is the protein.
5716 protected void viewAsCdna_actionPerformed()
5718 // TODO no longer a menu action - refactor as required
5719 final AlignmentI alignment = getViewport().getAlignment();
5720 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5721 if (mappings == null)
5725 List<SequenceI> cdnaSeqs = new ArrayList<>();
5726 for (SequenceI aaSeq : alignment.getSequences())
5728 for (AlignedCodonFrame acf : mappings)
5730 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5734 * There is a cDNA mapping for this protein sequence - add to new
5735 * alignment. It will share the same dataset sequence as other mapped
5736 * cDNA (no new mappings need to be created).
5738 final Sequence newSeq = new Sequence(dnaSeq);
5739 newSeq.setDatasetSequence(dnaSeq);
5740 cdnaSeqs.add(newSeq);
5744 if (cdnaSeqs.size() == 0)
5746 // show a warning dialog no mapped cDNA
5749 AlignmentI cdna = new Alignment(
5750 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5751 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5752 AlignFrame.DEFAULT_HEIGHT);
5753 cdna.alignAs(alignment);
5754 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5756 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5757 AlignFrame.DEFAULT_HEIGHT);
5761 * Set visibility of dna/protein complement view (available when shown in a
5767 protected void showComplement_actionPerformed(boolean show)
5769 SplitContainerI sf = getSplitViewContainer();
5772 sf.setComplementVisible(this, show);
5777 * Generate the reverse (optionally complemented) of the selected sequences,
5778 * and add them to the alignment
5781 protected void showReverse_actionPerformed(boolean complement)
5783 AlignmentI al = null;
5786 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5787 al = dna.reverseCdna(complement);
5788 viewport.addAlignment(al, "");
5789 addHistoryItem(new EditCommand(
5790 MessageManager.getString("label.add_sequences"), Action.PASTE,
5791 al.getSequencesArray(), 0, al.getWidth(),
5792 viewport.getAlignment()));
5793 } catch (Exception ex)
5795 System.err.println(ex.getMessage());
5801 * Try to run a script in the Groovy console, having first ensured that this
5802 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5803 * be targeted at this alignment.
5806 protected void runGroovy_actionPerformed()
5808 Jalview.setCurrentAlignFrame(this);
5809 groovy.ui.Console console = Desktop.getGroovyConsole();
5810 if (console != null)
5814 console.runScript();
5815 } catch (Exception ex)
5817 System.err.println((ex.toString()));
5818 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5819 MessageManager.getString("label.couldnt_run_groovy_script"),
5820 MessageManager.getString("label.groovy_support_failed"),
5821 JvOptionPane.ERROR_MESSAGE);
5826 System.err.println("Can't run Groovy script as console not found");
5831 * Hides columns containing (or not containing) a specified feature, provided
5832 * that would not leave all columns hidden
5834 * @param featureType
5835 * @param columnsContaining
5838 public boolean hideFeatureColumns(String featureType,
5839 boolean columnsContaining)
5841 boolean notForHiding = avc.markColumnsContainingFeatures(
5842 columnsContaining, false, false, featureType);
5845 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5846 false, featureType))
5848 getViewport().hideSelectedColumns();
5856 protected void selectHighlightedColumns_actionPerformed(
5857 ActionEvent actionEvent)
5859 // include key modifier check in case user selects from menu
5860 avc.markHighlightedColumns(
5861 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5862 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5863 | ActionEvent.CTRL_MASK)) != 0);
5867 * Rebuilds the Colour menu, including any user-defined colours which have
5868 * been loaded either on startup or during the session
5870 public void buildColourMenu()
5872 colourMenu.removeAll();
5874 colourMenu.add(applyToAllGroups);
5875 colourMenu.add(textColour);
5876 colourMenu.addSeparator();
5878 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5879 viewport.getAlignment(), false);
5881 colourMenu.add(annotationColour);
5882 bg.add(annotationColour);
5883 colourMenu.addSeparator();
5884 colourMenu.add(conservationMenuItem);
5885 colourMenu.add(modifyConservation);
5886 colourMenu.add(abovePIDThreshold);
5887 colourMenu.add(modifyPID);
5889 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5890 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5894 * Open a dialog (if not already open) that allows the user to select and
5895 * calculate PCA or Tree analysis
5897 protected void openTreePcaDialog()
5899 if (alignPanel.getCalculationDialog() == null)
5901 new CalculationChooser(AlignFrame.this);
5906 * Sets the status of the HMMER menu
5908 public void updateHMMERStatus()
5910 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
5914 protected void loadVcf_actionPerformed()
5916 JalviewFileChooser chooser = new JalviewFileChooser(
5917 Cache.getProperty("LAST_DIRECTORY"));
5918 chooser.setFileView(new JalviewFileView());
5919 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5920 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5922 int value = chooser.showOpenDialog(null);
5924 if (value == JalviewFileChooser.APPROVE_OPTION)
5926 String choice = chooser.getSelectedFile().getPath();
5927 Cache.setProperty("LAST_DIRECTORY", choice);
5928 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5929 new VCFLoader(choice).loadVCF(seqs, this);
5935 class PrintThread extends Thread
5939 public PrintThread(AlignmentPanel ap)
5944 static PageFormat pf;
5949 PrinterJob printJob = PrinterJob.getPrinterJob();
5953 printJob.setPrintable(ap, pf);
5957 printJob.setPrintable(ap);
5960 if (printJob.printDialog())
5965 } catch (Exception PrintException)
5967 PrintException.printStackTrace();