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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Dimension;
27 import java.awt.Rectangle;
28 import java.awt.Toolkit;
29 import java.awt.datatransfer.Clipboard;
30 import java.awt.datatransfer.DataFlavor;
31 import java.awt.datatransfer.StringSelection;
32 import java.awt.datatransfer.Transferable;
33 import java.awt.dnd.DnDConstants;
34 import java.awt.dnd.DropTargetDragEvent;
35 import java.awt.dnd.DropTargetDropEvent;
36 import java.awt.dnd.DropTargetEvent;
37 import java.awt.dnd.DropTargetListener;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.FocusAdapter;
41 import java.awt.event.FocusEvent;
42 import java.awt.event.ItemEvent;
43 import java.awt.event.ItemListener;
44 import java.awt.event.KeyAdapter;
45 import java.awt.event.KeyEvent;
46 import java.awt.event.MouseEvent;
47 import java.awt.print.PageFormat;
48 import java.awt.print.PrinterJob;
49 import java.beans.PropertyChangeEvent;
51 import java.io.FileWriter;
52 import java.io.PrintWriter;
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.Deque;
57 import java.util.Enumeration;
58 import java.util.Hashtable;
59 import java.util.List;
60 import java.util.Vector;
62 import javax.swing.ButtonGroup;
63 import javax.swing.JCheckBoxMenuItem;
64 import javax.swing.JComponent;
65 import javax.swing.JEditorPane;
66 import javax.swing.JInternalFrame;
67 import javax.swing.JLabel;
68 import javax.swing.JLayeredPane;
69 import javax.swing.JMenu;
70 import javax.swing.JMenuItem;
71 import javax.swing.JPanel;
72 import javax.swing.JScrollPane;
73 import javax.swing.SwingUtilities;
75 import ext.vamsas.ServiceHandle;
76 import jalview.analysis.AlignmentSorter;
77 import jalview.analysis.AlignmentUtils;
78 import jalview.analysis.CrossRef;
79 import jalview.analysis.Dna;
80 import jalview.analysis.GeneticCodeI;
81 import jalview.analysis.ParseProperties;
82 import jalview.analysis.SequenceIdMatcher;
83 import jalview.api.AlignExportSettingsI;
84 import jalview.api.AlignViewControllerGuiI;
85 import jalview.api.AlignViewControllerI;
86 import jalview.api.AlignViewportI;
87 import jalview.api.AlignmentViewPanel;
88 import jalview.api.FeatureSettingsControllerI;
89 import jalview.api.FeatureSettingsModelI;
90 import jalview.api.SplitContainerI;
91 import jalview.api.ViewStyleI;
92 import jalview.api.analysis.SimilarityParamsI;
93 import jalview.bin.Cache;
94 import jalview.bin.Jalview;
95 import jalview.commands.CommandI;
96 import jalview.commands.EditCommand;
97 import jalview.commands.EditCommand.Action;
98 import jalview.commands.OrderCommand;
99 import jalview.commands.RemoveGapColCommand;
100 import jalview.commands.RemoveGapsCommand;
101 import jalview.commands.SlideSequencesCommand;
102 import jalview.commands.TrimRegionCommand;
103 import jalview.datamodel.AlignExportSettingsAdapter;
104 import jalview.datamodel.AlignedCodonFrame;
105 import jalview.datamodel.Alignment;
106 import jalview.datamodel.AlignmentAnnotation;
107 import jalview.datamodel.AlignmentExportData;
108 import jalview.datamodel.AlignmentI;
109 import jalview.datamodel.AlignmentOrder;
110 import jalview.datamodel.AlignmentView;
111 import jalview.datamodel.ColumnSelection;
112 import jalview.datamodel.HiddenColumns;
113 import jalview.datamodel.PDBEntry;
114 import jalview.datamodel.SeqCigar;
115 import jalview.datamodel.Sequence;
116 import jalview.datamodel.SequenceGroup;
117 import jalview.datamodel.SequenceI;
118 import jalview.gui.ColourMenuHelper.ColourChangeListener;
119 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
120 import jalview.io.AlignmentProperties;
121 import jalview.io.AnnotationFile;
122 import jalview.io.BackupFiles;
123 import jalview.io.BioJsHTMLOutput;
124 import jalview.io.DataSourceType;
125 import jalview.io.FileFormat;
126 import jalview.io.FileFormatI;
127 import jalview.io.FileFormats;
128 import jalview.io.FileLoader;
129 import jalview.io.FileParse;
130 import jalview.io.FormatAdapter;
131 import jalview.io.HtmlSvgOutput;
132 import jalview.io.IdentifyFile;
133 import jalview.io.JPredFile;
134 import jalview.io.JalviewFileChooser;
135 import jalview.io.JalviewFileView;
136 import jalview.io.JnetAnnotationMaker;
137 import jalview.io.NewickFile;
138 import jalview.io.ScoreMatrixFile;
139 import jalview.io.TCoffeeScoreFile;
140 import jalview.io.vcf.VCFLoader;
141 import jalview.jbgui.GAlignFrame;
142 import jalview.project.Jalview2XML;
143 import jalview.schemes.ColourSchemeI;
144 import jalview.schemes.ColourSchemes;
145 import jalview.schemes.ResidueColourScheme;
146 import jalview.schemes.TCoffeeColourScheme;
147 import jalview.util.ImageMaker.TYPE;
148 import jalview.util.MessageManager;
149 import jalview.util.Platform;
150 import jalview.viewmodel.AlignmentViewport;
151 import jalview.viewmodel.ViewportRanges;
152 import jalview.ws.DBRefFetcher;
153 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
154 import jalview.ws.jws1.Discoverer;
155 import jalview.ws.jws2.Jws2Discoverer;
156 import jalview.ws.jws2.jabaws2.Jws2Instance;
157 import jalview.ws.seqfetcher.DbSourceProxy;
163 * @version $Revision$
165 @SuppressWarnings("serial")
166 public class AlignFrame extends GAlignFrame implements DropTargetListener,
167 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
170 public static final int DEFAULT_WIDTH = 700;
172 public static final int DEFAULT_HEIGHT = 500;
175 * The currently displayed panel (selected tabbed view if more than one)
177 public AlignmentPanel alignPanel;
179 AlignViewport viewport;
181 public AlignViewControllerI avc;
183 List<AlignmentPanel> alignPanels = new ArrayList<>();
186 * Last format used to load or save alignments in this window
188 FileFormatI currentFileFormat = null;
191 * Current filename for this alignment
193 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 // setBackground(Color.white); // BH 2019
351 if (!Jalview.isHeadlessMode())
353 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
356 avc = new jalview.controller.AlignViewController(this, viewport,
358 if (viewport.getAlignmentConservationAnnotation() == null)
360 // BLOSUM62Colour.setEnabled(false);
361 conservationMenuItem.setEnabled(false);
362 modifyConservation.setEnabled(false);
363 // PIDColour.setEnabled(false);
364 // abovePIDThreshold.setEnabled(false);
365 // modifyPID.setEnabled(false);
368 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
371 if (sortby.equals("Id"))
373 sortIDMenuItem_actionPerformed(null);
375 else if (sortby.equals("Pairwise Identity"))
377 sortPairwiseMenuItem_actionPerformed(null);
381 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
383 setMenusFromViewport(viewport);
384 buildSortByAnnotationScoresMenu();
385 calculateTree.addActionListener(new ActionListener()
389 public void actionPerformed(ActionEvent e)
396 if (Desktop.desktop != null)
398 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
399 if (!Platform.isJS())
401 addServiceListeners();
406 if (viewport.getWrapAlignment())
408 wrapMenuItem_actionPerformed(null);
411 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
413 this.overviewMenuItem_actionPerformed(null);
418 final List<AlignmentPanel> selviews = new ArrayList<>();
419 final List<AlignmentPanel> origview = new ArrayList<>();
420 final String menuLabel = MessageManager
421 .getString("label.copy_format_from");
422 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
423 new ViewSetProvider()
427 public AlignmentPanel[] getAllAlignmentPanels()
430 origview.add(alignPanel);
431 // make an array of all alignment panels except for this one
432 List<AlignmentPanel> aps = new ArrayList<>(
433 Arrays.asList(Desktop.getAlignmentPanels(null)));
434 aps.remove(AlignFrame.this.alignPanel);
435 return aps.toArray(new AlignmentPanel[aps.size()]);
437 }, selviews, new ItemListener()
441 public void itemStateChanged(ItemEvent e)
443 if (origview.size() > 0)
445 final AlignmentPanel ap = origview.get(0);
448 * Copy the ViewStyle of the selected panel to 'this one'.
449 * Don't change value of 'scaleProteinAsCdna' unless copying
452 ViewStyleI vs = selviews.get(0).getAlignViewport()
454 boolean fromSplitFrame = selviews.get(0)
455 .getAlignViewport().getCodingComplement() != null;
458 vs.setScaleProteinAsCdna(ap.getAlignViewport()
459 .getViewStyle().isScaleProteinAsCdna());
461 ap.getAlignViewport().setViewStyle(vs);
464 * Also rescale ViewStyle of SplitFrame complement if there is
465 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
466 * the whole ViewStyle (allow cDNA protein to have different
469 AlignViewportI complement = ap.getAlignViewport()
470 .getCodingComplement();
471 if (complement != null && vs.isScaleProteinAsCdna())
473 AlignFrame af = Desktop.getAlignFrameFor(complement);
474 ((SplitFrame) af.getSplitViewContainer())
476 af.setMenusForViewport();
480 ap.setSelected(true);
481 ap.alignFrame.setMenusForViewport();
486 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
487 .indexOf("devel") > -1
488 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
489 .indexOf("test") > -1)
491 formatMenu.add(vsel);
493 addFocusListener(new FocusAdapter()
496 public void focusGained(FocusEvent e)
498 Jalview.setCurrentAlignFrame(AlignFrame.this);
505 * Change the filename and format for the alignment, and enable the 'reload'
506 * button functionality.
513 public void setFileName(String file, FileFormatI format)
516 setFileFormat(format);
517 reload.setEnabled(true);
521 * JavaScript will have this, maybe others. More dependable than a file name
522 * and maintains a reference to the actual bytes loaded.
526 public void setFileObject(File file)
528 this.fileObject = file;
532 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
535 void addKeyListener()
537 addKeyListener(new KeyAdapter()
540 public void keyPressed(KeyEvent evt)
542 if (viewport.cursorMode
543 && ((evt.getKeyCode() >= KeyEvent.VK_0
544 && evt.getKeyCode() <= KeyEvent.VK_9)
545 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
546 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
547 && Character.isDigit(evt.getKeyChar()))
549 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
552 switch (evt.getKeyCode())
555 case 27: // escape key
556 deselectAllSequenceMenuItem_actionPerformed(null);
560 case KeyEvent.VK_DOWN:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 moveSelectedSequences(false);
565 if (viewport.cursorMode)
567 alignPanel.getSeqPanel().moveCursor(0, 1);
572 if (evt.isAltDown() || !viewport.cursorMode)
574 moveSelectedSequences(true);
576 if (viewport.cursorMode)
578 alignPanel.getSeqPanel().moveCursor(0, -1);
583 case KeyEvent.VK_LEFT:
584 if (evt.isAltDown() || !viewport.cursorMode)
586 slideSequences(false,
587 alignPanel.getSeqPanel().getKeyboardNo1());
591 alignPanel.getSeqPanel().moveCursor(-1, 0);
596 case KeyEvent.VK_RIGHT:
597 if (evt.isAltDown() || !viewport.cursorMode)
599 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
603 alignPanel.getSeqPanel().moveCursor(1, 0);
607 case KeyEvent.VK_SPACE:
608 if (viewport.cursorMode)
610 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
611 || evt.isShiftDown() || evt.isAltDown());
615 // case KeyEvent.VK_A:
616 // if (viewport.cursorMode)
618 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
619 // //System.out.println("A");
623 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
624 * System.out.println("closing bracket"); } break;
626 case KeyEvent.VK_DELETE:
627 case KeyEvent.VK_BACK_SPACE:
628 if (!viewport.cursorMode)
630 cut_actionPerformed();
634 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
635 || evt.isShiftDown() || evt.isAltDown());
641 if (viewport.cursorMode)
643 alignPanel.getSeqPanel().setCursorRow();
647 if (viewport.cursorMode && !evt.isControlDown())
649 alignPanel.getSeqPanel().setCursorColumn();
653 if (viewport.cursorMode)
655 alignPanel.getSeqPanel().setCursorPosition();
659 case KeyEvent.VK_ENTER:
660 case KeyEvent.VK_COMMA:
661 if (viewport.cursorMode)
663 alignPanel.getSeqPanel().setCursorRowAndColumn();
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
674 if (viewport.cursorMode)
676 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
681 viewport.cursorMode = !viewport.cursorMode;
682 setStatus(MessageManager
683 .formatMessage("label.keyboard_editing_mode", new String[]
684 { (viewport.cursorMode ? "on" : "off") }));
685 if (viewport.cursorMode)
687 ViewportRanges ranges = viewport.getRanges();
688 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
690 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
693 alignPanel.getSeqPanel().seqCanvas.repaint();
699 Help.showHelpWindow();
700 } catch (Exception ex)
702 ex.printStackTrace();
707 boolean toggleSeqs = !evt.isControlDown();
708 boolean toggleCols = !evt.isShiftDown();
709 toggleHiddenRegions(toggleSeqs, toggleCols);
714 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
715 boolean modifyExisting = true; // always modify, don't clear
716 // evt.isShiftDown();
717 boolean invertHighlighted = evt.isAltDown();
718 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
722 case KeyEvent.VK_PAGE_UP:
723 viewport.getRanges().pageUp();
725 case KeyEvent.VK_PAGE_DOWN:
726 viewport.getRanges().pageDown();
732 public void keyReleased(KeyEvent evt)
734 switch (evt.getKeyCode())
736 case KeyEvent.VK_LEFT:
737 if (evt.isAltDown() || !viewport.cursorMode)
739 viewport.firePropertyChange("alignment", null,
740 viewport.getAlignment().getSequences());
744 case KeyEvent.VK_RIGHT:
745 if (evt.isAltDown() || !viewport.cursorMode)
747 viewport.firePropertyChange("alignment", null,
748 viewport.getAlignment().getSequences());
756 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
758 ap.alignFrame = this;
759 avc = new jalview.controller.AlignViewController(this, viewport,
764 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
766 int aSize = alignPanels.size();
768 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
770 if (aSize == 1 && ap.av.getViewName() == null)
772 this.getContentPane().add(ap, BorderLayout.CENTER);
778 setInitialTabVisible();
781 expandViews.setEnabled(true);
782 gatherViews.setEnabled(true);
783 tabbedPane.addTab(ap.av.getViewName(), ap);
785 ap.setVisible(false);
790 if (ap.av.isPadGaps())
792 ap.av.getAlignment().padGaps();
794 ap.av.updateConservation(ap);
795 ap.av.updateConsensus(ap);
796 ap.av.updateStrucConsensus(ap);
800 public void setInitialTabVisible()
802 expandViews.setEnabled(true);
803 gatherViews.setEnabled(true);
804 tabbedPane.setVisible(true);
805 AlignmentPanel first = alignPanels.get(0);
806 tabbedPane.addTab(first.av.getViewName(), first);
807 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
810 public AlignViewport getViewport()
815 /* Set up intrinsic listeners for dynamically generated GUI bits. */
816 private void addServiceListeners()
818 final java.beans.PropertyChangeListener thisListener;
819 Desktop.instance.addJalviewPropertyChangeListener("services",
820 thisListener = new java.beans.PropertyChangeListener()
823 public void propertyChange(PropertyChangeEvent evt)
825 // // System.out.println("Discoverer property change.");
826 // if (evt.getPropertyName().equals("services"))
828 SwingUtilities.invokeLater(new Runnable()
835 "Rebuild WS Menu for service change");
836 BuildWebServiceMenu();
843 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
846 public void internalFrameClosed(
847 javax.swing.event.InternalFrameEvent evt)
849 // System.out.println("deregistering discoverer listener");
850 Desktop.instance.removeJalviewPropertyChangeListener("services",
852 closeMenuItem_actionPerformed(true);
855 // Finally, build the menu once to get current service state
856 new Thread(new Runnable()
861 BuildWebServiceMenu();
867 * Configure menu items that vary according to whether the alignment is
868 * nucleotide or protein
870 public void setGUINucleotide()
872 AlignmentI al = getViewport().getAlignment();
873 boolean nucleotide = al.isNucleotide();
875 loadVcf.setVisible(nucleotide);
876 showTranslation.setVisible(nucleotide);
877 showReverse.setVisible(nucleotide);
878 showReverseComplement.setVisible(nucleotide);
879 conservationMenuItem.setEnabled(!nucleotide);
881 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
882 showGroupConservation.setEnabled(!nucleotide);
884 showComplementMenuItem
885 .setText(nucleotide ? MessageManager.getString("label.protein")
886 : MessageManager.getString("label.nucleotide"));
890 * set up menus for the current viewport. This may be called after any
891 * operation that affects the data in the current view (selection changed,
892 * etc) to update the menus to reflect the new state.
895 public void setMenusForViewport()
897 setMenusFromViewport(viewport);
901 * Need to call this method when tabs are selected for multiple views, or when
902 * loading from Jalview2XML.java
907 public void setMenusFromViewport(AlignViewport av)
909 padGapsMenuitem.setSelected(av.isPadGaps());
910 colourTextMenuItem.setSelected(av.isShowColourText());
911 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
912 modifyPID.setEnabled(abovePIDThreshold.isSelected());
913 conservationMenuItem.setSelected(av.getConservationSelected());
914 modifyConservation.setEnabled(conservationMenuItem.isSelected());
915 seqLimits.setSelected(av.getShowJVSuffix());
916 idRightAlign.setSelected(av.isRightAlignIds());
917 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
918 renderGapsMenuItem.setSelected(av.isRenderGaps());
919 wrapMenuItem.setSelected(av.getWrapAlignment());
920 scaleAbove.setVisible(av.getWrapAlignment());
921 scaleLeft.setVisible(av.getWrapAlignment());
922 scaleRight.setVisible(av.getWrapAlignment());
923 annotationPanelMenuItem.setState(av.isShowAnnotation());
925 * Show/hide annotations only enabled if annotation panel is shown
927 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
928 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
929 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 viewBoxesMenuItem.setSelected(av.getShowBoxes());
932 viewTextMenuItem.setSelected(av.getShowText());
933 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
934 showGroupConsensus.setSelected(av.isShowGroupConsensus());
935 showGroupConservation.setSelected(av.isShowGroupConservation());
936 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
937 showSequenceLogo.setSelected(av.isShowSequenceLogo());
938 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
940 ColourMenuHelper.setColourSelected(colourMenu,
941 av.getGlobalColourScheme());
943 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
944 hiddenMarkers.setState(av.getShowHiddenMarkers());
945 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
946 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
947 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
948 autoCalculate.setSelected(av.autoCalculateConsensus);
949 sortByTree.setSelected(av.sortByTree);
950 listenToViewSelections.setSelected(av.followSelection);
952 showProducts.setEnabled(canShowProducts());
953 setGroovyEnabled(Desktop.getGroovyConsole() != null);
959 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
963 public void setGroovyEnabled(boolean b)
965 runGroovy.setEnabled(b);
968 private IProgressIndicator progressBar;
973 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
976 public void setProgressBar(String message, long id)
978 progressBar.setProgressBar(message, id);
982 public void registerHandler(final long id,
983 final IProgressIndicatorHandler handler)
985 progressBar.registerHandler(id, handler);
990 * @return true if any progress bars are still active
993 public boolean operationInProgress()
995 return progressBar.operationInProgress();
999 * Sets the text of the status bar. Note that setting a null or empty value
1000 * will cause the status bar to be hidden, with possibly undesirable flicker
1001 * of the screen layout.
1004 public void setStatus(String text)
1006 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1010 * Added so Castor Mapping file can obtain Jalview Version
1012 public String getVersion()
1014 return jalview.bin.Cache.getProperty("VERSION");
1017 public FeatureRenderer getFeatureRenderer()
1019 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1023 public void fetchSequence_actionPerformed()
1025 new SequenceFetcher(this);
1029 public void addFromFile_actionPerformed(ActionEvent e)
1031 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1035 public void reload_actionPerformed(ActionEvent e)
1037 if (fileName != null)
1039 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1040 // originating file's format
1041 // TODO: work out how to recover feature settings for correct view(s) when
1042 // file is reloaded.
1043 if (FileFormat.Jalview.equals(currentFileFormat))
1045 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1046 for (int i = 0; i < frames.length; i++)
1048 if (frames[i] instanceof AlignFrame && frames[i] != this
1049 && ((AlignFrame) frames[i]).fileName != null
1050 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1054 frames[i].setSelected(true);
1055 Desktop.instance.closeAssociatedWindows();
1056 } catch (java.beans.PropertyVetoException ex)
1062 Desktop.instance.closeAssociatedWindows();
1064 FileLoader loader = new FileLoader();
1065 DataSourceType protocol = fileName.startsWith("http:")
1066 ? DataSourceType.URL
1067 : DataSourceType.FILE;
1068 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1072 Rectangle bounds = this.getBounds();
1074 FileLoader loader = new FileLoader();
1076 AlignFrame newframe = null;
1078 if (fileObject == null)
1081 DataSourceType protocol = (fileName.startsWith("http:")
1082 ? DataSourceType.URL
1083 : DataSourceType.FILE);
1084 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1089 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1090 DataSourceType.FILE, currentFileFormat);
1093 newframe.setBounds(bounds);
1094 if (featureSettings != null && featureSettings.isShowing())
1096 final Rectangle fspos = featureSettings.frame.getBounds();
1097 // TODO: need a 'show feature settings' function that takes bounds -
1098 // need to refactor Desktop.addFrame
1099 newframe.featureSettings_actionPerformed(null);
1100 final FeatureSettings nfs = newframe.featureSettings;
1101 SwingUtilities.invokeLater(new Runnable()
1106 nfs.frame.setBounds(fspos);
1109 this.featureSettings.close();
1110 this.featureSettings = null;
1112 this.closeMenuItem_actionPerformed(true);
1118 public void addFromText_actionPerformed(ActionEvent e)
1121 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1125 public void addFromURL_actionPerformed(ActionEvent e)
1127 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1131 public void save_actionPerformed(ActionEvent e)
1133 if (fileName == null || (currentFileFormat == null)
1134 || fileName.startsWith("http"))
1136 saveAs_actionPerformed();
1140 saveAlignment(fileName, currentFileFormat);
1145 * Saves the alignment to a file with a name chosen by the user, if necessary
1146 * warning if a file would be overwritten
1149 public void saveAs_actionPerformed()
1151 String format = currentFileFormat == null ? null
1152 : currentFileFormat.getName();
1153 JalviewFileChooser chooser = JalviewFileChooser
1154 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1156 chooser.setFileView(new JalviewFileView());
1157 chooser.setDialogTitle(
1158 MessageManager.getString("label.save_alignment_to_file"));
1159 chooser.setToolTipText(MessageManager.getString("action.save"));
1161 int value = chooser.showSaveDialog(this);
1163 if (value != JalviewFileChooser.APPROVE_OPTION)
1167 currentFileFormat = chooser.getSelectedFormat();
1168 // todo is this (2005) test now obsolete - value is never null?
1169 while (currentFileFormat == null)
1171 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1173 .getString("label.select_file_format_before_saving"),
1174 MessageManager.getString("label.file_format_not_specified"),
1175 JvOptionPane.WARNING_MESSAGE);
1176 currentFileFormat = chooser.getSelectedFormat();
1177 value = chooser.showSaveDialog(this);
1178 if (value != JalviewFileChooser.APPROVE_OPTION)
1184 fileName = chooser.getSelectedFile().getPath();
1186 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1187 Cache.setProperty("LAST_DIRECTORY", fileName);
1188 saveAlignment(fileName, currentFileFormat);
1191 boolean lastSaveSuccessful = false;
1193 FileFormatI lastFormatSaved;
1195 String lastFilenameSaved;
1198 * Raise a dialog or status message for the last call to saveAlignment.
1200 * @return true if last call to saveAlignment(file, format) was successful.
1202 public boolean isSaveAlignmentSuccessful()
1205 if (!lastSaveSuccessful)
1207 JvOptionPane.showInternalMessageDialog(this, MessageManager
1208 .formatMessage("label.couldnt_save_file", new Object[]
1209 { lastFilenameSaved }),
1210 MessageManager.getString("label.error_saving_file"),
1211 JvOptionPane.WARNING_MESSAGE);
1216 setStatus(MessageManager.formatMessage(
1217 "label.successfully_saved_to_file_in_format", new Object[]
1218 { lastFilenameSaved, lastFormatSaved }));
1221 return lastSaveSuccessful;
1225 * Saves the alignment to the specified file path, in the specified format,
1226 * which may be an alignment format, or Jalview project format. If the
1227 * alignment has hidden regions, or the format is one capable of including
1228 * non-sequence data (features, annotations, groups), then the user may be
1229 * prompted to specify what to include in the output.
1234 public void saveAlignment(String file, FileFormatI format)
1236 lastSaveSuccessful = true;
1237 lastFilenameSaved = file;
1238 lastFormatSaved = format;
1240 if (FileFormat.Jalview.equals(format))
1242 String shortName = title;
1243 if (shortName.indexOf(File.separatorChar) > -1)
1245 shortName = shortName.substring(
1246 shortName.lastIndexOf(File.separatorChar) + 1);
1248 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file, shortName);
1250 statusBar.setText(MessageManager.formatMessage(
1251 "label.successfully_saved_to_file_in_format", new Object[]
1252 { fileName, format }));
1257 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1258 Runnable cancelAction = new Runnable()
1263 lastSaveSuccessful = false;
1266 Runnable outputAction = new Runnable()
1271 // todo defer this to inside formatSequences (or later)
1272 AlignmentExportData exportData = viewport
1273 .getAlignExportData(options);
1274 String output = new FormatAdapter(alignPanel, options)
1275 .formatSequences(format, exportData.getAlignment(),
1276 exportData.getOmitHidden(),
1277 exportData.getStartEndPostions(),
1278 viewport.getAlignment().getHiddenColumns());
1281 lastSaveSuccessful = false;
1285 // create backupfiles object and get new temp filename destination
1286 boolean doBackup = BackupFiles.getEnabled();
1287 BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1290 String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1291 PrintWriter out = new PrintWriter(
1292 new FileWriter(tempFilePath));
1296 AlignFrame.this.setTitle(file);
1297 statusBar.setText(MessageManager.formatMessage(
1298 "label.successfully_saved_to_file_in_format", new Object[]
1299 { fileName, format.getName() }));
1300 lastSaveSuccessful = true;
1301 } catch (Exception ex)
1303 lastSaveSuccessful = false;
1304 ex.printStackTrace();
1309 backupfiles.setWriteSuccess(lastSaveSuccessful);
1310 // do the backup file roll and rename the temp file to actual file
1311 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1318 * show dialog with export options if applicable; else just do it
1320 if (AlignExportOptions.isNeeded(viewport, format))
1322 AlignExportOptions choices = new AlignExportOptions(
1323 alignPanel.getAlignViewport(), format, options);
1324 choices.setResponseAction(0, outputAction);
1325 choices.setResponseAction(1, cancelAction);
1326 choices.showDialog();
1335 * Outputs the alignment to textbox in the requested format, if necessary
1336 * first prompting the user for whether to include hidden regions or
1339 * @param fileFormatName
1342 protected void outputText_actionPerformed(String fileFormatName)
1344 FileFormatI fileFormat = FileFormats.getInstance()
1345 .forName(fileFormatName);
1346 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1347 Runnable outputAction = new Runnable()
1352 // todo defer this to inside formatSequences (or later)
1353 AlignmentExportData exportData = viewport
1354 .getAlignExportData(options);
1355 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1356 cap.setForInput(null);
1359 FileFormatI format = fileFormat;
1360 cap.setText(new FormatAdapter(alignPanel, options)
1361 .formatSequences(format, exportData.getAlignment(),
1362 exportData.getOmitHidden(),
1363 exportData.getStartEndPostions(),
1364 viewport.getAlignment().getHiddenColumns()));
1365 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1366 "label.alignment_output_command", new Object[]
1367 { fileFormat.getName() }), 600, 500);
1368 } catch (OutOfMemoryError oom)
1370 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1378 * show dialog with export options if applicable; else just do it
1380 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1382 AlignExportOptions choices = new AlignExportOptions(
1383 alignPanel.getAlignViewport(), fileFormat, options);
1384 choices.setResponseAction(0, outputAction);
1385 choices.showDialog();
1400 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1402 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1403 htmlSVG.exportHTML(null);
1407 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1409 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1410 bjs.exportHTML(null);
1413 public void createImageMap(File file, String image)
1415 alignPanel.makePNGImageMap(file, image);
1419 * Creates a PNG image of the alignment and writes it to the given file. If
1420 * the file is null, the user is prompted to choose a file.
1425 public void createPNG(File f)
1427 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1431 * Creates an EPS image of the alignment and writes it to the given file. If
1432 * the file is null, the user is prompted to choose a file.
1437 public void createEPS(File f)
1439 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1443 * Creates an SVG image of the alignment and writes it to the given file. If
1444 * the file is null, the user is prompted to choose a file.
1449 public void createSVG(File f)
1451 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1455 public void pageSetup_actionPerformed(ActionEvent e)
1457 PrinterJob printJob = PrinterJob.getPrinterJob();
1458 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1468 public void printMenuItem_actionPerformed(ActionEvent e)
1470 // Putting in a thread avoids Swing painting problems
1471 PrintThread thread = new PrintThread(alignPanel);
1476 public void exportFeatures_actionPerformed(ActionEvent e)
1478 new AnnotationExporter(alignPanel).exportFeatures();
1482 public void exportAnnotations_actionPerformed(ActionEvent e)
1484 new AnnotationExporter(alignPanel).exportAnnotations();
1488 public void associatedData_actionPerformed(ActionEvent e)
1490 final JalviewFileChooser chooser = new JalviewFileChooser(
1491 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1492 chooser.setFileView(new JalviewFileView());
1493 String tooltip = MessageManager.getString("label.load_jalview_annotations");
1494 chooser.setDialogTitle(tooltip);
1495 chooser.setToolTipText(tooltip);
1496 chooser.setResponseHandler(0, new Runnable()
1501 String choice = chooser.getSelectedFile().getPath();
1502 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1503 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1507 chooser.showOpenDialog(this);
1511 * Close the current view or all views in the alignment frame. If the frame
1512 * only contains one view then the alignment will be removed from memory.
1514 * @param closeAllTabs
1517 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1519 if (alignPanels != null && alignPanels.size() < 2)
1521 closeAllTabs = true;
1526 if (alignPanels != null)
1530 if (this.isClosed())
1532 // really close all the windows - otherwise wait till
1533 // setClosed(true) is called
1534 for (int i = 0; i < alignPanels.size(); i++)
1536 AlignmentPanel ap = alignPanels.get(i);
1543 closeView(alignPanel);
1548 if (featureSettings != null && featureSettings.isOpen())
1550 featureSettings.close();
1551 featureSettings = null;
1554 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1555 * be called recursively, with the frame now in 'closed' state
1557 this.setClosed(true);
1559 } catch (Exception ex)
1561 ex.printStackTrace();
1566 * Close the specified panel and close up tabs appropriately.
1568 * @param panelToClose
1570 public void closeView(AlignmentPanel panelToClose)
1572 int index = tabbedPane.getSelectedIndex();
1573 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1574 alignPanels.remove(panelToClose);
1575 panelToClose.closePanel();
1576 panelToClose = null;
1578 tabbedPane.removeTabAt(closedindex);
1579 tabbedPane.validate();
1581 if (index > closedindex || index == tabbedPane.getTabCount())
1583 // modify currently selected tab index if necessary.
1587 this.tabSelectionChanged(index);
1593 void updateEditMenuBar()
1596 if (viewport.getHistoryList().size() > 0)
1598 undoMenuItem.setEnabled(true);
1599 CommandI command = viewport.getHistoryList().peek();
1600 undoMenuItem.setText(MessageManager
1601 .formatMessage("label.undo_command", new Object[]
1602 { command.getDescription() }));
1606 undoMenuItem.setEnabled(false);
1607 undoMenuItem.setText(MessageManager.getString("action.undo"));
1610 if (viewport.getRedoList().size() > 0)
1612 redoMenuItem.setEnabled(true);
1614 CommandI command = viewport.getRedoList().peek();
1615 redoMenuItem.setText(MessageManager
1616 .formatMessage("label.redo_command", new Object[]
1617 { command.getDescription() }));
1621 redoMenuItem.setEnabled(false);
1622 redoMenuItem.setText(MessageManager.getString("action.redo"));
1627 public void addHistoryItem(CommandI command)
1629 if (command.getSize() > 0)
1631 viewport.addToHistoryList(command);
1632 viewport.clearRedoList();
1633 updateEditMenuBar();
1634 viewport.updateHiddenColumns();
1635 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1636 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1637 // viewport.getColumnSelection()
1638 // .getHiddenColumns().size() > 0);
1644 * @return alignment objects for all views
1646 AlignmentI[] getViewAlignments()
1648 if (alignPanels != null)
1650 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1652 for (AlignmentPanel ap : alignPanels)
1654 als[i++] = ap.av.getAlignment();
1658 if (viewport != null)
1660 return new AlignmentI[] { viewport.getAlignment() };
1672 protected void undoMenuItem_actionPerformed(ActionEvent e)
1674 if (viewport.getHistoryList().isEmpty())
1678 CommandI command = viewport.getHistoryList().pop();
1679 viewport.addToRedoList(command);
1680 command.undoCommand(getViewAlignments());
1682 AlignmentViewport originalSource = getOriginatingSource(command);
1683 updateEditMenuBar();
1685 if (originalSource != null)
1687 if (originalSource != viewport)
1690 "Implementation worry: mismatch of viewport origin for undo");
1692 originalSource.updateHiddenColumns();
1693 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1695 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1696 // viewport.getColumnSelection()
1697 // .getHiddenColumns().size() > 0);
1698 originalSource.firePropertyChange("alignment", null,
1699 originalSource.getAlignment().getSequences());
1710 protected void redoMenuItem_actionPerformed(ActionEvent e)
1712 if (viewport.getRedoList().size() < 1)
1717 CommandI command = viewport.getRedoList().pop();
1718 viewport.addToHistoryList(command);
1719 command.doCommand(getViewAlignments());
1721 AlignmentViewport originalSource = getOriginatingSource(command);
1722 updateEditMenuBar();
1724 if (originalSource != null)
1727 if (originalSource != viewport)
1730 "Implementation worry: mismatch of viewport origin for redo");
1732 originalSource.updateHiddenColumns();
1733 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1735 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1736 // viewport.getColumnSelection()
1737 // .getHiddenColumns().size() > 0);
1738 originalSource.firePropertyChange("alignment", null,
1739 originalSource.getAlignment().getSequences());
1743 AlignmentViewport getOriginatingSource(CommandI command)
1745 AlignmentViewport originalSource = null;
1746 // For sequence removal and addition, we need to fire
1747 // the property change event FROM the viewport where the
1748 // original alignment was altered
1749 AlignmentI al = null;
1750 if (command instanceof EditCommand)
1752 EditCommand editCommand = (EditCommand) command;
1753 al = editCommand.getAlignment();
1754 List<Component> comps = PaintRefresher.components
1755 .get(viewport.getSequenceSetId());
1757 for (Component comp : comps)
1759 if (comp instanceof AlignmentPanel)
1761 if (al == ((AlignmentPanel) comp).av.getAlignment())
1763 originalSource = ((AlignmentPanel) comp).av;
1770 if (originalSource == null)
1772 // The original view is closed, we must validate
1773 // the current view against the closed view first
1776 PaintRefresher.validateSequences(al, viewport.getAlignment());
1779 originalSource = viewport;
1782 return originalSource;
1791 public void moveSelectedSequences(boolean up)
1793 SequenceGroup sg = viewport.getSelectionGroup();
1799 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1800 viewport.getHiddenRepSequences(), up);
1801 alignPanel.paintAlignment(true, false);
1804 synchronized void slideSequences(boolean right, int size)
1806 List<SequenceI> sg = new ArrayList<>();
1807 if (viewport.cursorMode)
1809 sg.add(viewport.getAlignment()
1810 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1812 else if (viewport.getSelectionGroup() != null
1813 && viewport.getSelectionGroup().getSize() != viewport
1814 .getAlignment().getHeight())
1816 sg = viewport.getSelectionGroup()
1817 .getSequences(viewport.getHiddenRepSequences());
1825 List<SequenceI> invertGroup = new ArrayList<>();
1827 for (SequenceI seq : viewport.getAlignment().getSequences())
1829 if (!sg.contains(seq))
1831 invertGroup.add(seq);
1835 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1837 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1838 for (int i = 0; i < invertGroup.size(); i++)
1840 seqs2[i] = invertGroup.get(i);
1843 SlideSequencesCommand ssc;
1846 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1847 viewport.getGapCharacter());
1851 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1852 viewport.getGapCharacter());
1855 int groupAdjustment = 0;
1856 if (ssc.getGapsInsertedBegin() && right)
1858 if (viewport.cursorMode)
1860 alignPanel.getSeqPanel().moveCursor(size, 0);
1864 groupAdjustment = size;
1867 else if (!ssc.getGapsInsertedBegin() && !right)
1869 if (viewport.cursorMode)
1871 alignPanel.getSeqPanel().moveCursor(-size, 0);
1875 groupAdjustment = -size;
1879 if (groupAdjustment != 0)
1881 viewport.getSelectionGroup().setStartRes(
1882 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1883 viewport.getSelectionGroup().setEndRes(
1884 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1888 * just extend the last slide command if compatible; but not if in
1889 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1891 boolean appendHistoryItem = false;
1892 Deque<CommandI> historyList = viewport.getHistoryList();
1893 boolean inSplitFrame = getSplitViewContainer() != null;
1894 if (!inSplitFrame && historyList != null && historyList.size() > 0
1895 && historyList.peek() instanceof SlideSequencesCommand)
1897 appendHistoryItem = ssc.appendSlideCommand(
1898 (SlideSequencesCommand) historyList.peek());
1901 if (!appendHistoryItem)
1903 addHistoryItem(ssc);
1916 protected void copy_actionPerformed()
1918 if (viewport.getSelectionGroup() == null)
1922 // TODO: preserve the ordering of displayed alignment annotation in any
1923 // internal paste (particularly sequence associated annotation)
1924 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1925 String[] omitHidden = null;
1927 if (viewport.hasHiddenColumns())
1929 omitHidden = viewport.getViewAsString(true);
1932 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1933 seqs, omitHidden, null);
1935 StringSelection ss = new StringSelection(output);
1939 jalview.gui.Desktop.internalCopy = true;
1940 // Its really worth setting the clipboard contents
1941 // to empty before setting the large StringSelection!!
1942 Toolkit.getDefaultToolkit().getSystemClipboard()
1943 .setContents(new StringSelection(""), null);
1945 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1947 } catch (OutOfMemoryError er)
1949 new OOMWarning("copying region", er);
1953 HiddenColumns hiddenColumns = null;
1954 if (viewport.hasHiddenColumns())
1956 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1957 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1959 // create new HiddenColumns object with copy of hidden regions
1960 // between startRes and endRes, offset by startRes
1961 hiddenColumns = new HiddenColumns(
1962 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1963 hiddenCutoff, hiddenOffset);
1966 Desktop.jalviewClipboard = new Object[] { seqs,
1967 viewport.getAlignment().getDataset(), hiddenColumns };
1968 setStatus(MessageManager.formatMessage(
1969 "label.copied_sequences_to_clipboard", new Object[]
1970 { Integer.valueOf(seqs.length).toString() }));
1980 protected void pasteNew_actionPerformed(ActionEvent e)
1992 protected void pasteThis_actionPerformed(ActionEvent e)
1998 * Paste contents of Jalview clipboard
2000 * @param newAlignment
2001 * true to paste to a new alignment, otherwise add to this.
2003 void paste(boolean newAlignment)
2005 boolean externalPaste = true;
2008 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2009 Transferable contents = c.getContents(this);
2011 if (contents == null)
2020 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2021 if (str.length() < 1)
2026 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2028 } catch (OutOfMemoryError er)
2030 new OOMWarning("Out of memory pasting sequences!!", er);
2034 SequenceI[] sequences;
2035 boolean annotationAdded = false;
2036 AlignmentI alignment = null;
2038 if (Desktop.jalviewClipboard != null)
2040 // The clipboard was filled from within Jalview, we must use the
2042 // And dataset from the copied alignment
2043 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2044 // be doubly sure that we create *new* sequence objects.
2045 sequences = new SequenceI[newseq.length];
2046 for (int i = 0; i < newseq.length; i++)
2048 sequences[i] = new Sequence(newseq[i]);
2050 alignment = new Alignment(sequences);
2051 externalPaste = false;
2055 // parse the clipboard as an alignment.
2056 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2058 sequences = alignment.getSequencesArray();
2062 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2068 if (Desktop.jalviewClipboard != null)
2070 // dataset is inherited
2071 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2075 // new dataset is constructed
2076 alignment.setDataset(null);
2078 alwidth = alignment.getWidth() + 1;
2082 AlignmentI pastedal = alignment; // preserve pasted alignment object
2083 // Add pasted sequences and dataset into existing alignment.
2084 alignment = viewport.getAlignment();
2085 alwidth = alignment.getWidth() + 1;
2086 // decide if we need to import sequences from an existing dataset
2087 boolean importDs = Desktop.jalviewClipboard != null
2088 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2089 // importDs==true instructs us to copy over new dataset sequences from
2090 // an existing alignment
2091 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2093 // minimum dataset set
2095 for (int i = 0; i < sequences.length; i++)
2099 newDs.addElement(null);
2101 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2103 if (importDs && ds != null)
2105 if (!newDs.contains(ds))
2107 newDs.setElementAt(ds, i);
2108 ds = new Sequence(ds);
2109 // update with new dataset sequence
2110 sequences[i].setDatasetSequence(ds);
2114 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2119 // copy and derive new dataset sequence
2120 sequences[i] = sequences[i].deriveSequence();
2121 alignment.getDataset()
2122 .addSequence(sequences[i].getDatasetSequence());
2123 // TODO: avoid creation of duplicate dataset sequences with a
2124 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2126 alignment.addSequence(sequences[i]); // merges dataset
2130 newDs.clear(); // tidy up
2132 if (alignment.getAlignmentAnnotation() != null)
2134 for (AlignmentAnnotation alan : alignment
2135 .getAlignmentAnnotation())
2137 if (alan.graphGroup > fgroup)
2139 fgroup = alan.graphGroup;
2143 if (pastedal.getAlignmentAnnotation() != null)
2145 // Add any annotation attached to alignment.
2146 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2147 for (int i = 0; i < alann.length; i++)
2149 annotationAdded = true;
2150 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2152 AlignmentAnnotation newann = new AlignmentAnnotation(
2154 if (newann.graphGroup > -1)
2156 if (newGraphGroups.size() <= newann.graphGroup
2157 || newGraphGroups.get(newann.graphGroup) == null)
2159 for (int q = newGraphGroups
2160 .size(); q <= newann.graphGroup; q++)
2162 newGraphGroups.add(q, null);
2164 newGraphGroups.set(newann.graphGroup,
2165 Integer.valueOf(++fgroup));
2167 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2171 newann.padAnnotation(alwidth);
2172 alignment.addAnnotation(newann);
2182 addHistoryItem(new EditCommand(
2183 MessageManager.getString("label.add_sequences"),
2184 Action.PASTE, sequences, 0, alignment.getWidth(),
2187 // Add any annotations attached to sequences
2188 for (int i = 0; i < sequences.length; i++)
2190 if (sequences[i].getAnnotation() != null)
2192 AlignmentAnnotation newann;
2193 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2195 annotationAdded = true;
2196 newann = sequences[i].getAnnotation()[a];
2197 newann.adjustForAlignment();
2198 newann.padAnnotation(alwidth);
2199 if (newann.graphGroup > -1)
2201 if (newann.graphGroup > -1)
2203 if (newGraphGroups.size() <= newann.graphGroup
2204 || newGraphGroups.get(newann.graphGroup) == null)
2206 for (int q = newGraphGroups
2207 .size(); q <= newann.graphGroup; q++)
2209 newGraphGroups.add(q, null);
2211 newGraphGroups.set(newann.graphGroup,
2212 Integer.valueOf(++fgroup));
2214 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2218 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2222 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2230 // propagate alignment changed.
2231 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2232 if (annotationAdded)
2234 // Duplicate sequence annotation in all views.
2235 AlignmentI[] alview = this.getViewAlignments();
2236 for (int i = 0; i < sequences.length; i++)
2238 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2243 for (int avnum = 0; avnum < alview.length; avnum++)
2245 if (alview[avnum] != alignment)
2247 // duplicate in a view other than the one with input focus
2248 int avwidth = alview[avnum].getWidth() + 1;
2249 // this relies on sann being preserved after we
2250 // modify the sequence's annotation array for each duplication
2251 for (int a = 0; a < sann.length; a++)
2253 AlignmentAnnotation newann = new AlignmentAnnotation(
2255 sequences[i].addAlignmentAnnotation(newann);
2256 newann.padAnnotation(avwidth);
2257 alview[avnum].addAnnotation(newann); // annotation was
2258 // duplicated earlier
2259 // TODO JAL-1145 graphGroups are not updated for sequence
2260 // annotation added to several views. This may cause
2262 alview[avnum].setAnnotationIndex(newann, a);
2267 buildSortByAnnotationScoresMenu();
2269 viewport.firePropertyChange("alignment", null,
2270 alignment.getSequences());
2271 if (alignPanels != null)
2273 for (AlignmentPanel ap : alignPanels)
2275 ap.validateAnnotationDimensions(false);
2280 alignPanel.validateAnnotationDimensions(false);
2286 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2288 String newtitle = new String("Copied sequences");
2290 if (Desktop.jalviewClipboard != null
2291 && Desktop.jalviewClipboard[2] != null)
2293 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2294 af.viewport.setHiddenColumns(hc);
2297 // >>>This is a fix for the moment, until a better solution is
2299 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2300 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2301 .getFeatureRenderer());
2303 // TODO: maintain provenance of an alignment, rather than just make the
2304 // title a concatenation of operations.
2307 if (title.startsWith("Copied sequences"))
2313 newtitle = newtitle.concat("- from " + title);
2318 newtitle = new String("Pasted sequences");
2321 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2326 } catch (Exception ex)
2328 ex.printStackTrace();
2329 System.out.println("Exception whilst pasting: " + ex);
2330 // could be anything being pasted in here
2336 protected void expand_newalign(ActionEvent e)
2340 AlignmentI alignment = AlignmentUtils
2341 .expandContext(getViewport().getAlignment(), -1);
2342 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2344 String newtitle = new String("Flanking alignment");
2346 if (Desktop.jalviewClipboard != null
2347 && Desktop.jalviewClipboard[2] != null)
2349 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2350 af.viewport.setHiddenColumns(hc);
2353 // >>>This is a fix for the moment, until a better solution is
2355 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2356 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2357 .getFeatureRenderer());
2359 // TODO: maintain provenance of an alignment, rather than just make the
2360 // title a concatenation of operations.
2362 if (title.startsWith("Copied sequences"))
2368 newtitle = newtitle.concat("- from " + title);
2372 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2374 } catch (Exception ex)
2376 ex.printStackTrace();
2377 System.out.println("Exception whilst pasting: " + ex);
2378 // could be anything being pasted in here
2379 } catch (OutOfMemoryError oom)
2381 new OOMWarning("Viewing flanking region of alignment", oom);
2386 * Action Cut (delete and copy) the selected region
2389 protected void cut_actionPerformed()
2391 copy_actionPerformed();
2392 delete_actionPerformed();
2396 * Performs menu option to Delete the currently selected region
2399 protected void delete_actionPerformed()
2402 SequenceGroup sg = viewport.getSelectionGroup();
2408 Runnable okAction = new Runnable()
2413 SequenceI[] cut = sg.getSequences()
2414 .toArray(new SequenceI[sg.getSize()]);
2416 addHistoryItem(new EditCommand(
2417 MessageManager.getString("label.cut_sequences"), Action.CUT,
2418 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2419 viewport.getAlignment()));
2421 viewport.setSelectionGroup(null);
2422 viewport.sendSelection();
2423 viewport.getAlignment().deleteGroup(sg);
2425 viewport.firePropertyChange("alignment", null,
2426 viewport.getAlignment().getSequences());
2427 if (viewport.getAlignment().getHeight() < 1)
2431 AlignFrame.this.setClosed(true);
2432 } catch (Exception ex)
2439 * If the cut affects all sequences, prompt for confirmation
2441 boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2442 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2443 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2444 if (wholeHeight && wholeWidth)
2446 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2447 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2448 Object[] options = new Object[] { MessageManager.getString("action.ok"),
2449 MessageManager.getString("action.cancel") };
2450 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2451 MessageManager.getString("label.delete_all"),
2452 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2453 options, options[0]);
2467 protected void deleteGroups_actionPerformed(ActionEvent e)
2469 if (avc.deleteGroups())
2471 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2472 alignPanel.updateAnnotation();
2473 alignPanel.paintAlignment(true, true);
2484 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2486 SequenceGroup sg = new SequenceGroup(
2487 viewport.getAlignment().getSequences());
2489 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2490 viewport.setSelectionGroup(sg);
2491 viewport.isSelectionGroupChanged(true);
2492 viewport.sendSelection();
2493 // JAL-2034 - should delegate to
2494 // alignPanel to decide if overview needs
2496 alignPanel.paintAlignment(false, false);
2497 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2507 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2509 if (viewport.cursorMode)
2511 alignPanel.getSeqPanel().keyboardNo1 = null;
2512 alignPanel.getSeqPanel().keyboardNo2 = null;
2514 viewport.setSelectionGroup(null);
2515 viewport.getColumnSelection().clear();
2516 viewport.setSelectionGroup(null);
2517 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2518 // JAL-2034 - should delegate to
2519 // alignPanel to decide if overview needs
2521 alignPanel.paintAlignment(false, false);
2522 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2523 viewport.sendSelection();
2533 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2535 SequenceGroup sg = viewport.getSelectionGroup();
2539 selectAllSequenceMenuItem_actionPerformed(null);
2544 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2546 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2548 // JAL-2034 - should delegate to
2549 // alignPanel to decide if overview needs
2552 alignPanel.paintAlignment(true, false);
2553 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2554 viewport.sendSelection();
2558 public void invertColSel_actionPerformed(ActionEvent e)
2560 viewport.invertColumnSelection();
2561 alignPanel.paintAlignment(true, false);
2562 viewport.sendSelection();
2572 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2574 trimAlignment(true);
2584 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2586 trimAlignment(false);
2589 void trimAlignment(boolean trimLeft)
2591 ColumnSelection colSel = viewport.getColumnSelection();
2594 if (!colSel.isEmpty())
2598 column = colSel.getMin();
2602 column = colSel.getMax();
2606 if (viewport.getSelectionGroup() != null)
2608 seqs = viewport.getSelectionGroup()
2609 .getSequencesAsArray(viewport.getHiddenRepSequences());
2613 seqs = viewport.getAlignment().getSequencesArray();
2616 TrimRegionCommand trimRegion;
2619 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2620 column, viewport.getAlignment());
2621 viewport.getRanges().setStartRes(0);
2625 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2626 column, viewport.getAlignment());
2629 setStatus(MessageManager
2630 .formatMessage("label.removed_columns", new String[]
2631 { Integer.valueOf(trimRegion.getSize()).toString() }));
2633 addHistoryItem(trimRegion);
2635 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2637 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2638 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2640 viewport.getAlignment().deleteGroup(sg);
2644 viewport.firePropertyChange("alignment", null,
2645 viewport.getAlignment().getSequences());
2656 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2658 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2661 if (viewport.getSelectionGroup() != null)
2663 seqs = viewport.getSelectionGroup()
2664 .getSequencesAsArray(viewport.getHiddenRepSequences());
2665 start = viewport.getSelectionGroup().getStartRes();
2666 end = viewport.getSelectionGroup().getEndRes();
2670 seqs = viewport.getAlignment().getSequencesArray();
2673 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2674 "Remove Gapped Columns", seqs, start, end,
2675 viewport.getAlignment());
2677 addHistoryItem(removeGapCols);
2679 setStatus(MessageManager
2680 .formatMessage("label.removed_empty_columns", new Object[]
2681 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2683 // This is to maintain viewport position on first residue
2684 // of first sequence
2685 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2686 ViewportRanges ranges = viewport.getRanges();
2687 int startRes = seq.findPosition(ranges.getStartRes());
2688 // ShiftList shifts;
2689 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2690 // edit.alColumnChanges=shifts.getInverse();
2691 // if (viewport.hasHiddenColumns)
2692 // viewport.getColumnSelection().compensateForEdits(shifts);
2693 ranges.setStartRes(seq.findIndex(startRes) - 1);
2694 viewport.firePropertyChange("alignment", null,
2695 viewport.getAlignment().getSequences());
2706 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2708 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2711 if (viewport.getSelectionGroup() != null)
2713 seqs = viewport.getSelectionGroup()
2714 .getSequencesAsArray(viewport.getHiddenRepSequences());
2715 start = viewport.getSelectionGroup().getStartRes();
2716 end = viewport.getSelectionGroup().getEndRes();
2720 seqs = viewport.getAlignment().getSequencesArray();
2723 // This is to maintain viewport position on first residue
2724 // of first sequence
2725 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2726 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2728 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2729 viewport.getAlignment()));
2731 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2733 viewport.firePropertyChange("alignment", null,
2734 viewport.getAlignment().getSequences());
2745 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2747 viewport.setPadGaps(padGapsMenuitem.isSelected());
2748 viewport.firePropertyChange("alignment", null,
2749 viewport.getAlignment().getSequences());
2759 public void findMenuItem_actionPerformed(ActionEvent e)
2765 * Create a new view of the current alignment.
2768 public void newView_actionPerformed(ActionEvent e)
2770 newView(null, true);
2774 * Creates and shows a new view of the current alignment.
2777 * title of newly created view; if null, one will be generated
2778 * @param copyAnnotation
2779 * if true then duplicate all annnotation, groups and settings
2780 * @return new alignment panel, already displayed.
2782 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2785 * Create a new AlignmentPanel (with its own, new Viewport)
2787 AlignmentPanel newap = new jalview.project.Jalview2XML()
2788 .copyAlignPanel(alignPanel);
2789 if (!copyAnnotation)
2792 * remove all groups and annotation except for the automatic stuff
2794 newap.av.getAlignment().deleteAllGroups();
2795 newap.av.getAlignment().deleteAllAnnotations(false);
2798 newap.av.setGatherViewsHere(false);
2800 if (viewport.getViewName() == null)
2802 viewport.setViewName(MessageManager
2803 .getString("label.view_name_original"));
2807 * Views share the same edits undo and redo stacks
2809 newap.av.setHistoryList(viewport.getHistoryList());
2810 newap.av.setRedoList(viewport.getRedoList());
2813 * copy any visualisation settings that are not saved in the project
2815 newap.av.setColourAppliesToAllGroups(
2816 viewport.getColourAppliesToAllGroups());
2819 * Views share the same mappings; need to deregister any new mappings
2820 * created by copyAlignPanel, and register the new reference to the shared
2823 newap.av.replaceMappings(viewport.getAlignment());
2826 * start up cDNA consensus (if applicable) now mappings are in place
2828 if (newap.av.initComplementConsensus())
2830 newap.refresh(true); // adjust layout of annotations
2833 newap.av.setViewName(getNewViewName(viewTitle));
2835 addAlignmentPanel(newap, true);
2836 newap.alignmentChanged();
2838 if (alignPanels.size() == 2)
2840 viewport.setGatherViewsHere(true);
2842 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2847 * Make a new name for the view, ensuring it is unique within the current
2848 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2849 * these now use viewId. Unique view names are still desirable for usability.)
2854 protected String getNewViewName(String viewTitle)
2856 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2857 boolean addFirstIndex = false;
2858 if (viewTitle == null || viewTitle.trim().length() == 0)
2860 viewTitle = MessageManager.getString("action.view");
2861 addFirstIndex = true;
2865 index = 1;// we count from 1 if given a specific name
2867 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2869 List<Component> comps = PaintRefresher.components
2870 .get(viewport.getSequenceSetId());
2872 List<String> existingNames = getExistingViewNames(comps);
2874 while (existingNames.contains(newViewName))
2876 newViewName = viewTitle + " " + (++index);
2882 * Returns a list of distinct view names found in the given list of
2883 * components. View names are held on the viewport of an AlignmentPanel.
2888 protected List<String> getExistingViewNames(List<Component> comps)
2890 List<String> existingNames = new ArrayList<>();
2891 for (Component comp : comps)
2893 if (comp instanceof AlignmentPanel)
2895 AlignmentPanel ap = (AlignmentPanel) comp;
2896 if (!existingNames.contains(ap.av.getViewName()))
2898 existingNames.add(ap.av.getViewName());
2902 return existingNames;
2906 * Explode tabbed views into separate windows.
2909 public void expandViews_actionPerformed(ActionEvent e)
2911 Desktop.explodeViews(this);
2915 * Gather views in separate windows back into a tabbed presentation.
2918 public void gatherViews_actionPerformed(ActionEvent e)
2920 Desktop.instance.gatherViews(this);
2930 public void font_actionPerformed(ActionEvent e)
2932 new FontChooser(alignPanel);
2942 protected void seqLimit_actionPerformed(ActionEvent e)
2944 viewport.setShowJVSuffix(seqLimits.isSelected());
2946 alignPanel.getIdPanel().getIdCanvas()
2947 .setPreferredSize(alignPanel.calculateIdWidth());
2948 alignPanel.paintAlignment(true, false);
2952 public void idRightAlign_actionPerformed(ActionEvent e)
2954 viewport.setRightAlignIds(idRightAlign.isSelected());
2955 alignPanel.paintAlignment(false, false);
2959 public void centreColumnLabels_actionPerformed(ActionEvent e)
2961 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2962 alignPanel.paintAlignment(false, false);
2968 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2971 protected void followHighlight_actionPerformed()
2974 * Set the 'follow' flag on the Viewport (and scroll to position if now
2977 final boolean state = this.followHighlightMenuItem.getState();
2978 viewport.setFollowHighlight(state);
2981 alignPanel.scrollToPosition(viewport.getSearchResults());
2992 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2994 viewport.setColourText(colourTextMenuItem.isSelected());
2995 alignPanel.paintAlignment(false, false);
3005 public void wrapMenuItem_actionPerformed(ActionEvent e)
3007 scaleAbove.setVisible(wrapMenuItem.isSelected());
3008 scaleLeft.setVisible(wrapMenuItem.isSelected());
3009 scaleRight.setVisible(wrapMenuItem.isSelected());
3010 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3011 alignPanel.updateLayout();
3015 public void showAllSeqs_actionPerformed(ActionEvent e)
3017 viewport.showAllHiddenSeqs();
3021 public void showAllColumns_actionPerformed(ActionEvent e)
3023 viewport.showAllHiddenColumns();
3024 alignPanel.paintAlignment(true, true);
3025 viewport.sendSelection();
3029 public void hideSelSequences_actionPerformed(ActionEvent e)
3031 viewport.hideAllSelectedSeqs();
3035 * called by key handler and the hide all/show all menu items
3040 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3043 boolean hide = false;
3044 SequenceGroup sg = viewport.getSelectionGroup();
3045 if (!toggleSeqs && !toggleCols)
3047 // Hide everything by the current selection - this is a hack - we do the
3048 // invert and then hide
3049 // first check that there will be visible columns after the invert.
3050 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3051 && sg.getStartRes() <= sg.getEndRes()))
3053 // now invert the sequence set, if required - empty selection implies
3054 // that no hiding is required.
3057 invertSequenceMenuItem_actionPerformed(null);
3058 sg = viewport.getSelectionGroup();
3062 viewport.expandColSelection(sg, true);
3063 // finally invert the column selection and get the new sequence
3065 invertColSel_actionPerformed(null);
3072 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3074 hideSelSequences_actionPerformed(null);
3077 else if (!(toggleCols && viewport.hasSelectedColumns()))
3079 showAllSeqs_actionPerformed(null);
3085 if (viewport.hasSelectedColumns())
3087 hideSelColumns_actionPerformed(null);
3090 viewport.setSelectionGroup(sg);
3095 showAllColumns_actionPerformed(null);
3104 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3105 * event.ActionEvent)
3108 public void hideAllButSelection_actionPerformed(ActionEvent e)
3110 toggleHiddenRegions(false, false);
3111 viewport.sendSelection();
3118 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3122 public void hideAllSelection_actionPerformed(ActionEvent e)
3124 SequenceGroup sg = viewport.getSelectionGroup();
3125 viewport.expandColSelection(sg, false);
3126 viewport.hideAllSelectedSeqs();
3127 viewport.hideSelectedColumns();
3128 alignPanel.updateLayout();
3129 alignPanel.paintAlignment(true, true);
3130 viewport.sendSelection();
3137 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3141 public void showAllhidden_actionPerformed(ActionEvent e)
3143 viewport.showAllHiddenColumns();
3144 viewport.showAllHiddenSeqs();
3145 alignPanel.paintAlignment(true, true);
3146 viewport.sendSelection();
3150 public void hideSelColumns_actionPerformed(ActionEvent e)
3152 viewport.hideSelectedColumns();
3153 alignPanel.updateLayout();
3154 alignPanel.paintAlignment(true, true);
3155 viewport.sendSelection();
3159 public void hiddenMarkers_actionPerformed(ActionEvent e)
3161 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3172 protected void scaleAbove_actionPerformed(ActionEvent e)
3174 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3175 alignPanel.updateLayout();
3176 alignPanel.paintAlignment(true, false);
3186 protected void scaleLeft_actionPerformed(ActionEvent e)
3188 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3189 alignPanel.updateLayout();
3190 alignPanel.paintAlignment(true, false);
3200 protected void scaleRight_actionPerformed(ActionEvent e)
3202 viewport.setScaleRightWrapped(scaleRight.isSelected());
3203 alignPanel.updateLayout();
3204 alignPanel.paintAlignment(true, false);
3214 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3216 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3217 alignPanel.paintAlignment(false, false);
3227 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3229 viewport.setShowText(viewTextMenuItem.isSelected());
3230 alignPanel.paintAlignment(false, false);
3240 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3242 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3243 alignPanel.paintAlignment(false, false);
3246 public FeatureSettings featureSettings;
3249 public FeatureSettingsControllerI getFeatureSettingsUI()
3251 return featureSettings;
3255 public void featureSettings_actionPerformed(ActionEvent e)
3257 showFeatureSettingsUI();
3261 public FeatureSettingsControllerI showFeatureSettingsUI()
3263 if (featureSettings != null)
3265 featureSettings.closeOldSettings();
3266 featureSettings = null;
3268 if (!showSeqFeatures.isSelected())
3270 // make sure features are actually displayed
3271 showSeqFeatures.setSelected(true);
3272 showSeqFeatures_actionPerformed(null);
3274 featureSettings = new FeatureSettings(this);
3275 return featureSettings;
3279 * Set or clear 'Show Sequence Features'
3285 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3287 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3288 alignPanel.paintAlignment(true, true);
3292 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3293 * the annotations panel as a whole.
3295 * The options to show/hide all annotations should be enabled when the panel
3296 * is shown, and disabled when the panel is hidden.
3301 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3303 final boolean setVisible = annotationPanelMenuItem.isSelected();
3304 viewport.setShowAnnotation(setVisible);
3305 this.showAllSeqAnnotations.setEnabled(setVisible);
3306 this.hideAllSeqAnnotations.setEnabled(setVisible);
3307 this.showAllAlAnnotations.setEnabled(setVisible);
3308 this.hideAllAlAnnotations.setEnabled(setVisible);
3309 alignPanel.updateLayout();
3313 public void alignmentProperties()
3316 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3319 String content = MessageManager.formatMessage("label.html_content",
3321 { contents.toString() });
3324 if (Platform.isJS())
3326 JLabel textLabel = new JLabel();
3327 textLabel.setText(content);
3328 textLabel.setBackground(Color.WHITE);
3330 pane = new JPanel(new BorderLayout());
3331 ((JPanel) pane).setOpaque(true);
3332 pane.setBackground(Color.WHITE);
3333 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3342 JEditorPane editPane = new JEditorPane("text/html", "");
3343 editPane.setEditable(false);
3344 editPane.setText(content);
3348 JInternalFrame frame = new JInternalFrame();
3350 frame.getContentPane().add(new JScrollPane(pane));
3352 Desktop.addInternalFrame(frame, MessageManager
3353 .formatMessage("label.alignment_properties", new Object[]
3354 { getTitle() }), 500, 400);
3364 public void overviewMenuItem_actionPerformed(ActionEvent e)
3366 if (alignPanel.overviewPanel != null)
3371 JInternalFrame frame = new JInternalFrame();
3375 // BH 2019.07.26 we allow for an embedded
3376 // undecorated overview with defined size
3377 frame.setName(Jalview.getAppID("overview"));
3379 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3380 if (dim != null && dim.width == 0)
3382 dim = null; // hidden, not embedded
3384 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3386 frame.setContentPane(overview);
3389 dim = new Dimension();
3390 // was frame.getSize(), but that is 0,0 at this point;
3394 // we are imbedding, and so we have an undecorated frame
3395 // and we can set the the frame dimensions accordingly.
3397 // allowing for unresizable option using, style="resize:none"
3398 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3399 "resize") != "none");
3400 Desktop.addInternalFrame(frame, MessageManager
3401 .formatMessage("label.overview_params", new Object[]
3402 { this.getTitle() }), true, dim.width, dim.height, resizable,
3405 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3406 frame.addInternalFrameListener(
3407 new javax.swing.event.InternalFrameAdapter()
3410 public void internalFrameClosed(
3411 javax.swing.event.InternalFrameEvent evt)
3414 alignPanel.setOverviewPanel(null);
3417 if (getKeyListeners().length > 0)
3419 frame.addKeyListener(getKeyListeners()[0]);
3422 alignPanel.setOverviewPanel(overview);
3426 public void textColour_actionPerformed()
3428 new TextColourChooser().chooseColour(alignPanel, null);
3432 * public void covariationColour_actionPerformed() {
3434 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3438 public void annotationColour_actionPerformed()
3440 new AnnotationColourChooser(viewport, alignPanel);
3444 public void annotationColumn_actionPerformed(ActionEvent e)
3446 new AnnotationColumnChooser(viewport, alignPanel);
3450 * Action on the user checking or unchecking the option to apply the selected
3451 * colour scheme to all groups. If unchecked, groups may have their own
3452 * independent colour schemes.
3457 public void applyToAllGroups_actionPerformed(boolean selected)
3459 viewport.setColourAppliesToAllGroups(selected);
3463 * Action on user selecting a colour from the colour menu
3466 * the name (not the menu item label!) of the colour scheme
3469 public void changeColour_actionPerformed(String name)
3472 * 'User Defined' opens a panel to configure or load a
3473 * user-defined colour scheme
3475 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3477 new UserDefinedColours(alignPanel);
3482 * otherwise set the chosen colour scheme (or null for 'None')
3484 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3486 viewport.getAlignment(), viewport.getHiddenRepSequences());
3491 * Actions on setting or changing the alignment colour scheme
3496 public void changeColour(ColourSchemeI cs)
3498 // TODO: pull up to controller method
3499 ColourMenuHelper.setColourSelected(colourMenu, cs);
3501 viewport.setGlobalColourScheme(cs);
3503 alignPanel.paintAlignment(true, true);
3507 * Show the PID threshold slider panel
3510 protected void modifyPID_actionPerformed()
3512 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3513 alignPanel.getViewName());
3514 SliderPanel.showPIDSlider();
3518 * Show the Conservation slider panel
3521 protected void modifyConservation_actionPerformed()
3523 SliderPanel.setConservationSlider(alignPanel,
3524 viewport.getResidueShading(), alignPanel.getViewName());
3525 SliderPanel.showConservationSlider();
3529 * Action on selecting or deselecting (Colour) By Conservation
3532 public void conservationMenuItem_actionPerformed(boolean selected)
3534 modifyConservation.setEnabled(selected);
3535 viewport.setConservationSelected(selected);
3536 viewport.getResidueShading().setConservationApplied(selected);
3538 changeColour(viewport.getGlobalColourScheme());
3541 modifyConservation_actionPerformed();
3545 SliderPanel.hideConservationSlider();
3550 * Action on selecting or deselecting (Colour) Above PID Threshold
3553 public void abovePIDThreshold_actionPerformed(boolean selected)
3555 modifyPID.setEnabled(selected);
3556 viewport.setAbovePIDThreshold(selected);
3559 viewport.getResidueShading().setThreshold(0,
3560 viewport.isIgnoreGapsConsensus());
3563 changeColour(viewport.getGlobalColourScheme());
3566 modifyPID_actionPerformed();
3570 SliderPanel.hidePIDSlider();
3581 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3583 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3584 AlignmentSorter.sortByPID(viewport.getAlignment(),
3585 viewport.getAlignment().getSequenceAt(0));
3586 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3587 viewport.getAlignment()));
3588 alignPanel.paintAlignment(true, false);
3598 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3600 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3601 AlignmentSorter.sortByID(viewport.getAlignment());
3603 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3604 alignPanel.paintAlignment(true, false);
3614 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3616 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3617 AlignmentSorter.sortByLength(viewport.getAlignment());
3618 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3619 viewport.getAlignment()));
3620 alignPanel.paintAlignment(true, false);
3630 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3632 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3633 AlignmentSorter.sortByGroup(viewport.getAlignment());
3634 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3635 viewport.getAlignment()));
3637 alignPanel.paintAlignment(true, false);
3647 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3649 new RedundancyPanel(alignPanel, this);
3659 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3661 if ((viewport.getSelectionGroup() == null)
3662 || (viewport.getSelectionGroup().getSize() < 2))
3664 JvOptionPane.showInternalMessageDialog(this,
3665 MessageManager.getString(
3666 "label.you_must_select_least_two_sequences"),
3667 MessageManager.getString("label.invalid_selection"),
3668 JvOptionPane.WARNING_MESSAGE);
3672 JInternalFrame frame = new JInternalFrame();
3673 frame.setContentPane(new PairwiseAlignPanel(viewport));
3674 Desktop.addInternalFrame(frame,
3675 MessageManager.getString("action.pairwise_alignment"), 600,
3681 public void autoCalculate_actionPerformed(ActionEvent e)
3683 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3684 if (viewport.autoCalculateConsensus)
3686 viewport.firePropertyChange("alignment", null,
3687 viewport.getAlignment().getSequences());
3692 public void sortByTreeOption_actionPerformed(ActionEvent e)
3694 viewport.sortByTree = sortByTree.isSelected();
3698 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3700 viewport.followSelection = listenToViewSelections.isSelected();
3704 * Constructs a tree panel and adds it to the desktop
3707 * tree type (NJ or AV)
3709 * name of score model used to compute the tree
3711 * parameters for the distance or similarity calculation
3713 void newTreePanel(String type, String modelName,
3714 SimilarityParamsI options)
3716 String frameTitle = "";
3719 boolean onSelection = false;
3720 if (viewport.getSelectionGroup() != null
3721 && viewport.getSelectionGroup().getSize() > 0)
3723 SequenceGroup sg = viewport.getSelectionGroup();
3725 /* Decide if the selection is a column region */
3726 for (SequenceI _s : sg.getSequences())
3728 if (_s.getLength() < sg.getEndRes())
3730 JvOptionPane.showMessageDialog(Desktop.desktop,
3731 MessageManager.getString(
3732 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3733 MessageManager.getString(
3734 "label.sequences_selection_not_aligned"),
3735 JvOptionPane.WARNING_MESSAGE);
3744 if (viewport.getAlignment().getHeight() < 2)
3750 tp = new TreePanel(alignPanel, type, modelName, options);
3751 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3753 frameTitle += " from ";
3755 if (viewport.getViewName() != null)
3757 frameTitle += viewport.getViewName() + " of ";
3760 frameTitle += this.title;
3762 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
3763 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
3774 public void addSortByOrderMenuItem(String title,
3775 final AlignmentOrder order)
3777 final JMenuItem item = new JMenuItem(MessageManager
3778 .formatMessage("action.by_title_param", new Object[]
3781 item.addActionListener(new java.awt.event.ActionListener()
3784 public void actionPerformed(ActionEvent e)
3786 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3788 // TODO: JBPNote - have to map order entries to curent SequenceI
3790 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3792 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3793 viewport.getAlignment()));
3795 alignPanel.paintAlignment(true, false);
3801 * Add a new sort by annotation score menu item
3804 * the menu to add the option to
3806 * the label used to retrieve scores for each sequence on the
3809 public void addSortByAnnotScoreMenuItem(JMenu sort,
3810 final String scoreLabel)
3812 final JMenuItem item = new JMenuItem(scoreLabel);
3814 item.addActionListener(new java.awt.event.ActionListener()
3817 public void actionPerformed(ActionEvent e)
3819 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3820 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3821 viewport.getAlignment());// ,viewport.getSelectionGroup());
3822 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3823 viewport.getAlignment()));
3824 alignPanel.paintAlignment(true, false);
3830 * last hash for alignment's annotation array - used to minimise cost of
3833 protected int _annotationScoreVectorHash;
3836 * search the alignment and rebuild the sort by annotation score submenu the
3837 * last alignment annotation vector hash is stored to minimize cost of
3838 * rebuilding in subsequence calls.
3842 public void buildSortByAnnotationScoresMenu()
3844 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3849 if (viewport.getAlignment().getAlignmentAnnotation()
3850 .hashCode() != _annotationScoreVectorHash)
3852 sortByAnnotScore.removeAll();
3853 // almost certainly a quicker way to do this - but we keep it simple
3854 Hashtable<String, String> scoreSorts = new Hashtable<>();
3855 AlignmentAnnotation aann[];
3856 for (SequenceI sqa : viewport.getAlignment().getSequences())
3858 aann = sqa.getAnnotation();
3859 for (int i = 0; aann != null && i < aann.length; i++)
3861 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3863 scoreSorts.put(aann[i].label, aann[i].label);
3867 Enumeration<String> labels = scoreSorts.keys();
3868 while (labels.hasMoreElements())
3870 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3871 labels.nextElement());
3873 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3876 _annotationScoreVectorHash = viewport.getAlignment()
3877 .getAlignmentAnnotation().hashCode();
3882 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3883 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3884 * call. Listeners are added to remove the menu item when the treePanel is
3885 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3889 public void buildTreeSortMenu()
3891 sortByTreeMenu.removeAll();
3893 List<Component> comps = PaintRefresher.components
3894 .get(viewport.getSequenceSetId());
3895 List<TreePanel> treePanels = new ArrayList<>();
3896 for (Component comp : comps)
3898 if (comp instanceof TreePanel)
3900 treePanels.add((TreePanel) comp);
3904 if (treePanels.size() < 1)
3906 sortByTreeMenu.setVisible(false);
3910 sortByTreeMenu.setVisible(true);
3912 for (final TreePanel tp : treePanels)
3914 final JMenuItem item = new JMenuItem(tp.getTitle());
3915 item.addActionListener(new java.awt.event.ActionListener()
3918 public void actionPerformed(ActionEvent e)
3920 tp.sortByTree_actionPerformed();
3921 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3926 sortByTreeMenu.add(item);
3930 public boolean sortBy(AlignmentOrder alorder, String undoname)
3932 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3933 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3934 if (undoname != null)
3936 addHistoryItem(new OrderCommand(undoname, oldOrder,
3937 viewport.getAlignment()));
3939 alignPanel.paintAlignment(true, false);
3944 * Work out whether the whole set of sequences or just the selected set will
3945 * be submitted for multiple alignment.
3948 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3950 // Now, check we have enough sequences
3951 AlignmentView msa = null;
3953 if ((viewport.getSelectionGroup() != null)
3954 && (viewport.getSelectionGroup().getSize() > 1))
3956 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3957 // some common interface!
3959 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3960 * SequenceI[sz = seqs.getSize(false)];
3962 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3963 * seqs.getSequenceAt(i); }
3965 msa = viewport.getAlignmentView(true);
3967 else if (viewport.getSelectionGroup() != null
3968 && viewport.getSelectionGroup().getSize() == 1)
3970 int option = JvOptionPane.showConfirmDialog(this,
3971 MessageManager.getString("warn.oneseq_msainput_selection"),
3972 MessageManager.getString("label.invalid_selection"),
3973 JvOptionPane.OK_CANCEL_OPTION);
3974 if (option == JvOptionPane.OK_OPTION)
3976 msa = viewport.getAlignmentView(false);
3981 msa = viewport.getAlignmentView(false);
3987 * Decides what is submitted to a secondary structure prediction service: the
3988 * first sequence in the alignment, or in the current selection, or, if the
3989 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3990 * region or the whole alignment. (where the first sequence in the set is the
3991 * one that the prediction will be for).
3993 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3995 AlignmentView seqs = null;
3997 if ((viewport.getSelectionGroup() != null)
3998 && (viewport.getSelectionGroup().getSize() > 0))
4000 seqs = viewport.getAlignmentView(true);
4004 seqs = viewport.getAlignmentView(false);
4006 // limit sequences - JBPNote in future - could spawn multiple prediction
4008 // TODO: viewport.getAlignment().isAligned is a global state - the local
4009 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4010 if (!viewport.getAlignment().isAligned(false))
4012 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4013 // TODO: if seqs.getSequences().length>1 then should really have warned
4027 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4029 // Pick the tree file
4030 JalviewFileChooser chooser = new JalviewFileChooser(
4031 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4032 chooser.setFileView(new JalviewFileView());
4033 chooser.setDialogTitle(
4034 MessageManager.getString("label.select_newick_like_tree_file"));
4035 chooser.setToolTipText(
4036 MessageManager.getString("label.load_tree_file"));
4038 chooser.setResponseHandler(0,new Runnable()
4043 String filePath = chooser.getSelectedFile().getPath();
4044 Cache.setProperty("LAST_DIRECTORY", filePath);
4045 NewickFile fin = null;
4048 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4049 DataSourceType.FILE));
4050 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4051 } catch (Exception ex)
4053 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4055 .getString("label.problem_reading_tree_file"),
4056 JvOptionPane.WARNING_MESSAGE);
4057 ex.printStackTrace();
4059 if (fin != null && fin.hasWarningMessage())
4061 JvOptionPane.showMessageDialog(Desktop.desktop,
4062 fin.getWarningMessage(),
4063 MessageManager.getString(
4064 "label.possible_problem_with_tree_file"),
4065 JvOptionPane.WARNING_MESSAGE);
4069 chooser.showOpenDialog(this);
4072 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4074 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4077 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4078 int h, int x, int y)
4080 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4084 * Add a treeviewer for the tree extracted from a Newick file object to the
4085 * current alignment view
4092 * Associated alignment input data (or null)
4101 * @return TreePanel handle
4103 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4104 AlignmentView input, int w, int h, int x, int y)
4106 TreePanel tp = null;
4112 if (nf.getTree() != null)
4114 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4115 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4118 dim = new Dimension(w, h);
4122 // no offset, either
4125 tp.setSize(dim.width, dim.height);
4129 tp.setLocation(x, y);
4132 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4134 } catch (Exception ex)
4136 ex.printStackTrace();
4142 private boolean buildingMenu = false;
4145 * Generates menu items and listener event actions for web service clients
4148 public void BuildWebServiceMenu()
4150 while (buildingMenu)
4154 System.err.println("Waiting for building menu to finish.");
4156 } catch (Exception e)
4160 final AlignFrame me = this;
4161 buildingMenu = true;
4162 new Thread(new Runnable()
4167 final List<JMenuItem> legacyItems = new ArrayList<>();
4170 // System.err.println("Building ws menu again "
4171 // + Thread.currentThread());
4172 // TODO: add support for context dependent disabling of services based
4174 // alignment and current selection
4175 // TODO: add additional serviceHandle parameter to specify abstract
4177 // class independently of AbstractName
4178 // TODO: add in rediscovery GUI function to restart discoverer
4179 // TODO: group services by location as well as function and/or
4181 // object broker mechanism.
4182 final Vector<JMenu> wsmenu = new Vector<>();
4183 final IProgressIndicator af = me;
4186 * do not i18n these strings - they are hard-coded in class
4187 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4188 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4190 final JMenu msawsmenu = new JMenu("Alignment");
4191 final JMenu secstrmenu = new JMenu(
4192 "Secondary Structure Prediction");
4193 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4194 final JMenu analymenu = new JMenu("Analysis");
4195 final JMenu dismenu = new JMenu("Protein Disorder");
4196 // JAL-940 - only show secondary structure prediction services from
4197 // the legacy server
4198 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4200 Discoverer.services != null && (Discoverer.services.size() > 0))
4202 // TODO: refactor to allow list of AbstractName/Handler bindings to
4204 // stored or retrieved from elsewhere
4205 // No MSAWS used any more:
4206 // Vector msaws = null; // (Vector)
4207 // Discoverer.services.get("MsaWS");
4208 Vector<ServiceHandle> secstrpr = Discoverer.services
4210 if (secstrpr != null)
4212 // Add any secondary structure prediction services
4213 for (int i = 0, j = secstrpr.size(); i < j; i++)
4215 final ext.vamsas.ServiceHandle sh = secstrpr
4217 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4218 .getServiceClient(sh);
4219 int p = secstrmenu.getItemCount();
4220 impl.attachWSMenuEntry(secstrmenu, me);
4221 int q = secstrmenu.getItemCount();
4222 for (int litm = p; litm < q; litm++)
4224 legacyItems.add(secstrmenu.getItem(litm));
4230 // Add all submenus in the order they should appear on the web
4232 wsmenu.add(msawsmenu);
4233 wsmenu.add(secstrmenu);
4234 wsmenu.add(dismenu);
4235 wsmenu.add(analymenu);
4236 // No search services yet
4237 // wsmenu.add(seqsrchmenu);
4239 javax.swing.SwingUtilities.invokeLater(new Runnable()
4246 webService.removeAll();
4247 // first, add discovered services onto the webservices menu
4248 if (wsmenu.size() > 0)
4250 for (int i = 0, j = wsmenu.size(); i < j; i++)
4252 webService.add(wsmenu.get(i));
4257 webService.add(me.webServiceNoServices);
4259 // TODO: move into separate menu builder class.
4260 boolean new_sspred = false;
4261 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4263 Jws2Discoverer jws2servs = Jws2Discoverer.getInstance();
4264 if (jws2servs != null)
4266 if (jws2servs.hasServices())
4268 jws2servs.attachWSMenuEntry(webService, me);
4269 for (Jws2Instance sv : jws2servs.getServices())
4271 if (sv.description.toLowerCase().contains("jpred"))
4273 for (JMenuItem jmi : legacyItems)
4275 jmi.setVisible(false);
4281 if (jws2servs.isRunning())
4283 JMenuItem tm = new JMenuItem(
4284 "Still discovering JABA Services");
4285 tm.setEnabled(false);
4290 build_urlServiceMenu(me.webService);
4291 build_fetchdbmenu(webService);
4292 for (JMenu item : wsmenu)
4294 if (item.getItemCount() == 0)
4296 item.setEnabled(false);
4300 item.setEnabled(true);
4303 } catch (Exception e)
4306 "Exception during web service menu building process.",
4311 } catch (Exception e)
4314 buildingMenu = false;
4321 * construct any groupURL type service menu entries.
4325 protected void build_urlServiceMenu(JMenu webService)
4327 // TODO: remove this code when 2.7 is released
4328 // DEBUG - alignmentView
4330 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4331 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4333 * @Override public void actionPerformed(ActionEvent e) {
4334 * jalview.datamodel.AlignmentView
4335 * .testSelectionViews(af.viewport.getAlignment(),
4336 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4338 * }); webService.add(testAlView);
4340 // TODO: refactor to RestClient discoverer and merge menu entries for
4341 // rest-style services with other types of analysis/calculation service
4342 // SHmmr test client - still being implemented.
4343 // DEBUG - alignmentView
4345 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4348 client.attachWSMenuEntry(
4349 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4355 * Searches the alignment sequences for xRefs and builds the Show
4356 * Cross-References menu (formerly called Show Products), with database
4357 * sources for which cross-references are found (protein sources for a
4358 * nucleotide alignment and vice versa)
4360 * @return true if Show Cross-references menu should be enabled
4362 public boolean canShowProducts()
4364 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4365 AlignmentI dataset = viewport.getAlignment().getDataset();
4367 showProducts.removeAll();
4368 final boolean dna = viewport.getAlignment().isNucleotide();
4370 if (seqs == null || seqs.length == 0)
4372 // nothing to see here.
4376 boolean showp = false;
4379 List<String> ptypes = new CrossRef(seqs, dataset)
4380 .findXrefSourcesForSequences(dna);
4382 for (final String source : ptypes)
4385 final AlignFrame af = this;
4386 JMenuItem xtype = new JMenuItem(source);
4387 xtype.addActionListener(new ActionListener()
4390 public void actionPerformed(ActionEvent e)
4392 showProductsFor(af.viewport.getSequenceSelection(), dna,
4396 showProducts.add(xtype);
4398 showProducts.setVisible(showp);
4399 showProducts.setEnabled(showp);
4400 } catch (Exception e)
4403 "canShowProducts threw an exception - please report to help@jalview.org",
4411 * Finds and displays cross-references for the selected sequences (protein
4412 * products for nucleotide sequences, dna coding sequences for peptides).
4415 * the sequences to show cross-references for
4417 * true if from a nucleotide alignment (so showing proteins)
4419 * the database to show cross-references for
4421 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4422 final String source)
4424 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4429 * Construct and display a new frame containing the translation of this
4430 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4433 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4435 AlignmentI al = null;
4438 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4440 al = dna.translateCdna(codeTable);
4441 } catch (Exception ex)
4443 jalview.bin.Cache.log.error(
4444 "Exception during translation. Please report this !", ex);
4445 final String msg = MessageManager.getString(
4446 "label.error_when_translating_sequences_submit_bug_report");
4447 final String errorTitle = MessageManager
4448 .getString("label.implementation_error")
4449 + MessageManager.getString("label.translation_failed");
4450 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4451 JvOptionPane.ERROR_MESSAGE);
4454 if (al == null || al.getHeight() == 0)
4456 final String msg = MessageManager.getString(
4457 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4458 final String errorTitle = MessageManager
4459 .getString("label.translation_failed");
4460 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4461 JvOptionPane.WARNING_MESSAGE);
4465 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4466 af.setFileFormat(this.currentFileFormat);
4467 final String newTitle = MessageManager
4468 .formatMessage("label.translation_of_params", new Object[]
4469 { this.getTitle(), codeTable.getId() });
4470 af.setTitle(newTitle);
4471 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4473 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4474 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4478 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4485 * Set the file format
4489 public void setFileFormat(FileFormatI format)
4491 this.currentFileFormat = format;
4495 * Try to load a features file onto the alignment.
4498 * contents or path to retrieve file or a File object
4500 * access mode of file (see jalview.io.AlignFile)
4501 * @return true if features file was parsed correctly.
4503 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4506 return avc.parseFeaturesFile(file, sourceType,
4507 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4512 public void refreshFeatureUI(boolean enableIfNecessary)
4514 // note - currently this is only still here rather than in the controller
4515 // because of the featureSettings hard reference that is yet to be
4517 if (enableIfNecessary)
4519 viewport.setShowSequenceFeatures(true);
4520 showSeqFeatures.setSelected(true);
4526 public void dragEnter(DropTargetDragEvent evt)
4531 public void dragExit(DropTargetEvent evt)
4536 public void dragOver(DropTargetDragEvent evt)
4541 public void dropActionChanged(DropTargetDragEvent evt)
4546 public void drop(DropTargetDropEvent evt)
4548 // JAL-1552 - acceptDrop required before getTransferable call for
4549 // Java's Transferable for native dnd
4550 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4551 Transferable t = evt.getTransferable();
4553 final AlignFrame thisaf = this;
4554 final List<Object> files = new ArrayList<>();
4555 List<DataSourceType> protocols = new ArrayList<>();
4559 Desktop.transferFromDropTarget(files, protocols, evt, t);
4560 } catch (Exception e)
4562 e.printStackTrace();
4566 new Thread(new Runnable()
4573 // check to see if any of these files have names matching sequences
4576 SequenceIdMatcher idm = new SequenceIdMatcher(
4577 viewport.getAlignment().getSequencesArray());
4579 * Object[] { String,SequenceI}
4581 ArrayList<Object[]> filesmatched = new ArrayList<>();
4582 ArrayList<Object> filesnotmatched = new ArrayList<>();
4583 for (int i = 0; i < files.size(); i++)
4586 Object file = files.get(i);
4587 String fileName = file.toString();
4589 DataSourceType protocol = (file instanceof File
4590 ? DataSourceType.FILE
4591 : FormatAdapter.checkProtocol(fileName));
4592 if (protocol == DataSourceType.FILE)
4595 if (file instanceof File) {
4597 Platform.cacheFileData(fl);
4599 fl = new File(fileName);
4601 pdbfn = fl.getName();
4603 else if (protocol == DataSourceType.URL)
4605 URL url = new URL(fileName);
4606 pdbfn = url.getFile();
4608 if (pdbfn.length() > 0)
4610 // attempt to find a match in the alignment
4611 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4612 int l = 0, c = pdbfn.indexOf(".");
4613 while (mtch == null && c != -1)
4618 } while ((c = pdbfn.indexOf(".", l)) > l);
4621 pdbfn = pdbfn.substring(0, l);
4623 mtch = idm.findAllIdMatches(pdbfn);
4630 type = new IdentifyFile().identify(file, protocol);
4631 } catch (Exception ex)
4635 if (type != null && type.isStructureFile())
4637 filesmatched.add(new Object[] { file, protocol, mtch });
4641 // File wasn't named like one of the sequences or wasn't a PDB
4643 filesnotmatched.add(file);
4647 if (filesmatched.size() > 0)
4649 boolean autoAssociate = Cache
4650 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4653 String msg = MessageManager.formatMessage(
4654 "label.automatically_associate_structure_files_with_sequences_same_name",
4656 { Integer.valueOf(filesmatched.size())
4658 String ttl = MessageManager.getString(
4659 "label.automatically_associate_structure_files_by_name");
4660 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4661 ttl, JvOptionPane.YES_NO_OPTION);
4662 autoAssociate = choice == JvOptionPane.YES_OPTION;
4666 for (Object[] fm : filesmatched)
4668 // try and associate
4669 // TODO: may want to set a standard ID naming formalism for
4670 // associating PDB files which have no IDs.
4671 for (SequenceI toassoc : (SequenceI[]) fm[2])
4673 PDBEntry pe = new AssociatePdbFileWithSeq()
4674 .associatePdbWithSeq(fm[0].toString(),
4675 (DataSourceType) fm[1], toassoc, false,
4679 System.err.println("Associated file : "
4680 + (fm[0].toString()) + " with "
4681 + toassoc.getDisplayId(true));
4685 // TODO: do we need to update overview ? only if features are
4687 alignPanel.paintAlignment(true, false);
4693 * add declined structures as sequences
4695 for (Object[] o : filesmatched)
4697 filesnotmatched.add(o[0]);
4701 if (filesnotmatched.size() > 0)
4703 if (assocfiles > 0 && (Cache.getDefault(
4704 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4705 || JvOptionPane.showConfirmDialog(thisaf,
4706 "<html>" + MessageManager.formatMessage(
4707 "label.ignore_unmatched_dropped_files_info",
4710 filesnotmatched.size())
4713 MessageManager.getString(
4714 "label.ignore_unmatched_dropped_files"),
4715 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4719 for (Object fn : filesnotmatched)
4721 loadJalviewDataFile(fn, null, null, null);
4725 } catch (Exception ex)
4727 ex.printStackTrace();
4735 * Attempt to load a "dropped" file or URL string, by testing in turn for
4737 * <li>an Annotation file</li>
4738 * <li>a JNet file</li>
4739 * <li>a features file</li>
4740 * <li>else try to interpret as an alignment file</li>
4744 * either a filename or a URL string.
4746 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4747 FileFormatI format, SequenceI assocSeq)
4749 // BH 2018 was String file
4752 if (sourceType == null)
4754 sourceType = FormatAdapter.checkProtocol(file);
4756 // if the file isn't identified, or not positively identified as some
4757 // other filetype (PFAM is default unidentified alignment file type) then
4758 // try to parse as annotation.
4759 boolean isAnnotation = (format == null
4760 || FileFormat.Pfam.equals(format))
4761 ? new AnnotationFile().annotateAlignmentView(viewport,
4767 // first see if its a T-COFFEE score file
4768 TCoffeeScoreFile tcf = null;
4771 tcf = new TCoffeeScoreFile(file, sourceType);
4774 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4778 new TCoffeeColourScheme(viewport.getAlignment()));
4779 isAnnotation = true;
4780 setStatus(MessageManager.getString(
4781 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4785 // some problem - if no warning its probable that the ID matching
4786 // process didn't work
4787 JvOptionPane.showMessageDialog(Desktop.desktop,
4788 tcf.getWarningMessage() == null
4789 ? MessageManager.getString(
4790 "label.check_file_matches_sequence_ids_alignment")
4791 : tcf.getWarningMessage(),
4792 MessageManager.getString(
4793 "label.problem_reading_tcoffee_score_file"),
4794 JvOptionPane.WARNING_MESSAGE);
4801 } catch (Exception x)
4804 "Exception when processing data source as T-COFFEE score file",
4810 // try to see if its a JNet 'concise' style annotation file *before*
4812 // try to parse it as a features file
4815 format = new IdentifyFile().identify(file, sourceType);
4817 if (FileFormat.ScoreMatrix == format)
4819 ScoreMatrixFile sm = new ScoreMatrixFile(
4820 new FileParse(file, sourceType));
4822 // todo: i18n this message
4823 setStatus(MessageManager.formatMessage(
4824 "label.successfully_loaded_matrix",
4825 sm.getMatrixName()));
4827 else if (FileFormat.Jnet.equals(format))
4829 JPredFile predictions = new JPredFile(file, sourceType);
4830 new JnetAnnotationMaker();
4831 JnetAnnotationMaker.add_annotation(predictions,
4832 viewport.getAlignment(), 0, false);
4833 viewport.getAlignment().setupJPredAlignment();
4834 isAnnotation = true;
4836 // else if (IdentifyFile.FeaturesFile.equals(format))
4837 else if (FileFormat.Features.equals(format))
4839 if (parseFeaturesFile(file, sourceType))
4841 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4842 if (splitFrame != null)
4844 splitFrame.repaint();
4848 alignPanel.paintAlignment(true, true);
4854 new FileLoader().LoadFile(viewport, file, sourceType, format);
4860 updateForAnnotations();
4862 } catch (Exception ex)
4864 ex.printStackTrace();
4865 } catch (OutOfMemoryError oom)
4870 } catch (Exception x)
4875 + (sourceType != null
4876 ? (sourceType == DataSourceType.PASTE
4878 : "using " + sourceType + " from "
4882 ? "(parsing as '" + format + "' file)"
4884 oom, Desktop.desktop);
4889 * Do all updates necessary after an annotation file such as jnet. Also called
4890 * from Jalview.loadAppletParams for "annotations", "jnetFile"
4893 public void updateForAnnotations()
4895 alignPanel.adjustAnnotationHeight();
4896 viewport.updateSequenceIdColours();
4897 buildSortByAnnotationScoresMenu();
4898 alignPanel.paintAlignment(true, true);
4902 * Change the display state for the given feature groups -- Added by BH from
4906 * list of group strings
4908 * visible or invisible
4910 public void setFeatureGroupState(String[] groups, boolean state)
4912 jalview.api.FeatureRenderer fr = null;
4913 viewport.setShowSequenceFeatures(true);
4914 if (alignPanel != null
4915 && (fr = alignPanel.getFeatureRenderer()) != null)
4918 fr.setGroupVisibility(Arrays.asList(groups), state);
4919 alignPanel.getSeqPanel().seqCanvas.repaint();
4920 if (alignPanel.overviewPanel != null)
4922 alignPanel.overviewPanel.updateOverviewImage();
4929 * Method invoked by the ChangeListener on the tabbed pane, in other words
4930 * when a different tabbed pane is selected by the user or programmatically.
4933 public void tabSelectionChanged(int index)
4937 alignPanel = alignPanels.get(index);
4938 viewport = alignPanel.av;
4939 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4940 setMenusFromViewport(viewport);
4941 if (featureSettings != null && featureSettings.isOpen()
4942 && featureSettings.fr.getViewport() != viewport)
4944 if (viewport.isShowSequenceFeatures())
4946 // refresh the featureSettings to reflect UI change
4947 showFeatureSettingsUI();
4951 // close feature settings for this view.
4952 featureSettings.close();
4959 * 'focus' any colour slider that is open to the selected viewport
4961 if (viewport.getConservationSelected())
4963 SliderPanel.setConservationSlider(alignPanel,
4964 viewport.getResidueShading(), alignPanel.getViewName());
4968 SliderPanel.hideConservationSlider();
4970 if (viewport.getAbovePIDThreshold())
4972 SliderPanel.setPIDSliderSource(alignPanel,
4973 viewport.getResidueShading(), alignPanel.getViewName());
4977 SliderPanel.hidePIDSlider();
4981 * If there is a frame linked to this one in a SplitPane, switch it to the
4982 * same view tab index. No infinite recursion of calls should happen, since
4983 * tabSelectionChanged() should not get invoked on setting the selected
4984 * index to an unchanged value. Guard against setting an invalid index
4985 * before the new view peer tab has been created.
4987 final AlignViewportI peer = viewport.getCodingComplement();
4990 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4991 .getAlignPanel().alignFrame;
4992 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4994 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5000 * On right mouse click on view tab, prompt for and set new view name.
5003 public void tabbedPane_mousePressed(MouseEvent e)
5005 if (e.isPopupTrigger())
5007 String msg = MessageManager.getString("label.enter_view_name");
5008 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5009 String reply = JvOptionPane.showInputDialog(msg, ttl);
5013 viewport.setViewName(reply);
5014 // TODO warn if reply is in getExistingViewNames()?
5015 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5020 public AlignViewport getCurrentView()
5026 * Open the dialog for regex description parsing.
5029 protected void extractScores_actionPerformed(ActionEvent e)
5031 ParseProperties pp = new jalview.analysis.ParseProperties(
5032 viewport.getAlignment());
5033 // TODO: verify regex and introduce GUI dialog for version 2.5
5034 // if (pp.getScoresFromDescription("col", "score column ",
5035 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5037 if (pp.getScoresFromDescription("description column",
5038 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5040 buildSortByAnnotationScoresMenu();
5048 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5052 protected void showDbRefs_actionPerformed(ActionEvent e)
5054 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5060 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5064 protected void showNpFeats_actionPerformed(ActionEvent e)
5066 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5070 * find the viewport amongst the tabs in this alignment frame and close that
5075 public boolean closeView(AlignViewportI av)
5079 this.closeMenuItem_actionPerformed(false);
5082 Component[] comp = tabbedPane.getComponents();
5083 for (int i = 0; comp != null && i < comp.length; i++)
5085 if (comp[i] instanceof AlignmentPanel)
5087 if (((AlignmentPanel) comp[i]).av == av)
5090 closeView((AlignmentPanel) comp[i]);
5098 protected void build_fetchdbmenu(JMenu webService)
5100 // Temporary hack - DBRef Fetcher always top level ws entry.
5101 // TODO We probably want to store a sequence database checklist in
5102 // preferences and have checkboxes.. rather than individual sources selected
5104 final JMenu rfetch = new JMenu(
5105 MessageManager.getString("action.fetch_db_references"));
5106 rfetch.setToolTipText(MessageManager.getString(
5107 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5108 webService.add(rfetch);
5110 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5111 MessageManager.getString("option.trim_retrieved_seqs"));
5112 trimrs.setToolTipText(
5113 MessageManager.getString("label.trim_retrieved_sequences"));
5115 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5116 trimrs.addActionListener(new ActionListener()
5119 public void actionPerformed(ActionEvent e)
5121 trimrs.setSelected(trimrs.isSelected());
5122 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5123 Boolean.valueOf(trimrs.isSelected()).toString());
5127 JMenuItem fetchr = new JMenuItem(
5128 MessageManager.getString("label.standard_databases"));
5129 fetchr.setToolTipText(
5130 MessageManager.getString("label.fetch_embl_uniprot"));
5131 fetchr.addActionListener(new ActionListener()
5135 public void actionPerformed(ActionEvent e)
5137 new Thread(new Runnable()
5142 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5143 .getAlignment().isNucleotide();
5144 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5145 alignPanel.av.getSequenceSelection(),
5146 alignPanel.alignFrame, null,
5147 alignPanel.alignFrame.featureSettings, isNucleotide);
5148 dbRefFetcher.addListener(new FetchFinishedListenerI()
5151 public void finished()
5154 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5155 .getFeatureSettingsModels())
5158 alignPanel.av.mergeFeaturesStyle(srcSettings);
5160 AlignFrame.this.setMenusForViewport();
5163 dbRefFetcher.fetchDBRefs(false);
5171 new Thread(new Runnable()
5176 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5177 .getSequenceFetcherSingleton();
5178 javax.swing.SwingUtilities.invokeLater(new Runnable()
5183 String[] dbclasses = sf.getNonAlignmentSources();
5184 List<DbSourceProxy> otherdb;
5185 JMenu dfetch = new JMenu();
5186 JMenu ifetch = new JMenu();
5187 JMenuItem fetchr = null;
5188 int comp = 0, icomp = 0, mcomp = 15;
5189 String mname = null;
5191 for (String dbclass : dbclasses)
5193 otherdb = sf.getSourceProxy(dbclass);
5194 // add a single entry for this class, or submenu allowing 'fetch
5196 if (otherdb == null || otherdb.size() < 1)
5202 mname = "From " + dbclass;
5204 if (otherdb.size() == 1)
5206 final DbSourceProxy[] dassource = otherdb
5207 .toArray(new DbSourceProxy[0]);
5208 DbSourceProxy src = otherdb.get(0);
5209 fetchr = new JMenuItem(src.getDbSource());
5210 fetchr.addActionListener(new ActionListener()
5214 public void actionPerformed(ActionEvent e)
5216 new Thread(new Runnable()
5222 boolean isNucleotide = alignPanel.alignFrame
5223 .getViewport().getAlignment()
5225 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5226 alignPanel.av.getSequenceSelection(),
5227 alignPanel.alignFrame, dassource,
5228 alignPanel.alignFrame.featureSettings,
5231 .addListener(new FetchFinishedListenerI()
5234 public void finished()
5236 FeatureSettingsModelI srcSettings = dassource[0]
5237 .getFeatureColourScheme();
5238 alignPanel.av.mergeFeaturesStyle(
5240 AlignFrame.this.setMenusForViewport();
5243 dbRefFetcher.fetchDBRefs(false);
5249 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5250 MessageManager.formatMessage(
5251 "label.fetch_retrieve_from", new Object[]
5252 { src.getDbName() })));
5258 final DbSourceProxy[] dassource = otherdb
5259 .toArray(new DbSourceProxy[0]);
5261 DbSourceProxy src = otherdb.get(0);
5262 fetchr = new JMenuItem(MessageManager
5263 .formatMessage("label.fetch_all_param", new Object[]
5264 { src.getDbSource() }));
5265 fetchr.addActionListener(new ActionListener()
5268 public void actionPerformed(ActionEvent e)
5270 new Thread(new Runnable()
5276 boolean isNucleotide = alignPanel.alignFrame
5277 .getViewport().getAlignment()
5279 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5280 alignPanel.av.getSequenceSelection(),
5281 alignPanel.alignFrame, dassource,
5282 alignPanel.alignFrame.featureSettings,
5285 .addListener(new FetchFinishedListenerI()
5288 public void finished()
5290 AlignFrame.this.setMenusForViewport();
5293 dbRefFetcher.fetchDBRefs(false);
5299 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5300 MessageManager.formatMessage(
5301 "label.fetch_retrieve_from_all_sources",
5303 { Integer.valueOf(otherdb.size())
5305 src.getDbSource(), src.getDbName() })));
5308 // and then build the rest of the individual menus
5309 ifetch = new JMenu(MessageManager.formatMessage(
5310 "label.source_from_db_source", new Object[]
5311 { src.getDbSource() }));
5313 String imname = null;
5315 for (DbSourceProxy sproxy : otherdb)
5317 String dbname = sproxy.getDbName();
5318 String sname = dbname.length() > 5
5319 ? dbname.substring(0, 5) + "..."
5321 String msname = dbname.length() > 10
5322 ? dbname.substring(0, 10) + "..."
5326 imname = MessageManager
5327 .formatMessage("label.from_msname", new Object[]
5330 fetchr = new JMenuItem(msname);
5331 final DbSourceProxy[] dassrc = { sproxy };
5332 fetchr.addActionListener(new ActionListener()
5336 public void actionPerformed(ActionEvent e)
5338 new Thread(new Runnable()
5344 boolean isNucleotide = alignPanel.alignFrame
5345 .getViewport().getAlignment()
5347 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5348 alignPanel.av.getSequenceSelection(),
5349 alignPanel.alignFrame, dassrc,
5350 alignPanel.alignFrame.featureSettings,
5353 .addListener(new FetchFinishedListenerI()
5356 public void finished()
5358 AlignFrame.this.setMenusForViewport();
5361 dbRefFetcher.fetchDBRefs(false);
5367 fetchr.setToolTipText(
5368 "<html>" + MessageManager.formatMessage(
5369 "label.fetch_retrieve_from", new Object[]
5373 if (++icomp >= mcomp || i == (otherdb.size()))
5375 ifetch.setText(MessageManager.formatMessage(
5376 "label.source_to_target", imname, sname));
5378 ifetch = new JMenu();
5386 if (comp >= mcomp || dbi >= (dbclasses.length))
5388 dfetch.setText(MessageManager.formatMessage(
5389 "label.source_to_target", mname, dbclass));
5391 dfetch = new JMenu();
5404 * Left justify the whole alignment.
5407 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5409 AlignmentI al = viewport.getAlignment();
5411 viewport.firePropertyChange("alignment", null, al);
5415 * Right justify the whole alignment.
5418 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5420 AlignmentI al = viewport.getAlignment();
5422 viewport.firePropertyChange("alignment", null, al);
5426 public void setShowSeqFeatures(boolean b)
5428 showSeqFeatures.setSelected(b);
5429 viewport.setShowSequenceFeatures(b);
5436 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5437 * awt.event.ActionEvent)
5440 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5442 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5443 alignPanel.paintAlignment(false, false);
5450 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5454 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5456 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5457 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5465 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5466 * .event.ActionEvent)
5469 protected void showGroupConservation_actionPerformed(ActionEvent e)
5471 viewport.setShowGroupConservation(showGroupConservation.getState());
5472 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5479 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5480 * .event.ActionEvent)
5483 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5485 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5486 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5493 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5494 * .event.ActionEvent)
5497 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5499 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5500 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5504 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5506 showSequenceLogo.setState(true);
5507 viewport.setShowSequenceLogo(true);
5508 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5509 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5513 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5515 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5522 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5523 * .event.ActionEvent)
5526 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5528 if (avc.makeGroupsFromSelection())
5530 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5531 alignPanel.updateAnnotation();
5532 alignPanel.paintAlignment(true,
5533 viewport.needToUpdateStructureViews());
5537 public void clearAlignmentSeqRep()
5539 // TODO refactor alignmentseqrep to controller
5540 if (viewport.getAlignment().hasSeqrep())
5542 viewport.getAlignment().setSeqrep(null);
5543 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5544 alignPanel.updateAnnotation();
5545 alignPanel.paintAlignment(true, true);
5550 protected void createGroup_actionPerformed(ActionEvent e)
5552 if (avc.createGroup())
5554 if (applyAutoAnnotationSettings.isSelected())
5556 alignPanel.updateAnnotation(true, false);
5558 alignPanel.alignmentChanged();
5563 protected void unGroup_actionPerformed(ActionEvent e)
5567 alignPanel.alignmentChanged();
5572 * make the given alignmentPanel the currently selected tab
5574 * @param alignmentPanel
5576 public void setDisplayedView(AlignmentPanel alignmentPanel)
5578 if (!viewport.getSequenceSetId()
5579 .equals(alignmentPanel.av.getSequenceSetId()))
5581 throw new Error(MessageManager.getString(
5582 "error.implementation_error_cannot_show_view_alignment_frame"));
5584 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5585 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5587 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5592 * Action on selection of menu options to Show or Hide annotations.
5595 * @param forSequences
5596 * update sequence-related annotations
5597 * @param forAlignment
5598 * update non-sequence-related annotations
5601 protected void setAnnotationsVisibility(boolean visible,
5602 boolean forSequences, boolean forAlignment)
5604 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5605 .getAlignmentAnnotation();
5610 for (AlignmentAnnotation aa : anns)
5613 * don't display non-positional annotations on an alignment
5615 if (aa.annotations == null)
5619 boolean apply = (aa.sequenceRef == null && forAlignment)
5620 || (aa.sequenceRef != null && forSequences);
5623 aa.visible = visible;
5626 alignPanel.validateAnnotationDimensions(true);
5627 alignPanel.alignmentChanged();
5631 * Store selected annotation sort order for the view and repaint.
5634 protected void sortAnnotations_actionPerformed()
5636 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5638 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5639 alignPanel.paintAlignment(false, false);
5644 * @return alignment panels in this alignment frame
5646 public List<? extends AlignmentViewPanel> getAlignPanels()
5648 // alignPanels is never null
5649 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5654 * Open a new alignment window, with the cDNA associated with this (protein)
5655 * alignment, aligned as is the protein.
5657 protected void viewAsCdna_actionPerformed()
5659 // TODO no longer a menu action - refactor as required
5660 final AlignmentI alignment = getViewport().getAlignment();
5661 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5662 if (mappings == null)
5666 List<SequenceI> cdnaSeqs = new ArrayList<>();
5667 for (SequenceI aaSeq : alignment.getSequences())
5669 for (AlignedCodonFrame acf : mappings)
5671 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5675 * There is a cDNA mapping for this protein sequence - add to new
5676 * alignment. It will share the same dataset sequence as other mapped
5677 * cDNA (no new mappings need to be created).
5679 final Sequence newSeq = new Sequence(dnaSeq);
5680 newSeq.setDatasetSequence(dnaSeq);
5681 cdnaSeqs.add(newSeq);
5685 if (cdnaSeqs.size() == 0)
5687 // show a warning dialog no mapped cDNA
5690 AlignmentI cdna = new Alignment(
5691 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5692 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5693 AlignFrame.DEFAULT_HEIGHT);
5694 cdna.alignAs(alignment);
5695 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5697 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5698 AlignFrame.DEFAULT_HEIGHT);
5702 * Set visibility of dna/protein complement view (available when shown in a
5708 protected void showComplement_actionPerformed(boolean show)
5710 SplitContainerI sf = getSplitViewContainer();
5713 sf.setComplementVisible(this, show);
5718 * Generate the reverse (optionally complemented) of the selected sequences,
5719 * and add them to the alignment
5722 protected void showReverse_actionPerformed(boolean complement)
5724 AlignmentI al = null;
5727 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5728 al = dna.reverseCdna(complement);
5729 viewport.addAlignment(al, "");
5730 addHistoryItem(new EditCommand(
5731 MessageManager.getString("label.add_sequences"), Action.PASTE,
5732 al.getSequencesArray(), 0, al.getWidth(),
5733 viewport.getAlignment()));
5734 } catch (Exception ex)
5736 System.err.println(ex.getMessage());
5742 * Try to run a script in the Groovy console, having first ensured that this
5743 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5744 * be targeted at this alignment.
5747 protected void runGroovy_actionPerformed()
5749 Jalview.setCurrentAlignFrame(this);
5750 groovy.ui.Console console = Desktop.getGroovyConsole();
5751 if (console != null)
5755 console.runScript();
5756 } catch (Exception ex)
5758 System.err.println((ex.toString()));
5759 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5760 MessageManager.getString("label.couldnt_run_groovy_script"),
5761 MessageManager.getString("label.groovy_support_failed"),
5762 JvOptionPane.ERROR_MESSAGE);
5767 System.err.println("Can't run Groovy script as console not found");
5772 * Hides columns containing (or not containing) a specified feature, provided
5773 * that would not leave all columns hidden
5775 * @param featureType
5776 * @param columnsContaining
5779 public boolean hideFeatureColumns(String featureType,
5780 boolean columnsContaining)
5782 boolean notForHiding = avc.markColumnsContainingFeatures(
5783 columnsContaining, false, false, featureType);
5786 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5787 false, featureType))
5789 getViewport().hideSelectedColumns();
5797 protected void selectHighlightedColumns_actionPerformed(
5798 ActionEvent actionEvent)
5800 // include key modifier check in case user selects from menu
5801 avc.markHighlightedColumns(
5802 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5803 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5804 | ActionEvent.CTRL_MASK)) != 0);
5808 * Rebuilds the Colour menu, including any user-defined colours which have
5809 * been loaded either on startup or during the session
5811 public void buildColourMenu()
5813 colourMenu.removeAll();
5815 colourMenu.add(applyToAllGroups);
5816 colourMenu.add(textColour);
5817 colourMenu.addSeparator();
5819 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5820 viewport.getAlignment(), false);
5822 colourMenu.add(annotationColour);
5823 bg.add(annotationColour);
5824 colourMenu.addSeparator();
5825 colourMenu.add(conservationMenuItem);
5826 colourMenu.add(modifyConservation);
5827 colourMenu.add(abovePIDThreshold);
5828 colourMenu.add(modifyPID);
5830 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5831 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5835 * Open a dialog (if not already open) that allows the user to select and
5836 * calculate PCA or Tree analysis
5838 protected void openTreePcaDialog()
5840 if (alignPanel.getCalculationDialog() == null)
5842 new CalculationChooser(AlignFrame.this);
5847 protected void loadVcf_actionPerformed()
5849 JalviewFileChooser chooser = new JalviewFileChooser(
5850 Cache.getProperty("LAST_DIRECTORY"));
5851 chooser.setFileView(new JalviewFileView());
5852 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5853 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5854 final AlignFrame us = this;
5855 chooser.setResponseHandler(0, new Runnable()
5860 String choice = chooser.getSelectedFile().getPath();
5861 Cache.setProperty("LAST_DIRECTORY", choice);
5862 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5863 new VCFLoader(choice).loadVCF(seqs, us);
5866 chooser.showOpenDialog(null);
5870 private Rectangle lastFeatureSettingsBounds = null;
5872 public void setFeatureSettingsGeometry(Rectangle bounds)
5874 lastFeatureSettingsBounds = bounds;
5878 public Rectangle getFeatureSettingsGeometry()
5880 return lastFeatureSettingsBounds;
5883 public void scrollTo(int row, int column)
5885 alignPanel.getSeqPanel().scrollTo(row, column);
5888 public void scrollToRow(int row)
5890 alignPanel.getSeqPanel().scrollToRow(row);
5893 public void scrollToColumn(int column)
5895 alignPanel.getSeqPanel().scrollToColumn(column);
5899 * BH 2019 from JalviewLite
5901 * get sequence feature groups that are hidden or shown
5907 public String[] getFeatureGroupsOfState(boolean visible)
5909 jalview.api.FeatureRenderer fr = null;
5910 if (alignPanel != null
5912 .getFeatureRenderer()) != null)
5914 List<String> gps = fr.getGroups(visible);
5915 String[] _gps = gps.toArray(new String[gps.size()]);
5923 * @return list of feature groups on the view
5925 public String[] getFeatureGroups()
5927 jalview.api.FeatureRenderer fr = null;
5928 if (alignPanel != null
5929 && (fr = alignPanel.getFeatureRenderer()) != null)
5931 List<String> gps = fr.getFeatureGroups();
5932 String[] _gps = gps.toArray(new String[gps.size()]);
5938 public void select(SequenceGroup sel, ColumnSelection csel,
5939 HiddenColumns hidden)
5941 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
5947 class PrintThread extends Thread
5951 public PrintThread(AlignmentPanel ap)
5956 static PageFormat pf;
5961 PrinterJob printJob = PrinterJob.getPrinterJob();
5965 printJob.setPrintable(ap, pf);
5969 printJob.setPrintable(ap);
5972 if (printJob.printDialog())
5977 } catch (Exception PrintException)
5979 PrintException.printStackTrace();