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.Rectangle;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.DataFlavor;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.dnd.DnDConstants;
33 import java.awt.dnd.DropTargetDragEvent;
34 import java.awt.dnd.DropTargetDropEvent;
35 import java.awt.dnd.DropTargetEvent;
36 import java.awt.dnd.DropTargetListener;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.event.FocusAdapter;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.ItemEvent;
42 import java.awt.event.ItemListener;
43 import java.awt.event.KeyAdapter;
44 import java.awt.event.KeyEvent;
45 import java.awt.event.MouseEvent;
46 import java.awt.print.PageFormat;
47 import java.awt.print.PrinterJob;
48 import java.beans.PropertyChangeEvent;
50 import java.io.FileWriter;
51 import java.io.IOException;
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.Locale;
61 import java.util.Vector;
63 import javax.swing.ButtonGroup;
64 import javax.swing.JCheckBoxMenuItem;
65 import javax.swing.JComponent;
66 import javax.swing.JEditorPane;
67 import javax.swing.JInternalFrame;
68 import javax.swing.JLabel;
69 import javax.swing.JLayeredPane;
70 import javax.swing.JMenu;
71 import javax.swing.JMenuItem;
72 import javax.swing.JPanel;
73 import javax.swing.JScrollPane;
74 import javax.swing.SwingUtilities;
76 import ext.vamsas.ServiceHandle;
77 import jalview.analysis.AlignmentSorter;
78 import jalview.analysis.AlignmentUtils;
79 import jalview.analysis.CrossRef;
80 import jalview.analysis.Dna;
81 import jalview.analysis.GeneticCodeI;
82 import jalview.analysis.ParseProperties;
83 import jalview.analysis.SequenceIdMatcher;
84 import jalview.api.AlignExportSettingsI;
85 import jalview.api.AlignViewControllerGuiI;
86 import jalview.api.AlignViewControllerI;
87 import jalview.api.AlignViewportI;
88 import jalview.api.AlignmentViewPanel;
89 import jalview.api.FeatureSettingsControllerI;
90 import jalview.api.FeatureSettingsModelI;
91 import jalview.api.SplitContainerI;
92 import jalview.api.ViewStyleI;
93 import jalview.api.analysis.SimilarityParamsI;
94 import jalview.bin.Cache;
95 import jalview.bin.Console;
96 import jalview.bin.Jalview;
97 import jalview.commands.CommandI;
98 import jalview.commands.EditCommand;
99 import jalview.commands.EditCommand.Action;
100 import jalview.commands.OrderCommand;
101 import jalview.commands.RemoveGapColCommand;
102 import jalview.commands.RemoveGapsCommand;
103 import jalview.commands.SlideSequencesCommand;
104 import jalview.commands.TrimRegionCommand;
105 import jalview.datamodel.AlignExportSettingsAdapter;
106 import jalview.datamodel.AlignedCodonFrame;
107 import jalview.datamodel.Alignment;
108 import jalview.datamodel.AlignmentAnnotation;
109 import jalview.datamodel.AlignmentExportData;
110 import jalview.datamodel.AlignmentI;
111 import jalview.datamodel.AlignmentOrder;
112 import jalview.datamodel.AlignmentView;
113 import jalview.datamodel.ColumnSelection;
114 import jalview.datamodel.HiddenColumns;
115 import jalview.datamodel.PDBEntry;
116 import jalview.datamodel.SeqCigar;
117 import jalview.datamodel.Sequence;
118 import jalview.datamodel.SequenceGroup;
119 import jalview.datamodel.SequenceI;
120 import jalview.gui.ColourMenuHelper.ColourChangeListener;
121 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
122 import jalview.io.AlignmentProperties;
123 import jalview.io.AnnotationFile;
124 import jalview.io.BackupFiles;
125 import jalview.io.BioJsHTMLOutput;
126 import jalview.io.DataSourceType;
127 import jalview.io.FileFormat;
128 import jalview.io.FileFormatI;
129 import jalview.io.FileFormats;
130 import jalview.io.FileLoader;
131 import jalview.io.FileParse;
132 import jalview.io.FormatAdapter;
133 import jalview.io.HtmlSvgOutput;
134 import jalview.io.IdentifyFile;
135 import jalview.io.JPredFile;
136 import jalview.io.JalviewFileChooser;
137 import jalview.io.JalviewFileView;
138 import jalview.io.JnetAnnotationMaker;
139 import jalview.io.NewickFile;
140 import jalview.io.ScoreMatrixFile;
141 import jalview.io.TCoffeeScoreFile;
142 import jalview.io.vcf.VCFLoader;
143 import jalview.jbgui.GAlignFrame;
144 import jalview.project.Jalview2XML;
145 import jalview.schemes.ColourSchemeI;
146 import jalview.schemes.ColourSchemes;
147 import jalview.schemes.ResidueColourScheme;
148 import jalview.schemes.TCoffeeColourScheme;
149 import jalview.util.HttpUtils;
150 import jalview.util.ImageMaker.TYPE;
151 import jalview.util.MessageManager;
152 import jalview.util.Platform;
153 import jalview.viewmodel.AlignmentViewport;
154 import jalview.viewmodel.ViewportRanges;
155 import jalview.ws.DBRefFetcher;
156 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
157 import jalview.ws.jws1.Discoverer;
158 import jalview.ws.jws2.Jws2Discoverer;
159 import jalview.ws.jws2.jabaws2.Jws2Instance;
160 import jalview.ws.seqfetcher.DbSourceProxy;
166 * @version $Revision$
168 @SuppressWarnings("serial")
169 public class AlignFrame extends GAlignFrame implements DropTargetListener,
170 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
173 public static final int DEFAULT_WIDTH = 700;
175 public static final int DEFAULT_HEIGHT = 500;
178 * The currently displayed panel (selected tabbed view if more than one)
180 public AlignmentPanel alignPanel;
182 AlignViewport viewport;
184 public AlignViewControllerI avc;
186 List<AlignmentPanel> alignPanels = new ArrayList<>();
189 * Last format used to load or save alignments in this window
191 FileFormatI currentFileFormat = null;
194 * Current filename for this alignment
196 String fileName = null;
201 * Creates a new AlignFrame object with specific width and height.
207 public AlignFrame(AlignmentI al, int width, int height)
209 this(al, null, width, height);
213 * Creates a new AlignFrame object with specific width, height and
219 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId)
224 this(al, null, width, height, sequenceSetId);
228 * Creates a new AlignFrame object with specific width, height and
234 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId, String viewId)
240 this(al, null, width, height, sequenceSetId, viewId);
244 * new alignment window with hidden columns
248 * @param hiddenColumns
249 * ColumnSelection or null
251 * Width of alignment frame
255 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
258 this(al, hiddenColumns, width, height, null);
262 * Create alignment frame for al with hiddenColumns, a specific width and
263 * height, and specific sequenceId
266 * @param hiddenColumns
269 * @param sequenceSetId
272 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
273 int height, String sequenceSetId)
275 this(al, hiddenColumns, width, height, sequenceSetId, null);
279 * Create alignment frame for al with hiddenColumns, a specific width and
280 * height, and specific sequenceId
283 * @param hiddenColumns
286 * @param sequenceSetId
291 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
292 int height, String sequenceSetId, String viewId)
294 setSize(width, height);
296 if (al.getDataset() == null)
301 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
303 alignPanel = new AlignmentPanel(this, viewport);
305 addAlignmentPanel(alignPanel, true);
309 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
310 HiddenColumns hiddenColumns, int width, int height)
312 setSize(width, height);
314 if (al.getDataset() == null)
319 viewport = new AlignViewport(al, hiddenColumns);
321 if (hiddenSeqs != null && hiddenSeqs.length > 0)
323 viewport.hideSequence(hiddenSeqs);
325 alignPanel = new AlignmentPanel(this, viewport);
326 addAlignmentPanel(alignPanel, true);
331 * Make a new AlignFrame from existing alignmentPanels
338 public AlignFrame(AlignmentPanel ap)
342 addAlignmentPanel(ap, false);
347 * initalise the alignframe from the underlying viewport data and the
352 // setBackground(Color.white); // BH 2019
354 if (!Jalview.isHeadlessMode())
356 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
359 avc = new jalview.controller.AlignViewController(this, viewport,
361 if (viewport.getAlignmentConservationAnnotation() == null)
363 // BLOSUM62Colour.setEnabled(false);
364 conservationMenuItem.setEnabled(false);
365 modifyConservation.setEnabled(false);
366 // PIDColour.setEnabled(false);
367 // abovePIDThreshold.setEnabled(false);
368 // modifyPID.setEnabled(false);
371 String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
373 if (sortby.equals("Id"))
375 sortIDMenuItem_actionPerformed(null);
377 else if (sortby.equals("Pairwise Identity"))
379 sortPairwiseMenuItem_actionPerformed(null);
383 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
385 setMenusFromViewport(viewport);
386 buildSortByAnnotationScoresMenu();
387 calculateTree.addActionListener(new ActionListener()
391 public void actionPerformed(ActionEvent e)
398 if (Desktop.desktop != null)
400 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
401 if (!Platform.isJS())
403 addServiceListeners();
408 if (viewport.getWrapAlignment())
410 wrapMenuItem_actionPerformed(null);
413 if (Cache.getDefault("SHOW_OVERVIEW", false))
415 this.overviewMenuItem_actionPerformed(null);
420 final List<AlignmentViewPanel> selviews = new ArrayList<>();
421 final List<AlignmentPanel> origview = new ArrayList<>();
422 final String menuLabel = MessageManager
423 .getString("label.copy_format_from");
424 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
425 new ViewSetProvider()
429 public AlignmentPanel[] getAllAlignmentPanels()
432 origview.add(alignPanel);
433 // make an array of all alignment panels except for this one
434 List<AlignmentPanel> aps = new ArrayList<>(
435 Arrays.asList(Desktop.getAlignmentPanels(null)));
436 aps.remove(AlignFrame.this.alignPanel);
437 return aps.toArray(new AlignmentPanel[aps.size()]);
439 }, selviews, new ItemListener()
443 public void itemStateChanged(ItemEvent e)
445 if (origview.size() > 0)
447 final AlignmentPanel ap = origview.get(0);
450 * Copy the ViewStyle of the selected panel to 'this one'.
451 * Don't change value of 'scaleProteinAsCdna' unless copying
454 ViewStyleI vs = selviews.get(0).getAlignViewport()
456 boolean fromSplitFrame = selviews.get(0)
457 .getAlignViewport().getCodingComplement() != null;
460 vs.setScaleProteinAsCdna(ap.getAlignViewport()
461 .getViewStyle().isScaleProteinAsCdna());
463 ap.getAlignViewport().setViewStyle(vs);
466 * Also rescale ViewStyle of SplitFrame complement if there is
467 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
468 * the whole ViewStyle (allow cDNA protein to have different
471 AlignViewportI complement = ap.getAlignViewport()
472 .getCodingComplement();
473 if (complement != null && vs.isScaleProteinAsCdna())
475 AlignFrame af = Desktop.getAlignFrameFor(complement);
476 ((SplitFrame) af.getSplitViewContainer())
478 af.setMenusForViewport();
482 ap.setSelected(true);
483 ap.alignFrame.setMenusForViewport();
488 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
489 .indexOf("devel") > -1
490 || Cache.getDefault("VERSION", "DEVELOPMENT")
491 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
493 formatMenu.add(vsel);
495 addFocusListener(new FocusAdapter()
498 public void focusGained(FocusEvent e)
500 Jalview.setCurrentAlignFrame(AlignFrame.this);
507 * Change the filename and format for the alignment, and enable the 'reload'
508 * button functionality.
515 public void setFileName(String file, FileFormatI format)
518 setFileFormat(format);
519 reload.setEnabled(true);
523 * JavaScript will have this, maybe others. More dependable than a file name
524 * and maintains a reference to the actual bytes loaded.
528 public void setFileObject(File file)
530 this.fileObject = file;
534 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
537 void addKeyListener()
539 addKeyListener(new KeyAdapter()
542 public void keyPressed(KeyEvent evt)
544 if (viewport.cursorMode
545 && ((evt.getKeyCode() >= KeyEvent.VK_0
546 && evt.getKeyCode() <= KeyEvent.VK_9)
547 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
548 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
549 && Character.isDigit(evt.getKeyChar()))
551 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
554 switch (evt.getKeyCode())
557 case 27: // escape key
558 deselectAllSequenceMenuItem_actionPerformed(null);
562 case KeyEvent.VK_DOWN:
563 if (evt.isAltDown() || !viewport.cursorMode)
565 moveSelectedSequences(false);
567 if (viewport.cursorMode)
569 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
574 if (evt.isAltDown() || !viewport.cursorMode)
576 moveSelectedSequences(true);
578 if (viewport.cursorMode)
580 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
585 case KeyEvent.VK_LEFT:
586 if (evt.isAltDown() || !viewport.cursorMode)
588 slideSequences(false,
589 alignPanel.getSeqPanel().getKeyboardNo1());
593 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
598 case KeyEvent.VK_RIGHT:
599 if (evt.isAltDown() || !viewport.cursorMode)
601 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
605 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
609 case KeyEvent.VK_SPACE:
610 if (viewport.cursorMode)
612 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
613 || evt.isShiftDown() || evt.isAltDown());
617 // case KeyEvent.VK_A:
618 // if (viewport.cursorMode)
620 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
621 // //System.out.println("A");
625 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
626 * System.out.println("closing bracket"); } break;
628 case KeyEvent.VK_DELETE:
629 case KeyEvent.VK_BACK_SPACE:
630 if (!viewport.cursorMode)
632 cut_actionPerformed();
636 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
637 || evt.isShiftDown() || evt.isAltDown());
643 if (viewport.cursorMode)
645 alignPanel.getSeqPanel().setCursorRow();
649 if (viewport.cursorMode && !evt.isControlDown())
651 alignPanel.getSeqPanel().setCursorColumn();
655 if (viewport.cursorMode)
657 alignPanel.getSeqPanel().setCursorPosition();
661 case KeyEvent.VK_ENTER:
662 case KeyEvent.VK_COMMA:
663 if (viewport.cursorMode)
665 alignPanel.getSeqPanel().setCursorRowAndColumn();
670 if (viewport.cursorMode)
672 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
676 if (viewport.cursorMode)
678 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
683 viewport.cursorMode = !viewport.cursorMode;
684 setStatus(MessageManager
685 .formatMessage("label.keyboard_editing_mode", new String[]
686 { (viewport.cursorMode ? "on" : "off") }));
687 if (viewport.cursorMode)
689 ViewportRanges ranges = viewport.getRanges();
690 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
692 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
695 alignPanel.getSeqPanel().seqCanvas.repaint();
701 Help.showHelpWindow();
702 } catch (Exception ex)
704 ex.printStackTrace();
709 boolean toggleSeqs = !evt.isControlDown();
710 boolean toggleCols = !evt.isShiftDown();
711 toggleHiddenRegions(toggleSeqs, toggleCols);
716 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
717 boolean modifyExisting = true; // always modify, don't clear
718 // evt.isShiftDown();
719 boolean invertHighlighted = evt.isAltDown();
720 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
724 case KeyEvent.VK_PAGE_UP:
725 viewport.getRanges().pageUp();
727 case KeyEvent.VK_PAGE_DOWN:
728 viewport.getRanges().pageDown();
734 public void keyReleased(KeyEvent evt)
736 switch (evt.getKeyCode())
738 case KeyEvent.VK_LEFT:
739 if (evt.isAltDown() || !viewport.cursorMode)
741 viewport.firePropertyChange("alignment", null,
742 viewport.getAlignment().getSequences());
746 case KeyEvent.VK_RIGHT:
747 if (evt.isAltDown() || !viewport.cursorMode)
749 viewport.firePropertyChange("alignment", null,
750 viewport.getAlignment().getSequences());
758 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
760 ap.alignFrame = this;
761 avc = new jalview.controller.AlignViewController(this, viewport,
766 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
768 int aSize = alignPanels.size();
770 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
772 if (aSize == 1 && ap.av.getViewName() == null)
774 this.getContentPane().add(ap, BorderLayout.CENTER);
780 setInitialTabVisible();
783 expandViews.setEnabled(true);
784 gatherViews.setEnabled(true);
785 tabbedPane.addTab(ap.av.getViewName(), ap);
787 ap.setVisible(false);
792 if (ap.av.isPadGaps())
794 ap.av.getAlignment().padGaps();
796 ap.av.updateConservation(ap);
797 ap.av.updateConsensus(ap);
798 ap.av.updateStrucConsensus(ap);
802 public void setInitialTabVisible()
804 expandViews.setEnabled(true);
805 gatherViews.setEnabled(true);
806 tabbedPane.setVisible(true);
807 AlignmentPanel first = alignPanels.get(0);
808 tabbedPane.addTab(first.av.getViewName(), first);
809 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
812 public AlignViewport getViewport()
817 /* Set up intrinsic listeners for dynamically generated GUI bits. */
818 private void addServiceListeners()
820 final java.beans.PropertyChangeListener thisListener;
821 Desktop.instance.addJalviewPropertyChangeListener("services",
822 thisListener = new java.beans.PropertyChangeListener()
825 public void propertyChange(PropertyChangeEvent evt)
827 // // System.out.println("Discoverer property change.");
828 // if (evt.getPropertyName().equals("services"))
830 SwingUtilities.invokeLater(new Runnable()
837 "Rebuild WS Menu for service change");
838 BuildWebServiceMenu();
845 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
848 public void internalFrameClosed(
849 javax.swing.event.InternalFrameEvent evt)
851 // System.out.println("deregistering discoverer listener");
852 Desktop.instance.removeJalviewPropertyChangeListener("services",
854 closeMenuItem_actionPerformed(true);
857 // Finally, build the menu once to get current service state
858 new Thread(new Runnable()
863 BuildWebServiceMenu();
869 * Configure menu items that vary according to whether the alignment is
870 * nucleotide or protein
872 public void setGUINucleotide()
874 AlignmentI al = getViewport().getAlignment();
875 boolean nucleotide = al.isNucleotide();
877 loadVcf.setVisible(nucleotide);
878 showTranslation.setVisible(nucleotide);
879 showReverse.setVisible(nucleotide);
880 showReverseComplement.setVisible(nucleotide);
881 conservationMenuItem.setEnabled(!nucleotide);
883 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
884 showGroupConservation.setEnabled(!nucleotide);
886 showComplementMenuItem
887 .setText(nucleotide ? MessageManager.getString("label.protein")
888 : MessageManager.getString("label.nucleotide"));
892 * set up menus for the current viewport. This may be called after any
893 * operation that affects the data in the current view (selection changed,
894 * etc) to update the menus to reflect the new state.
897 public void setMenusForViewport()
899 setMenusFromViewport(viewport);
903 * Need to call this method when tabs are selected for multiple views, or when
904 * loading from Jalview2XML.java
909 public void setMenusFromViewport(AlignViewport av)
911 padGapsMenuitem.setSelected(av.isPadGaps());
912 colourTextMenuItem.setSelected(av.isShowColourText());
913 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
914 modifyPID.setEnabled(abovePIDThreshold.isSelected());
915 conservationMenuItem.setSelected(av.getConservationSelected());
916 modifyConservation.setEnabled(conservationMenuItem.isSelected());
917 seqLimits.setSelected(av.getShowJVSuffix());
918 idRightAlign.setSelected(av.isRightAlignIds());
919 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
920 renderGapsMenuItem.setSelected(av.isRenderGaps());
921 wrapMenuItem.setSelected(av.getWrapAlignment());
922 scaleAbove.setVisible(av.getWrapAlignment());
923 scaleLeft.setVisible(av.getWrapAlignment());
924 scaleRight.setVisible(av.getWrapAlignment());
925 annotationPanelMenuItem.setState(av.isShowAnnotation());
927 * Show/hide annotations only enabled if annotation panel is shown
929 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
930 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
931 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
932 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
933 viewBoxesMenuItem.setSelected(av.getShowBoxes());
934 viewTextMenuItem.setSelected(av.getShowText());
935 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
936 showGroupConsensus.setSelected(av.isShowGroupConsensus());
937 showGroupConservation.setSelected(av.isShowGroupConservation());
938 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
939 showSequenceLogo.setSelected(av.isShowSequenceLogo());
940 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
942 ColourMenuHelper.setColourSelected(colourMenu,
943 av.getGlobalColourScheme());
945 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
946 hiddenMarkers.setState(av.getShowHiddenMarkers());
947 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
948 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
949 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
950 autoCalculate.setSelected(av.autoCalculateConsensus);
951 sortByTree.setSelected(av.sortByTree);
952 listenToViewSelections.setSelected(av.followSelection);
954 showProducts.setEnabled(canShowProducts());
955 setGroovyEnabled(Desktop.getGroovyConsole() != null);
961 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
965 public void setGroovyEnabled(boolean b)
967 runGroovy.setEnabled(b);
970 private IProgressIndicator progressBar;
975 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
978 public void setProgressBar(String message, long id)
980 progressBar.setProgressBar(message, id);
984 public void registerHandler(final long id,
985 final IProgressIndicatorHandler handler)
987 progressBar.registerHandler(id, handler);
992 * @return true if any progress bars are still active
995 public boolean operationInProgress()
997 return progressBar.operationInProgress();
1001 * Sets the text of the status bar. Note that setting a null or empty value
1002 * will cause the status bar to be hidden, with possibly undesirable flicker
1003 * of the screen layout.
1006 public void setStatus(String text)
1008 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1012 * Added so Castor Mapping file can obtain Jalview Version
1014 public String getVersion()
1016 return Cache.getProperty("VERSION");
1019 public FeatureRenderer getFeatureRenderer()
1021 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1025 public void fetchSequence_actionPerformed()
1027 new SequenceFetcher(this);
1031 public void addFromFile_actionPerformed(ActionEvent e)
1033 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1037 public void reload_actionPerformed(ActionEvent e)
1039 if (fileName != null)
1041 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1042 // originating file's format
1043 // TODO: work out how to recover feature settings for correct view(s) when
1044 // file is reloaded.
1045 if (FileFormat.Jalview.equals(currentFileFormat))
1047 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1048 for (int i = 0; i < frames.length; i++)
1050 if (frames[i] instanceof AlignFrame && frames[i] != this
1051 && ((AlignFrame) frames[i]).fileName != null
1052 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1056 frames[i].setSelected(true);
1057 Desktop.instance.closeAssociatedWindows();
1058 } catch (java.beans.PropertyVetoException ex)
1064 Desktop.instance.closeAssociatedWindows();
1066 FileLoader loader = new FileLoader();
1067 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1068 ? DataSourceType.URL
1069 : DataSourceType.FILE;
1070 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1074 Rectangle bounds = this.getBounds();
1076 FileLoader loader = new FileLoader();
1078 AlignFrame newframe = null;
1080 if (fileObject == null)
1083 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1084 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1085 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1090 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1091 DataSourceType.FILE, currentFileFormat);
1094 newframe.setBounds(bounds);
1095 if (featureSettings != null && featureSettings.isShowing())
1097 final Rectangle fspos = featureSettings.frame.getBounds();
1098 // TODO: need a 'show feature settings' function that takes bounds -
1099 // need to refactor Desktop.addFrame
1100 newframe.featureSettings_actionPerformed(null);
1101 final FeatureSettings nfs = newframe.featureSettings;
1102 SwingUtilities.invokeLater(new Runnable()
1107 nfs.frame.setBounds(fspos);
1110 this.featureSettings.close();
1111 this.featureSettings = null;
1113 this.closeMenuItem_actionPerformed(true);
1119 public void addFromText_actionPerformed(ActionEvent e)
1122 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1126 public void addFromURL_actionPerformed(ActionEvent e)
1128 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1132 public void save_actionPerformed(ActionEvent e)
1134 if (fileName == null || (currentFileFormat == null)
1135 || HttpUtils.startsWithHttpOrHttps(fileName))
1137 saveAs_actionPerformed();
1141 saveAlignment(fileName, currentFileFormat);
1146 * Saves the alignment to a file with a name chosen by the user, if necessary
1147 * warning if a file would be overwritten
1150 public void saveAs_actionPerformed()
1152 String format = currentFileFormat == null ? null
1153 : currentFileFormat.getName();
1154 JalviewFileChooser chooser = JalviewFileChooser
1155 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1157 chooser.setFileView(new JalviewFileView());
1158 chooser.setDialogTitle(
1159 MessageManager.getString("label.save_alignment_to_file"));
1160 chooser.setToolTipText(MessageManager.getString("action.save"));
1162 int value = chooser.showSaveDialog(this);
1164 if (value != JalviewFileChooser.APPROVE_OPTION)
1168 currentFileFormat = chooser.getSelectedFormat();
1169 // todo is this (2005) test now obsolete - value is never null?
1170 while (currentFileFormat == null)
1172 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1174 .getString("label.select_file_format_before_saving"),
1175 MessageManager.getString("label.file_format_not_specified"),
1176 JvOptionPane.WARNING_MESSAGE);
1177 currentFileFormat = chooser.getSelectedFormat();
1178 value = chooser.showSaveDialog(this);
1179 if (value != JalviewFileChooser.APPROVE_OPTION)
1185 fileName = chooser.getSelectedFile().getPath();
1187 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1188 Cache.setProperty("LAST_DIRECTORY", fileName);
1189 saveAlignment(fileName, currentFileFormat);
1192 boolean lastSaveSuccessful = false;
1194 FileFormatI lastFormatSaved;
1196 String lastFilenameSaved;
1199 * Raise a dialog or status message for the last call to saveAlignment.
1201 * @return true if last call to saveAlignment(file, format) was successful.
1203 public boolean isSaveAlignmentSuccessful()
1206 if (!lastSaveSuccessful)
1208 if (!Platform.isHeadless())
1210 JvOptionPane.showInternalMessageDialog(this, MessageManager
1211 .formatMessage("label.couldnt_save_file", new Object[]
1212 { lastFilenameSaved }),
1213 MessageManager.getString("label.error_saving_file"),
1214 JvOptionPane.WARNING_MESSAGE);
1218 Console.error(MessageManager
1219 .formatMessage("label.couldnt_save_file", new Object[]
1220 { lastFilenameSaved }));
1226 setStatus(MessageManager.formatMessage(
1227 "label.successfully_saved_to_file_in_format", new Object[]
1228 { lastFilenameSaved, lastFormatSaved }));
1231 return lastSaveSuccessful;
1235 * Saves the alignment to the specified file path, in the specified format,
1236 * which may be an alignment format, or Jalview project format. If the
1237 * alignment has hidden regions, or the format is one capable of including
1238 * non-sequence data (features, annotations, groups), then the user may be
1239 * prompted to specify what to include in the output.
1244 public void saveAlignment(String file, FileFormatI format)
1246 lastSaveSuccessful = true;
1247 lastFilenameSaved = file;
1248 lastFormatSaved = format;
1250 if (FileFormat.Jalview.equals(format))
1252 String shortName = title;
1253 if (shortName.indexOf(File.separatorChar) > -1)
1255 shortName = shortName
1256 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1258 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1261 Console.debug("lastSaveSuccessful=" + lastSaveSuccessful);
1262 if (lastSaveSuccessful)
1264 this.getViewport().setSavedUpToDate(true);
1267 statusBar.setText(MessageManager.formatMessage(
1268 "label.successfully_saved_to_file_in_format", new Object[]
1274 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1275 Runnable cancelAction = new Runnable()
1280 lastSaveSuccessful = false;
1283 Runnable outputAction = new Runnable()
1288 // todo defer this to inside formatSequences (or later)
1289 AlignmentExportData exportData = viewport
1290 .getAlignExportData(options);
1291 String output = new FormatAdapter(alignPanel, options)
1292 .formatSequences(format, exportData.getAlignment(),
1293 exportData.getOmitHidden(),
1294 exportData.getStartEndPostions(),
1295 viewport.getAlignment().getHiddenColumns());
1298 lastSaveSuccessful = false;
1302 // create backupfiles object and get new temp filename destination
1303 boolean doBackup = BackupFiles.getEnabled();
1304 BackupFiles backupfiles = null;
1308 "ALIGNFRAME making backupfiles object for " + file);
1309 backupfiles = new BackupFiles(file);
1313 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1315 Console.trace("ALIGNFRAME setting PrintWriter");
1316 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1318 if (backupfiles != null)
1320 Console.trace("ALIGNFRAME about to write to temp file "
1321 + backupfiles.getTempFilePath());
1325 Console.trace("ALIGNFRAME about to close file");
1327 Console.trace("ALIGNFRAME closed file");
1328 AlignFrame.this.setTitle(file);
1329 statusBar.setText(MessageManager.formatMessage(
1330 "label.successfully_saved_to_file_in_format",
1332 { fileName, format.getName() }));
1333 lastSaveSuccessful = true;
1334 } catch (IOException e)
1336 lastSaveSuccessful = false;
1338 "ALIGNFRAME Something happened writing the temp file");
1339 Console.error(e.getMessage());
1340 Console.debug(Cache.getStackTraceString(e));
1341 } catch (Exception ex)
1343 lastSaveSuccessful = false;
1345 "ALIGNFRAME Something unexpected happened writing the temp file");
1346 Console.error(ex.getMessage());
1347 Console.debug(Cache.getStackTraceString(ex));
1352 backupfiles.setWriteSuccess(lastSaveSuccessful);
1353 Console.debug("ALIGNFRAME writing temp file was "
1354 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1355 // do the backup file roll and rename the temp file to actual file
1357 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1358 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1360 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1361 + (lastSaveSuccessful ? "" : "un")
1365 Console.debug("lastSaveSuccessful=" + lastSaveSuccessful);
1366 if (lastSaveSuccessful)
1368 AlignFrame.this.getViewport().setSavedUpToDate(true);
1375 * show dialog with export options if applicable; else just do it
1377 if (AlignExportOptions.isNeeded(viewport, format))
1379 AlignExportOptions choices = new AlignExportOptions(
1380 alignPanel.getAlignViewport(), format, options);
1381 choices.setResponseAction(0, outputAction);
1382 choices.setResponseAction(1, cancelAction);
1383 choices.showDialog();
1392 * Outputs the alignment to textbox in the requested format, if necessary
1393 * first prompting the user for whether to include hidden regions or
1396 * @param fileFormatName
1399 protected void outputText_actionPerformed(String fileFormatName)
1401 FileFormatI fileFormat = FileFormats.getInstance()
1402 .forName(fileFormatName);
1403 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1404 Runnable outputAction = new Runnable()
1409 // todo defer this to inside formatSequences (or later)
1410 AlignmentExportData exportData = viewport
1411 .getAlignExportData(options);
1412 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1413 cap.setForInput(null);
1416 FileFormatI format = fileFormat;
1417 cap.setText(new FormatAdapter(alignPanel, options)
1418 .formatSequences(format, exportData.getAlignment(),
1419 exportData.getOmitHidden(),
1420 exportData.getStartEndPostions(),
1421 viewport.getAlignment().getHiddenColumns()));
1422 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1423 "label.alignment_output_command", new Object[]
1424 { fileFormat.getName() }), 600, 500);
1425 } catch (OutOfMemoryError oom)
1427 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1435 * show dialog with export options if applicable; else just do it
1437 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1439 AlignExportOptions choices = new AlignExportOptions(
1440 alignPanel.getAlignViewport(), fileFormat, options);
1441 choices.setResponseAction(0, outputAction);
1442 choices.showDialog();
1457 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1459 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1460 htmlSVG.exportHTML(null);
1464 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1466 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1467 bjs.exportHTML(null);
1470 public void createImageMap(File file, String image)
1472 alignPanel.makePNGImageMap(file, image);
1476 * Creates a PNG image of the alignment and writes it to the given file. If
1477 * the file is null, the user is prompted to choose a file.
1482 public void createPNG(File f)
1484 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1488 * Creates an EPS image of the alignment and writes it to the given file. If
1489 * the file is null, the user is prompted to choose a file.
1494 public void createEPS(File f)
1496 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1500 * Creates an SVG image of the alignment and writes it to the given file. If
1501 * the file is null, the user is prompted to choose a file.
1506 public void createSVG(File f)
1508 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1512 public void pageSetup_actionPerformed(ActionEvent e)
1514 PrinterJob printJob = PrinterJob.getPrinterJob();
1515 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1525 public void printMenuItem_actionPerformed(ActionEvent e)
1527 // Putting in a thread avoids Swing painting problems
1528 PrintThread thread = new PrintThread(alignPanel);
1533 public void exportFeatures_actionPerformed(ActionEvent e)
1535 new AnnotationExporter(alignPanel).exportFeatures();
1539 public void exportAnnotations_actionPerformed(ActionEvent e)
1541 new AnnotationExporter(alignPanel).exportAnnotations();
1545 public void associatedData_actionPerformed(ActionEvent e)
1547 final JalviewFileChooser chooser = new JalviewFileChooser(
1548 Cache.getProperty("LAST_DIRECTORY"));
1549 chooser.setFileView(new JalviewFileView());
1550 String tooltip = MessageManager
1551 .getString("label.load_jalview_annotations");
1552 chooser.setDialogTitle(tooltip);
1553 chooser.setToolTipText(tooltip);
1554 chooser.setResponseHandler(0, new Runnable()
1559 String choice = chooser.getSelectedFile().getPath();
1560 Cache.setProperty("LAST_DIRECTORY", choice);
1561 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1565 chooser.showOpenDialog(this);
1569 * Close the current view or all views in the alignment frame. If the frame
1570 * only contains one view then the alignment will be removed from memory.
1572 * @param closeAllTabs
1575 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1577 if (alignPanels != null && alignPanels.size() < 2)
1579 closeAllTabs = true;
1584 if (alignPanels != null)
1588 if (this.isClosed())
1590 // really close all the windows - otherwise wait till
1591 // setClosed(true) is called
1592 for (int i = 0; i < alignPanels.size(); i++)
1594 AlignmentPanel ap = alignPanels.get(i);
1601 closeView(alignPanel);
1606 if (featureSettings != null && featureSettings.isOpen())
1608 featureSettings.close();
1609 featureSettings = null;
1612 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1613 * be called recursively, with the frame now in 'closed' state
1615 this.setClosed(true);
1617 } catch (Exception ex)
1619 ex.printStackTrace();
1624 * Close the specified panel and close up tabs appropriately.
1626 * @param panelToClose
1628 public void closeView(AlignmentPanel panelToClose)
1630 int index = tabbedPane.getSelectedIndex();
1631 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1632 alignPanels.remove(panelToClose);
1633 panelToClose.closePanel();
1634 panelToClose = null;
1636 tabbedPane.removeTabAt(closedindex);
1637 tabbedPane.validate();
1639 if (index > closedindex || index == tabbedPane.getTabCount())
1641 // modify currently selected tab index if necessary.
1645 this.tabSelectionChanged(index);
1651 void updateEditMenuBar()
1654 if (viewport.getHistoryList().size() > 0)
1656 undoMenuItem.setEnabled(true);
1657 CommandI command = viewport.getHistoryList().peek();
1658 undoMenuItem.setText(MessageManager
1659 .formatMessage("label.undo_command", new Object[]
1660 { command.getDescription() }));
1664 undoMenuItem.setEnabled(false);
1665 undoMenuItem.setText(MessageManager.getString("action.undo"));
1668 if (viewport.getRedoList().size() > 0)
1670 redoMenuItem.setEnabled(true);
1672 CommandI command = viewport.getRedoList().peek();
1673 redoMenuItem.setText(MessageManager
1674 .formatMessage("label.redo_command", new Object[]
1675 { command.getDescription() }));
1679 redoMenuItem.setEnabled(false);
1680 redoMenuItem.setText(MessageManager.getString("action.redo"));
1685 public void addHistoryItem(CommandI command)
1687 if (command.getSize() > 0)
1689 viewport.addToHistoryList(command);
1690 viewport.clearRedoList();
1691 updateEditMenuBar();
1692 viewport.updateHiddenColumns();
1693 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1694 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1695 // viewport.getColumnSelection()
1696 // .getHiddenColumns().size() > 0);
1702 * @return alignment objects for all views
1704 AlignmentI[] getViewAlignments()
1706 if (alignPanels != null)
1708 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1710 for (AlignmentPanel ap : alignPanels)
1712 als[i++] = ap.av.getAlignment();
1716 if (viewport != null)
1718 return new AlignmentI[] { viewport.getAlignment() };
1730 protected void undoMenuItem_actionPerformed(ActionEvent e)
1732 if (viewport.getHistoryList().isEmpty())
1736 CommandI command = viewport.getHistoryList().pop();
1737 viewport.addToRedoList(command);
1738 command.undoCommand(getViewAlignments());
1740 AlignmentViewport originalSource = getOriginatingSource(command);
1741 updateEditMenuBar();
1743 if (originalSource != null)
1745 if (originalSource != viewport)
1748 "Implementation worry: mismatch of viewport origin for undo");
1750 originalSource.updateHiddenColumns();
1751 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1753 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1754 // viewport.getColumnSelection()
1755 // .getHiddenColumns().size() > 0);
1756 originalSource.firePropertyChange("alignment", null,
1757 originalSource.getAlignment().getSequences());
1768 protected void redoMenuItem_actionPerformed(ActionEvent e)
1770 if (viewport.getRedoList().size() < 1)
1775 CommandI command = viewport.getRedoList().pop();
1776 viewport.addToHistoryList(command);
1777 command.doCommand(getViewAlignments());
1779 AlignmentViewport originalSource = getOriginatingSource(command);
1780 updateEditMenuBar();
1782 if (originalSource != null)
1785 if (originalSource != viewport)
1788 "Implementation worry: mismatch of viewport origin for redo");
1790 originalSource.updateHiddenColumns();
1791 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1793 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1794 // viewport.getColumnSelection()
1795 // .getHiddenColumns().size() > 0);
1796 originalSource.firePropertyChange("alignment", null,
1797 originalSource.getAlignment().getSequences());
1801 AlignmentViewport getOriginatingSource(CommandI command)
1803 AlignmentViewport originalSource = null;
1804 // For sequence removal and addition, we need to fire
1805 // the property change event FROM the viewport where the
1806 // original alignment was altered
1807 AlignmentI al = null;
1808 if (command instanceof EditCommand)
1810 EditCommand editCommand = (EditCommand) command;
1811 al = editCommand.getAlignment();
1812 List<Component> comps = PaintRefresher.components
1813 .get(viewport.getSequenceSetId());
1815 for (Component comp : comps)
1817 if (comp instanceof AlignmentPanel)
1819 if (al == ((AlignmentPanel) comp).av.getAlignment())
1821 originalSource = ((AlignmentPanel) comp).av;
1828 if (originalSource == null)
1830 // The original view is closed, we must validate
1831 // the current view against the closed view first
1834 PaintRefresher.validateSequences(al, viewport.getAlignment());
1837 originalSource = viewport;
1840 return originalSource;
1844 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1845 * or the sequence under cursor in keyboard mode
1850 public void moveSelectedSequences(boolean up)
1852 SequenceGroup sg = viewport.getSelectionGroup();
1856 if (viewport.cursorMode)
1858 sg = new SequenceGroup();
1859 sg.addSequence(viewport.getAlignment().getSequenceAt(
1860 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1868 if (sg.getSize() < 1)
1873 // TODO: JAL-3733 - add an event to the undo buffer for this !
1875 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1876 viewport.getHiddenRepSequences(), up);
1877 alignPanel.paintAlignment(true, false);
1880 synchronized void slideSequences(boolean right, int size)
1882 List<SequenceI> sg = new ArrayList<>();
1883 if (viewport.cursorMode)
1885 sg.add(viewport.getAlignment()
1886 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1888 else if (viewport.getSelectionGroup() != null
1889 && viewport.getSelectionGroup().getSize() != viewport
1890 .getAlignment().getHeight())
1892 sg = viewport.getSelectionGroup()
1893 .getSequences(viewport.getHiddenRepSequences());
1901 List<SequenceI> invertGroup = new ArrayList<>();
1903 for (SequenceI seq : viewport.getAlignment().getSequences())
1905 if (!sg.contains(seq))
1907 invertGroup.add(seq);
1911 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1913 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1914 for (int i = 0; i < invertGroup.size(); i++)
1916 seqs2[i] = invertGroup.get(i);
1919 SlideSequencesCommand ssc;
1922 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1923 viewport.getGapCharacter());
1927 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1928 viewport.getGapCharacter());
1931 int groupAdjustment = 0;
1932 if (ssc.getGapsInsertedBegin() && right)
1934 if (viewport.cursorMode)
1936 alignPanel.getSeqPanel().moveCursor(size, 0);
1940 groupAdjustment = size;
1943 else if (!ssc.getGapsInsertedBegin() && !right)
1945 if (viewport.cursorMode)
1947 alignPanel.getSeqPanel().moveCursor(-size, 0);
1951 groupAdjustment = -size;
1955 if (groupAdjustment != 0)
1957 viewport.getSelectionGroup().setStartRes(
1958 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1959 viewport.getSelectionGroup().setEndRes(
1960 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1964 * just extend the last slide command if compatible; but not if in
1965 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1967 boolean appendHistoryItem = false;
1968 Deque<CommandI> historyList = viewport.getHistoryList();
1969 boolean inSplitFrame = getSplitViewContainer() != null;
1970 if (!inSplitFrame && historyList != null && historyList.size() > 0
1971 && historyList.peek() instanceof SlideSequencesCommand)
1973 appendHistoryItem = ssc.appendSlideCommand(
1974 (SlideSequencesCommand) historyList.peek());
1977 if (!appendHistoryItem)
1979 addHistoryItem(ssc);
1992 protected void copy_actionPerformed()
1994 if (viewport.getSelectionGroup() == null)
1998 // TODO: preserve the ordering of displayed alignment annotation in any
1999 // internal paste (particularly sequence associated annotation)
2000 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2001 String[] omitHidden = null;
2003 if (viewport.hasHiddenColumns())
2005 omitHidden = viewport.getViewAsString(true);
2008 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2009 seqs, omitHidden, null);
2011 StringSelection ss = new StringSelection(output);
2015 jalview.gui.Desktop.internalCopy = true;
2016 // Its really worth setting the clipboard contents
2017 // to empty before setting the large StringSelection!!
2018 Toolkit.getDefaultToolkit().getSystemClipboard()
2019 .setContents(new StringSelection(""), null);
2021 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2023 } catch (OutOfMemoryError er)
2025 new OOMWarning("copying region", er);
2029 HiddenColumns hiddenColumns = null;
2030 if (viewport.hasHiddenColumns())
2032 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2033 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2035 // create new HiddenColumns object with copy of hidden regions
2036 // between startRes and endRes, offset by startRes
2037 hiddenColumns = new HiddenColumns(
2038 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2039 hiddenCutoff, hiddenOffset);
2042 Desktop.jalviewClipboard = new Object[] { seqs,
2043 viewport.getAlignment().getDataset(), hiddenColumns };
2044 setStatus(MessageManager.formatMessage(
2045 "label.copied_sequences_to_clipboard", new Object[]
2046 { Integer.valueOf(seqs.length).toString() }));
2056 protected void pasteNew_actionPerformed(ActionEvent e)
2068 protected void pasteThis_actionPerformed(ActionEvent e)
2074 * Paste contents of Jalview clipboard
2076 * @param newAlignment
2077 * true to paste to a new alignment, otherwise add to this.
2079 void paste(boolean newAlignment)
2081 boolean externalPaste = true;
2084 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2085 Transferable contents = c.getContents(this);
2087 if (contents == null)
2096 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2097 if (str.length() < 1)
2102 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2104 } catch (OutOfMemoryError er)
2106 new OOMWarning("Out of memory pasting sequences!!", er);
2110 SequenceI[] sequences;
2111 boolean annotationAdded = false;
2112 AlignmentI alignment = null;
2114 if (Desktop.jalviewClipboard != null)
2116 // The clipboard was filled from within Jalview, we must use the
2118 // And dataset from the copied alignment
2119 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2120 // be doubly sure that we create *new* sequence objects.
2121 sequences = new SequenceI[newseq.length];
2122 for (int i = 0; i < newseq.length; i++)
2124 sequences[i] = new Sequence(newseq[i]);
2126 alignment = new Alignment(sequences);
2127 externalPaste = false;
2131 // parse the clipboard as an alignment.
2132 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2134 sequences = alignment.getSequencesArray();
2138 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2144 if (Desktop.jalviewClipboard != null)
2146 // dataset is inherited
2147 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2151 // new dataset is constructed
2152 alignment.setDataset(null);
2154 alwidth = alignment.getWidth() + 1;
2158 AlignmentI pastedal = alignment; // preserve pasted alignment object
2159 // Add pasted sequences and dataset into existing alignment.
2160 alignment = viewport.getAlignment();
2161 alwidth = alignment.getWidth() + 1;
2162 // decide if we need to import sequences from an existing dataset
2163 boolean importDs = Desktop.jalviewClipboard != null
2164 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2165 // importDs==true instructs us to copy over new dataset sequences from
2166 // an existing alignment
2167 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2169 // minimum dataset set
2171 for (int i = 0; i < sequences.length; i++)
2175 newDs.addElement(null);
2177 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2179 if (importDs && ds != null)
2181 if (!newDs.contains(ds))
2183 newDs.setElementAt(ds, i);
2184 ds = new Sequence(ds);
2185 // update with new dataset sequence
2186 sequences[i].setDatasetSequence(ds);
2190 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2195 // copy and derive new dataset sequence
2196 sequences[i] = sequences[i].deriveSequence();
2197 alignment.getDataset()
2198 .addSequence(sequences[i].getDatasetSequence());
2199 // TODO: avoid creation of duplicate dataset sequences with a
2200 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2202 alignment.addSequence(sequences[i]); // merges dataset
2206 newDs.clear(); // tidy up
2208 if (alignment.getAlignmentAnnotation() != null)
2210 for (AlignmentAnnotation alan : alignment
2211 .getAlignmentAnnotation())
2213 if (alan.graphGroup > fgroup)
2215 fgroup = alan.graphGroup;
2219 if (pastedal.getAlignmentAnnotation() != null)
2221 // Add any annotation attached to alignment.
2222 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2223 for (int i = 0; i < alann.length; i++)
2225 annotationAdded = true;
2226 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2228 AlignmentAnnotation newann = new AlignmentAnnotation(
2230 if (newann.graphGroup > -1)
2232 if (newGraphGroups.size() <= newann.graphGroup
2233 || newGraphGroups.get(newann.graphGroup) == null)
2235 for (int q = newGraphGroups
2236 .size(); q <= newann.graphGroup; q++)
2238 newGraphGroups.add(q, null);
2240 newGraphGroups.set(newann.graphGroup,
2241 Integer.valueOf(++fgroup));
2243 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2247 newann.padAnnotation(alwidth);
2248 alignment.addAnnotation(newann);
2258 addHistoryItem(new EditCommand(
2259 MessageManager.getString("label.add_sequences"),
2260 Action.PASTE, sequences, 0, alignment.getWidth(),
2263 // Add any annotations attached to sequences
2264 for (int i = 0; i < sequences.length; i++)
2266 if (sequences[i].getAnnotation() != null)
2268 AlignmentAnnotation newann;
2269 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2271 annotationAdded = true;
2272 newann = sequences[i].getAnnotation()[a];
2273 newann.adjustForAlignment();
2274 newann.padAnnotation(alwidth);
2275 if (newann.graphGroup > -1)
2277 if (newann.graphGroup > -1)
2279 if (newGraphGroups.size() <= newann.graphGroup
2280 || newGraphGroups.get(newann.graphGroup) == null)
2282 for (int q = newGraphGroups
2283 .size(); q <= newann.graphGroup; q++)
2285 newGraphGroups.add(q, null);
2287 newGraphGroups.set(newann.graphGroup,
2288 Integer.valueOf(++fgroup));
2290 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2294 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2298 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2306 // propagate alignment changed.
2307 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2308 if (annotationAdded)
2310 // Duplicate sequence annotation in all views.
2311 AlignmentI[] alview = this.getViewAlignments();
2312 for (int i = 0; i < sequences.length; i++)
2314 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2319 for (int avnum = 0; avnum < alview.length; avnum++)
2321 if (alview[avnum] != alignment)
2323 // duplicate in a view other than the one with input focus
2324 int avwidth = alview[avnum].getWidth() + 1;
2325 // this relies on sann being preserved after we
2326 // modify the sequence's annotation array for each duplication
2327 for (int a = 0; a < sann.length; a++)
2329 AlignmentAnnotation newann = new AlignmentAnnotation(
2331 sequences[i].addAlignmentAnnotation(newann);
2332 newann.padAnnotation(avwidth);
2333 alview[avnum].addAnnotation(newann); // annotation was
2334 // duplicated earlier
2335 // TODO JAL-1145 graphGroups are not updated for sequence
2336 // annotation added to several views. This may cause
2338 alview[avnum].setAnnotationIndex(newann, a);
2343 buildSortByAnnotationScoresMenu();
2345 viewport.firePropertyChange("alignment", null,
2346 alignment.getSequences());
2347 if (alignPanels != null)
2349 for (AlignmentPanel ap : alignPanels)
2351 ap.validateAnnotationDimensions(false);
2356 alignPanel.validateAnnotationDimensions(false);
2362 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2364 String newtitle = new String("Copied sequences");
2366 if (Desktop.jalviewClipboard != null
2367 && Desktop.jalviewClipboard[2] != null)
2369 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2370 af.viewport.setHiddenColumns(hc);
2373 // >>>This is a fix for the moment, until a better solution is
2375 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2376 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2377 .getFeatureRenderer());
2379 // TODO: maintain provenance of an alignment, rather than just make the
2380 // title a concatenation of operations.
2383 if (title.startsWith("Copied sequences"))
2389 newtitle = newtitle.concat("- from " + title);
2394 newtitle = new String("Pasted sequences");
2397 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2402 } catch (Exception ex)
2404 ex.printStackTrace();
2405 System.out.println("Exception whilst pasting: " + ex);
2406 // could be anything being pasted in here
2412 protected void expand_newalign(ActionEvent e)
2416 AlignmentI alignment = AlignmentUtils
2417 .expandContext(getViewport().getAlignment(), -1);
2418 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2420 String newtitle = new String("Flanking alignment");
2422 if (Desktop.jalviewClipboard != null
2423 && Desktop.jalviewClipboard[2] != null)
2425 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2426 af.viewport.setHiddenColumns(hc);
2429 // >>>This is a fix for the moment, until a better solution is
2431 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2432 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2433 .getFeatureRenderer());
2435 // TODO: maintain provenance of an alignment, rather than just make the
2436 // title a concatenation of operations.
2438 if (title.startsWith("Copied sequences"))
2444 newtitle = newtitle.concat("- from " + title);
2448 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2450 } catch (Exception ex)
2452 ex.printStackTrace();
2453 System.out.println("Exception whilst pasting: " + ex);
2454 // could be anything being pasted in here
2455 } catch (OutOfMemoryError oom)
2457 new OOMWarning("Viewing flanking region of alignment", oom);
2462 * Action Cut (delete and copy) the selected region
2465 protected void cut_actionPerformed()
2467 copy_actionPerformed();
2468 delete_actionPerformed();
2472 * Performs menu option to Delete the currently selected region
2475 protected void delete_actionPerformed()
2478 SequenceGroup sg = viewport.getSelectionGroup();
2484 Runnable okAction = new Runnable()
2489 SequenceI[] cut = sg.getSequences()
2490 .toArray(new SequenceI[sg.getSize()]);
2492 addHistoryItem(new EditCommand(
2493 MessageManager.getString("label.cut_sequences"), Action.CUT,
2494 cut, sg.getStartRes(),
2495 sg.getEndRes() - sg.getStartRes() + 1,
2496 viewport.getAlignment()));
2498 viewport.setSelectionGroup(null);
2499 viewport.sendSelection();
2500 viewport.getAlignment().deleteGroup(sg);
2502 viewport.firePropertyChange("alignment", null,
2503 viewport.getAlignment().getSequences());
2504 if (viewport.getAlignment().getHeight() < 1)
2508 AlignFrame.this.setClosed(true);
2509 } catch (Exception ex)
2517 * If the cut affects all sequences, prompt for confirmation
2519 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2521 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2522 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2523 if (wholeHeight && wholeWidth)
2525 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2526 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2527 Object[] options = new Object[] {
2528 MessageManager.getString("action.ok"),
2529 MessageManager.getString("action.cancel") };
2530 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2531 MessageManager.getString("label.delete_all"),
2532 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2533 options, options[0]);
2548 protected void deleteGroups_actionPerformed(ActionEvent e)
2550 if (avc.deleteGroups())
2552 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2553 alignPanel.updateAnnotation();
2554 alignPanel.paintAlignment(true, true);
2565 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2567 SequenceGroup sg = new SequenceGroup(
2568 viewport.getAlignment().getSequences());
2570 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2571 viewport.setSelectionGroup(sg);
2572 viewport.isSelectionGroupChanged(true);
2573 viewport.sendSelection();
2574 // JAL-2034 - should delegate to
2575 // alignPanel to decide if overview needs
2577 alignPanel.paintAlignment(false, false);
2578 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2588 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2590 if (viewport.cursorMode)
2592 alignPanel.getSeqPanel().keyboardNo1 = null;
2593 alignPanel.getSeqPanel().keyboardNo2 = null;
2595 viewport.setSelectionGroup(null);
2596 viewport.getColumnSelection().clear();
2597 viewport.setSearchResults(null);
2598 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2599 // JAL-2034 - should delegate to
2600 // alignPanel to decide if overview needs
2602 alignPanel.paintAlignment(false, false);
2603 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2604 viewport.sendSelection();
2614 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2616 SequenceGroup sg = viewport.getSelectionGroup();
2620 selectAllSequenceMenuItem_actionPerformed(null);
2625 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2627 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2629 // JAL-2034 - should delegate to
2630 // alignPanel to decide if overview needs
2633 alignPanel.paintAlignment(true, false);
2634 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2635 viewport.sendSelection();
2639 public void invertColSel_actionPerformed(ActionEvent e)
2641 viewport.invertColumnSelection();
2642 alignPanel.paintAlignment(true, false);
2643 viewport.sendSelection();
2653 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2655 trimAlignment(true);
2665 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2667 trimAlignment(false);
2670 void trimAlignment(boolean trimLeft)
2672 ColumnSelection colSel = viewport.getColumnSelection();
2675 if (!colSel.isEmpty())
2679 column = colSel.getMin();
2683 column = colSel.getMax();
2687 if (viewport.getSelectionGroup() != null)
2689 seqs = viewport.getSelectionGroup()
2690 .getSequencesAsArray(viewport.getHiddenRepSequences());
2694 seqs = viewport.getAlignment().getSequencesArray();
2697 TrimRegionCommand trimRegion;
2700 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2701 column, viewport.getAlignment());
2702 viewport.getRanges().setStartRes(0);
2706 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2707 column, viewport.getAlignment());
2710 setStatus(MessageManager.formatMessage("label.removed_columns",
2712 { Integer.valueOf(trimRegion.getSize()).toString() }));
2714 addHistoryItem(trimRegion);
2716 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2718 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2719 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2721 viewport.getAlignment().deleteGroup(sg);
2725 viewport.firePropertyChange("alignment", null,
2726 viewport.getAlignment().getSequences());
2737 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2739 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2742 if (viewport.getSelectionGroup() != null)
2744 seqs = viewport.getSelectionGroup()
2745 .getSequencesAsArray(viewport.getHiddenRepSequences());
2746 start = viewport.getSelectionGroup().getStartRes();
2747 end = viewport.getSelectionGroup().getEndRes();
2751 seqs = viewport.getAlignment().getSequencesArray();
2754 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2755 "Remove Gapped Columns", seqs, start, end,
2756 viewport.getAlignment());
2758 addHistoryItem(removeGapCols);
2760 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2762 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2764 // This is to maintain viewport position on first residue
2765 // of first sequence
2766 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2767 ViewportRanges ranges = viewport.getRanges();
2768 int startRes = seq.findPosition(ranges.getStartRes());
2769 // ShiftList shifts;
2770 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2771 // edit.alColumnChanges=shifts.getInverse();
2772 // if (viewport.hasHiddenColumns)
2773 // viewport.getColumnSelection().compensateForEdits(shifts);
2774 ranges.setStartRes(seq.findIndex(startRes) - 1);
2775 viewport.firePropertyChange("alignment", null,
2776 viewport.getAlignment().getSequences());
2787 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2789 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2792 if (viewport.getSelectionGroup() != null)
2794 seqs = viewport.getSelectionGroup()
2795 .getSequencesAsArray(viewport.getHiddenRepSequences());
2796 start = viewport.getSelectionGroup().getStartRes();
2797 end = viewport.getSelectionGroup().getEndRes();
2801 seqs = viewport.getAlignment().getSequencesArray();
2804 // This is to maintain viewport position on first residue
2805 // of first sequence
2806 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2807 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2809 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2810 viewport.getAlignment()));
2812 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2814 viewport.firePropertyChange("alignment", null,
2815 viewport.getAlignment().getSequences());
2826 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2828 viewport.setPadGaps(padGapsMenuitem.isSelected());
2829 viewport.firePropertyChange("alignment", null,
2830 viewport.getAlignment().getSequences());
2834 * Opens a Finder dialog
2839 public void findMenuItem_actionPerformed(ActionEvent e)
2841 new Finder(alignPanel, false, null);
2845 * Create a new view of the current alignment.
2848 public void newView_actionPerformed(ActionEvent e)
2850 newView(null, true);
2854 * Creates and shows a new view of the current alignment.
2857 * title of newly created view; if null, one will be generated
2858 * @param copyAnnotation
2859 * if true then duplicate all annnotation, groups and settings
2860 * @return new alignment panel, already displayed.
2862 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2865 * Create a new AlignmentPanel (with its own, new Viewport)
2867 AlignmentPanel newap = new jalview.project.Jalview2XML()
2868 .copyAlignPanel(alignPanel);
2869 if (!copyAnnotation)
2872 * remove all groups and annotation except for the automatic stuff
2874 newap.av.getAlignment().deleteAllGroups();
2875 newap.av.getAlignment().deleteAllAnnotations(false);
2878 newap.av.setGatherViewsHere(false);
2880 if (viewport.getViewName() == null)
2882 viewport.setViewName(
2883 MessageManager.getString("label.view_name_original"));
2887 * Views share the same edits undo and redo stacks
2889 newap.av.setHistoryList(viewport.getHistoryList());
2890 newap.av.setRedoList(viewport.getRedoList());
2893 * copy any visualisation settings that are not saved in the project
2895 newap.av.setColourAppliesToAllGroups(
2896 viewport.getColourAppliesToAllGroups());
2899 * Views share the same mappings; need to deregister any new mappings
2900 * created by copyAlignPanel, and register the new reference to the shared
2903 newap.av.replaceMappings(viewport.getAlignment());
2906 * start up cDNA consensus (if applicable) now mappings are in place
2908 if (newap.av.initComplementConsensus())
2910 newap.refresh(true); // adjust layout of annotations
2913 newap.av.setViewName(getNewViewName(viewTitle));
2915 addAlignmentPanel(newap, true);
2916 newap.alignmentChanged();
2918 if (alignPanels.size() == 2)
2920 viewport.setGatherViewsHere(true);
2922 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2927 * Make a new name for the view, ensuring it is unique within the current
2928 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2929 * these now use viewId. Unique view names are still desirable for usability.)
2934 protected String getNewViewName(String viewTitle)
2936 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2937 boolean addFirstIndex = false;
2938 if (viewTitle == null || viewTitle.trim().length() == 0)
2940 viewTitle = MessageManager.getString("action.view");
2941 addFirstIndex = true;
2945 index = 1;// we count from 1 if given a specific name
2947 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2949 List<Component> comps = PaintRefresher.components
2950 .get(viewport.getSequenceSetId());
2952 List<String> existingNames = getExistingViewNames(comps);
2954 while (existingNames.contains(newViewName))
2956 newViewName = viewTitle + " " + (++index);
2962 * Returns a list of distinct view names found in the given list of
2963 * components. View names are held on the viewport of an AlignmentPanel.
2968 protected List<String> getExistingViewNames(List<Component> comps)
2970 List<String> existingNames = new ArrayList<>();
2971 for (Component comp : comps)
2973 if (comp instanceof AlignmentPanel)
2975 AlignmentPanel ap = (AlignmentPanel) comp;
2976 if (!existingNames.contains(ap.av.getViewName()))
2978 existingNames.add(ap.av.getViewName());
2982 return existingNames;
2986 * Explode tabbed views into separate windows.
2989 public void expandViews_actionPerformed(ActionEvent e)
2991 Desktop.explodeViews(this);
2995 * Gather views in separate windows back into a tabbed presentation.
2998 public void gatherViews_actionPerformed(ActionEvent e)
3000 Desktop.instance.gatherViews(this);
3010 public void font_actionPerformed(ActionEvent e)
3012 new FontChooser(alignPanel);
3022 protected void seqLimit_actionPerformed(ActionEvent e)
3024 viewport.setShowJVSuffix(seqLimits.isSelected());
3026 alignPanel.getIdPanel().getIdCanvas()
3027 .setPreferredSize(alignPanel.calculateIdWidth());
3028 alignPanel.paintAlignment(true, false);
3032 public void idRightAlign_actionPerformed(ActionEvent e)
3034 viewport.setRightAlignIds(idRightAlign.isSelected());
3035 alignPanel.paintAlignment(false, false);
3039 public void centreColumnLabels_actionPerformed(ActionEvent e)
3041 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3042 alignPanel.paintAlignment(false, false);
3048 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3051 protected void followHighlight_actionPerformed()
3054 * Set the 'follow' flag on the Viewport (and scroll to position if now
3057 final boolean state = this.followHighlightMenuItem.getState();
3058 viewport.setFollowHighlight(state);
3061 alignPanel.scrollToPosition(viewport.getSearchResults());
3072 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3074 viewport.setColourText(colourTextMenuItem.isSelected());
3075 alignPanel.paintAlignment(false, false);
3085 public void wrapMenuItem_actionPerformed(ActionEvent e)
3087 scaleAbove.setVisible(wrapMenuItem.isSelected());
3088 scaleLeft.setVisible(wrapMenuItem.isSelected());
3089 scaleRight.setVisible(wrapMenuItem.isSelected());
3090 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3091 alignPanel.updateLayout();
3095 public void showAllSeqs_actionPerformed(ActionEvent e)
3097 viewport.showAllHiddenSeqs();
3101 public void showAllColumns_actionPerformed(ActionEvent e)
3103 viewport.showAllHiddenColumns();
3104 alignPanel.paintAlignment(true, true);
3105 viewport.sendSelection();
3109 public void hideSelSequences_actionPerformed(ActionEvent e)
3111 viewport.hideAllSelectedSeqs();
3115 * called by key handler and the hide all/show all menu items
3120 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3123 boolean hide = false;
3124 SequenceGroup sg = viewport.getSelectionGroup();
3125 if (!toggleSeqs && !toggleCols)
3127 // Hide everything by the current selection - this is a hack - we do the
3128 // invert and then hide
3129 // first check that there will be visible columns after the invert.
3130 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3131 && sg.getStartRes() <= sg.getEndRes()))
3133 // now invert the sequence set, if required - empty selection implies
3134 // that no hiding is required.
3137 invertSequenceMenuItem_actionPerformed(null);
3138 sg = viewport.getSelectionGroup();
3142 viewport.expandColSelection(sg, true);
3143 // finally invert the column selection and get the new sequence
3145 invertColSel_actionPerformed(null);
3152 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3154 hideSelSequences_actionPerformed(null);
3157 else if (!(toggleCols && viewport.hasSelectedColumns()))
3159 showAllSeqs_actionPerformed(null);
3165 if (viewport.hasSelectedColumns())
3167 hideSelColumns_actionPerformed(null);
3170 viewport.setSelectionGroup(sg);
3175 showAllColumns_actionPerformed(null);
3184 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3185 * event.ActionEvent)
3188 public void hideAllButSelection_actionPerformed(ActionEvent e)
3190 toggleHiddenRegions(false, false);
3191 viewport.sendSelection();
3198 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3202 public void hideAllSelection_actionPerformed(ActionEvent e)
3204 SequenceGroup sg = viewport.getSelectionGroup();
3205 viewport.expandColSelection(sg, false);
3206 viewport.hideAllSelectedSeqs();
3207 viewport.hideSelectedColumns();
3208 alignPanel.updateLayout();
3209 alignPanel.paintAlignment(true, true);
3210 viewport.sendSelection();
3217 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3221 public void showAllhidden_actionPerformed(ActionEvent e)
3223 viewport.showAllHiddenColumns();
3224 viewport.showAllHiddenSeqs();
3225 alignPanel.paintAlignment(true, true);
3226 viewport.sendSelection();
3230 public void hideSelColumns_actionPerformed(ActionEvent e)
3232 viewport.hideSelectedColumns();
3233 alignPanel.updateLayout();
3234 alignPanel.paintAlignment(true, true);
3235 viewport.sendSelection();
3239 public void hiddenMarkers_actionPerformed(ActionEvent e)
3241 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3252 protected void scaleAbove_actionPerformed(ActionEvent e)
3254 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3255 alignPanel.updateLayout();
3256 alignPanel.paintAlignment(true, false);
3266 protected void scaleLeft_actionPerformed(ActionEvent e)
3268 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3269 alignPanel.updateLayout();
3270 alignPanel.paintAlignment(true, false);
3280 protected void scaleRight_actionPerformed(ActionEvent e)
3282 viewport.setScaleRightWrapped(scaleRight.isSelected());
3283 alignPanel.updateLayout();
3284 alignPanel.paintAlignment(true, false);
3294 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3296 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3297 alignPanel.paintAlignment(false, false);
3307 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3309 viewport.setShowText(viewTextMenuItem.isSelected());
3310 alignPanel.paintAlignment(false, false);
3320 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3322 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3323 alignPanel.paintAlignment(false, false);
3326 public FeatureSettings featureSettings;
3329 public FeatureSettingsControllerI getFeatureSettingsUI()
3331 return featureSettings;
3335 public void featureSettings_actionPerformed(ActionEvent e)
3337 showFeatureSettingsUI();
3341 public FeatureSettingsControllerI showFeatureSettingsUI()
3343 if (featureSettings != null)
3345 featureSettings.closeOldSettings();
3346 featureSettings = null;
3348 if (!showSeqFeatures.isSelected())
3350 // make sure features are actually displayed
3351 showSeqFeatures.setSelected(true);
3352 showSeqFeatures_actionPerformed(null);
3354 featureSettings = new FeatureSettings(this);
3355 return featureSettings;
3359 * Set or clear 'Show Sequence Features'
3365 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3367 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3368 alignPanel.paintAlignment(true, true);
3372 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3373 * the annotations panel as a whole.
3375 * The options to show/hide all annotations should be enabled when the panel
3376 * is shown, and disabled when the panel is hidden.
3381 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3383 final boolean setVisible = annotationPanelMenuItem.isSelected();
3384 viewport.setShowAnnotation(setVisible);
3385 this.showAllSeqAnnotations.setEnabled(setVisible);
3386 this.hideAllSeqAnnotations.setEnabled(setVisible);
3387 this.showAllAlAnnotations.setEnabled(setVisible);
3388 this.hideAllAlAnnotations.setEnabled(setVisible);
3389 alignPanel.updateLayout();
3393 public void alignmentProperties()
3396 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3399 String content = MessageManager.formatMessage("label.html_content",
3401 { contents.toString() });
3404 if (Platform.isJS())
3406 JLabel textLabel = new JLabel();
3407 textLabel.setText(content);
3408 textLabel.setBackground(Color.WHITE);
3410 pane = new JPanel(new BorderLayout());
3411 ((JPanel) pane).setOpaque(true);
3412 pane.setBackground(Color.WHITE);
3413 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3422 JEditorPane editPane = new JEditorPane("text/html", "");
3423 editPane.setEditable(false);
3424 editPane.setText(content);
3428 JInternalFrame frame = new JInternalFrame();
3430 frame.getContentPane().add(new JScrollPane(pane));
3432 Desktop.addInternalFrame(frame, MessageManager
3433 .formatMessage("label.alignment_properties", new Object[]
3434 { getTitle() }), 500, 400);
3444 public void overviewMenuItem_actionPerformed(ActionEvent e)
3446 if (alignPanel.overviewPanel != null)
3451 JInternalFrame frame = new JInternalFrame();
3452 final OverviewPanel overview = new OverviewPanel(alignPanel);
3453 frame.setContentPane(overview);
3454 Desktop.addInternalFrame(frame, MessageManager
3455 .formatMessage("label.overview_params", new Object[]
3456 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3459 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3460 frame.addInternalFrameListener(
3461 new javax.swing.event.InternalFrameAdapter()
3464 public void internalFrameClosed(
3465 javax.swing.event.InternalFrameEvent evt)
3468 alignPanel.setOverviewPanel(null);
3471 if (getKeyListeners().length > 0)
3473 frame.addKeyListener(getKeyListeners()[0]);
3476 alignPanel.setOverviewPanel(overview);
3480 public void textColour_actionPerformed()
3482 new TextColourChooser().chooseColour(alignPanel, null);
3486 * public void covariationColour_actionPerformed() {
3488 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3492 public void annotationColour_actionPerformed()
3494 new AnnotationColourChooser(viewport, alignPanel);
3498 public void annotationColumn_actionPerformed(ActionEvent e)
3500 new AnnotationColumnChooser(viewport, alignPanel);
3504 * Action on the user checking or unchecking the option to apply the selected
3505 * colour scheme to all groups. If unchecked, groups may have their own
3506 * independent colour schemes.
3511 public void applyToAllGroups_actionPerformed(boolean selected)
3513 viewport.setColourAppliesToAllGroups(selected);
3517 * Action on user selecting a colour from the colour menu
3520 * the name (not the menu item label!) of the colour scheme
3523 public void changeColour_actionPerformed(String name)
3526 * 'User Defined' opens a panel to configure or load a
3527 * user-defined colour scheme
3529 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3531 new UserDefinedColours(alignPanel);
3536 * otherwise set the chosen colour scheme (or null for 'None')
3538 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3539 viewport, viewport.getAlignment(),
3540 viewport.getHiddenRepSequences());
3545 * Actions on setting or changing the alignment colour scheme
3550 public void changeColour(ColourSchemeI cs)
3552 // TODO: pull up to controller method
3553 ColourMenuHelper.setColourSelected(colourMenu, cs);
3555 viewport.setGlobalColourScheme(cs);
3557 alignPanel.paintAlignment(true, true);
3561 * Show the PID threshold slider panel
3564 protected void modifyPID_actionPerformed()
3566 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3567 alignPanel.getViewName());
3568 SliderPanel.showPIDSlider();
3572 * Show the Conservation slider panel
3575 protected void modifyConservation_actionPerformed()
3577 SliderPanel.setConservationSlider(alignPanel,
3578 viewport.getResidueShading(), alignPanel.getViewName());
3579 SliderPanel.showConservationSlider();
3583 * Action on selecting or deselecting (Colour) By Conservation
3586 public void conservationMenuItem_actionPerformed(boolean selected)
3588 modifyConservation.setEnabled(selected);
3589 viewport.setConservationSelected(selected);
3590 viewport.getResidueShading().setConservationApplied(selected);
3592 changeColour(viewport.getGlobalColourScheme());
3595 modifyConservation_actionPerformed();
3599 SliderPanel.hideConservationSlider();
3604 * Action on selecting or deselecting (Colour) Above PID Threshold
3607 public void abovePIDThreshold_actionPerformed(boolean selected)
3609 modifyPID.setEnabled(selected);
3610 viewport.setAbovePIDThreshold(selected);
3613 viewport.getResidueShading().setThreshold(0,
3614 viewport.isIgnoreGapsConsensus());
3617 changeColour(viewport.getGlobalColourScheme());
3620 modifyPID_actionPerformed();
3624 SliderPanel.hidePIDSlider();
3635 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3637 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3638 AlignmentSorter.sortByPID(viewport.getAlignment(),
3639 viewport.getAlignment().getSequenceAt(0));
3640 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3641 viewport.getAlignment()));
3642 alignPanel.paintAlignment(true, false);
3652 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3654 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3655 AlignmentSorter.sortByID(viewport.getAlignment());
3657 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3658 alignPanel.paintAlignment(true, false);
3668 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3670 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3671 AlignmentSorter.sortByLength(viewport.getAlignment());
3672 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3673 viewport.getAlignment()));
3674 alignPanel.paintAlignment(true, false);
3684 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3686 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3687 AlignmentSorter.sortByGroup(viewport.getAlignment());
3688 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3689 viewport.getAlignment()));
3691 alignPanel.paintAlignment(true, false);
3701 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3703 new RedundancyPanel(alignPanel, this);
3713 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3715 if ((viewport.getSelectionGroup() == null)
3716 || (viewport.getSelectionGroup().getSize() < 2))
3718 JvOptionPane.showInternalMessageDialog(this,
3719 MessageManager.getString(
3720 "label.you_must_select_least_two_sequences"),
3721 MessageManager.getString("label.invalid_selection"),
3722 JvOptionPane.WARNING_MESSAGE);
3726 JInternalFrame frame = new JInternalFrame();
3727 frame.setContentPane(new PairwiseAlignPanel(viewport));
3728 Desktop.addInternalFrame(frame,
3729 MessageManager.getString("action.pairwise_alignment"), 600,
3735 public void autoCalculate_actionPerformed(ActionEvent e)
3737 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3738 if (viewport.autoCalculateConsensus)
3740 viewport.firePropertyChange("alignment", null,
3741 viewport.getAlignment().getSequences());
3746 public void sortByTreeOption_actionPerformed(ActionEvent e)
3748 viewport.sortByTree = sortByTree.isSelected();
3752 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3754 viewport.followSelection = listenToViewSelections.isSelected();
3758 * Constructs a tree panel and adds it to the desktop
3761 * tree type (NJ or AV)
3763 * name of score model used to compute the tree
3765 * parameters for the distance or similarity calculation
3767 void newTreePanel(String type, String modelName,
3768 SimilarityParamsI options)
3770 String frameTitle = "";
3773 boolean onSelection = false;
3774 if (viewport.getSelectionGroup() != null
3775 && viewport.getSelectionGroup().getSize() > 0)
3777 SequenceGroup sg = viewport.getSelectionGroup();
3779 /* Decide if the selection is a column region */
3780 for (SequenceI _s : sg.getSequences())
3782 if (_s.getLength() < sg.getEndRes())
3784 JvOptionPane.showMessageDialog(Desktop.desktop,
3785 MessageManager.getString(
3786 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3787 MessageManager.getString(
3788 "label.sequences_selection_not_aligned"),
3789 JvOptionPane.WARNING_MESSAGE);
3798 if (viewport.getAlignment().getHeight() < 2)
3804 tp = new TreePanel(alignPanel, type, modelName, options);
3805 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3807 frameTitle += " from ";
3809 if (viewport.getViewName() != null)
3811 frameTitle += viewport.getViewName() + " of ";
3814 frameTitle += this.title;
3816 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3827 public void addSortByOrderMenuItem(String title,
3828 final AlignmentOrder order)
3830 final JMenuItem item = new JMenuItem(MessageManager
3831 .formatMessage("action.by_title_param", new Object[]
3834 item.addActionListener(new java.awt.event.ActionListener()
3837 public void actionPerformed(ActionEvent e)
3839 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3841 // TODO: JBPNote - have to map order entries to curent SequenceI
3843 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3845 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3846 viewport.getAlignment()));
3848 alignPanel.paintAlignment(true, false);
3854 * Add a new sort by annotation score menu item
3857 * the menu to add the option to
3859 * the label used to retrieve scores for each sequence on the
3862 public void addSortByAnnotScoreMenuItem(JMenu sort,
3863 final String scoreLabel)
3865 final JMenuItem item = new JMenuItem(scoreLabel);
3867 item.addActionListener(new java.awt.event.ActionListener()
3870 public void actionPerformed(ActionEvent e)
3872 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3873 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3874 viewport.getAlignment());// ,viewport.getSelectionGroup());
3875 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3876 viewport.getAlignment()));
3877 alignPanel.paintAlignment(true, false);
3883 * last hash for alignment's annotation array - used to minimise cost of
3886 protected int _annotationScoreVectorHash;
3889 * search the alignment and rebuild the sort by annotation score submenu the
3890 * last alignment annotation vector hash is stored to minimize cost of
3891 * rebuilding in subsequence calls.
3895 public void buildSortByAnnotationScoresMenu()
3897 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3902 if (viewport.getAlignment().getAlignmentAnnotation()
3903 .hashCode() != _annotationScoreVectorHash)
3905 sortByAnnotScore.removeAll();
3906 // almost certainly a quicker way to do this - but we keep it simple
3907 Hashtable<String, String> scoreSorts = new Hashtable<>();
3908 AlignmentAnnotation aann[];
3909 for (SequenceI sqa : viewport.getAlignment().getSequences())
3911 aann = sqa.getAnnotation();
3912 for (int i = 0; aann != null && i < aann.length; i++)
3914 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3916 scoreSorts.put(aann[i].label, aann[i].label);
3920 Enumeration<String> labels = scoreSorts.keys();
3921 while (labels.hasMoreElements())
3923 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3925 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3928 _annotationScoreVectorHash = viewport.getAlignment()
3929 .getAlignmentAnnotation().hashCode();
3934 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3935 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3936 * call. Listeners are added to remove the menu item when the treePanel is
3937 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3941 public void buildTreeSortMenu()
3943 sortByTreeMenu.removeAll();
3945 List<Component> comps = PaintRefresher.components
3946 .get(viewport.getSequenceSetId());
3947 List<TreePanel> treePanels = new ArrayList<>();
3948 for (Component comp : comps)
3950 if (comp instanceof TreePanel)
3952 treePanels.add((TreePanel) comp);
3956 if (treePanels.size() < 1)
3958 sortByTreeMenu.setVisible(false);
3962 sortByTreeMenu.setVisible(true);
3964 for (final TreePanel tp : treePanels)
3966 final JMenuItem item = new JMenuItem(tp.getTitle());
3967 item.addActionListener(new java.awt.event.ActionListener()
3970 public void actionPerformed(ActionEvent e)
3972 tp.sortByTree_actionPerformed();
3973 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3978 sortByTreeMenu.add(item);
3982 public boolean sortBy(AlignmentOrder alorder, String undoname)
3984 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3985 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3986 if (undoname != null)
3988 addHistoryItem(new OrderCommand(undoname, oldOrder,
3989 viewport.getAlignment()));
3991 alignPanel.paintAlignment(true, false);
3996 * Work out whether the whole set of sequences or just the selected set will
3997 * be submitted for multiple alignment.
4000 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4002 // Now, check we have enough sequences
4003 AlignmentView msa = null;
4005 if ((viewport.getSelectionGroup() != null)
4006 && (viewport.getSelectionGroup().getSize() > 1))
4008 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4009 // some common interface!
4011 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4012 * SequenceI[sz = seqs.getSize(false)];
4014 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4015 * seqs.getSequenceAt(i); }
4017 msa = viewport.getAlignmentView(true);
4019 else if (viewport.getSelectionGroup() != null
4020 && viewport.getSelectionGroup().getSize() == 1)
4022 int option = JvOptionPane.showConfirmDialog(this,
4023 MessageManager.getString("warn.oneseq_msainput_selection"),
4024 MessageManager.getString("label.invalid_selection"),
4025 JvOptionPane.OK_CANCEL_OPTION);
4026 if (option == JvOptionPane.OK_OPTION)
4028 msa = viewport.getAlignmentView(false);
4033 msa = viewport.getAlignmentView(false);
4039 * Decides what is submitted to a secondary structure prediction service: the
4040 * first sequence in the alignment, or in the current selection, or, if the
4041 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4042 * region or the whole alignment. (where the first sequence in the set is the
4043 * one that the prediction will be for).
4045 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4047 AlignmentView seqs = null;
4049 if ((viewport.getSelectionGroup() != null)
4050 && (viewport.getSelectionGroup().getSize() > 0))
4052 seqs = viewport.getAlignmentView(true);
4056 seqs = viewport.getAlignmentView(false);
4058 // limit sequences - JBPNote in future - could spawn multiple prediction
4060 // TODO: viewport.getAlignment().isAligned is a global state - the local
4061 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4062 if (!viewport.getAlignment().isAligned(false))
4064 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4065 // TODO: if seqs.getSequences().length>1 then should really have warned
4079 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4081 // Pick the tree file
4082 JalviewFileChooser chooser = new JalviewFileChooser(
4083 Cache.getProperty("LAST_DIRECTORY"));
4084 chooser.setFileView(new JalviewFileView());
4085 chooser.setDialogTitle(
4086 MessageManager.getString("label.select_newick_like_tree_file"));
4087 chooser.setToolTipText(
4088 MessageManager.getString("label.load_tree_file"));
4090 chooser.setResponseHandler(0, new Runnable()
4095 String filePath = chooser.getSelectedFile().getPath();
4096 Cache.setProperty("LAST_DIRECTORY", filePath);
4097 NewickFile fin = null;
4100 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4101 DataSourceType.FILE));
4102 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4103 } catch (Exception ex)
4105 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4107 .getString("label.problem_reading_tree_file"),
4108 JvOptionPane.WARNING_MESSAGE);
4109 ex.printStackTrace();
4111 if (fin != null && fin.hasWarningMessage())
4113 JvOptionPane.showMessageDialog(Desktop.desktop,
4114 fin.getWarningMessage(),
4115 MessageManager.getString(
4116 "label.possible_problem_with_tree_file"),
4117 JvOptionPane.WARNING_MESSAGE);
4121 chooser.showOpenDialog(this);
4124 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4126 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4129 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4130 int h, int x, int y)
4132 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4136 * Add a treeviewer for the tree extracted from a Newick file object to the
4137 * current alignment view
4144 * Associated alignment input data (or null)
4153 * @return TreePanel handle
4155 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4156 AlignmentView input, int w, int h, int x, int y)
4158 TreePanel tp = null;
4164 if (nf.getTree() != null)
4166 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4172 tp.setLocation(x, y);
4175 Desktop.addInternalFrame(tp, treeTitle, w, h);
4177 } catch (Exception ex)
4179 ex.printStackTrace();
4185 private boolean buildingMenu = false;
4188 * Generates menu items and listener event actions for web service clients
4191 public void BuildWebServiceMenu()
4193 while (buildingMenu)
4197 System.err.println("Waiting for building menu to finish.");
4199 } catch (Exception e)
4203 final AlignFrame me = this;
4204 buildingMenu = true;
4205 new Thread(new Runnable()
4210 final List<JMenuItem> legacyItems = new ArrayList<>();
4213 // System.err.println("Building ws menu again "
4214 // + Thread.currentThread());
4215 // TODO: add support for context dependent disabling of services based
4217 // alignment and current selection
4218 // TODO: add additional serviceHandle parameter to specify abstract
4220 // class independently of AbstractName
4221 // TODO: add in rediscovery GUI function to restart discoverer
4222 // TODO: group services by location as well as function and/or
4224 // object broker mechanism.
4225 final Vector<JMenu> wsmenu = new Vector<>();
4226 final IProgressIndicator af = me;
4229 * do not i18n these strings - they are hard-coded in class
4230 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4231 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4233 final JMenu msawsmenu = new JMenu("Alignment");
4234 final JMenu secstrmenu = new JMenu(
4235 "Secondary Structure Prediction");
4236 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4237 final JMenu analymenu = new JMenu("Analysis");
4238 final JMenu dismenu = new JMenu("Protein Disorder");
4239 // JAL-940 - only show secondary structure prediction services from
4240 // the legacy server
4241 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4243 Discoverer.services != null && (Discoverer.services.size() > 0))
4245 // TODO: refactor to allow list of AbstractName/Handler bindings to
4247 // stored or retrieved from elsewhere
4248 // No MSAWS used any more:
4249 // Vector msaws = null; // (Vector)
4250 // Discoverer.services.get("MsaWS");
4251 Vector<ServiceHandle> secstrpr = Discoverer.services
4253 if (secstrpr != null)
4255 // Add any secondary structure prediction services
4256 for (int i = 0, j = secstrpr.size(); i < j; i++)
4258 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4259 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4260 .getServiceClient(sh);
4261 int p = secstrmenu.getItemCount();
4262 impl.attachWSMenuEntry(secstrmenu, me);
4263 int q = secstrmenu.getItemCount();
4264 for (int litm = p; litm < q; litm++)
4266 legacyItems.add(secstrmenu.getItem(litm));
4272 // Add all submenus in the order they should appear on the web
4274 wsmenu.add(msawsmenu);
4275 wsmenu.add(secstrmenu);
4276 wsmenu.add(dismenu);
4277 wsmenu.add(analymenu);
4278 // No search services yet
4279 // wsmenu.add(seqsrchmenu);
4281 javax.swing.SwingUtilities.invokeLater(new Runnable()
4288 webService.removeAll();
4289 // first, add discovered services onto the webservices menu
4290 if (wsmenu.size() > 0)
4292 for (int i = 0, j = wsmenu.size(); i < j; i++)
4294 webService.add(wsmenu.get(i));
4299 webService.add(me.webServiceNoServices);
4301 // TODO: move into separate menu builder class.
4303 // logic for 2.11.1.4 is
4304 // always look to see if there is a discover. if there isn't
4305 // we can't show any Jws2 services
4306 // if there are services available, show them - regardless of
4307 // the 'show JWS2 preference'
4308 // if the discoverer is running then say so
4309 // otherwise offer to trigger discovery if 'show JWS2' is not
4311 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4312 if (jws2servs != null)
4314 if (jws2servs.hasServices())
4316 jws2servs.attachWSMenuEntry(webService, me);
4317 for (Jws2Instance sv : jws2servs.getServices())
4319 if (sv.description.toLowerCase(Locale.ROOT)
4322 for (JMenuItem jmi : legacyItems)
4324 jmi.setVisible(false);
4330 if (jws2servs.isRunning())
4332 JMenuItem tm = new JMenuItem(
4333 "Still discovering JABA Services");
4334 tm.setEnabled(false);
4337 else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4339 JMenuItem enableJws2 = new JMenuItem(
4340 "Discover Web Services");
4341 enableJws2.setToolTipText(
4342 "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4343 enableJws2.setEnabled(true);
4344 enableJws2.addActionListener(new ActionListener()
4348 public void actionPerformed(ActionEvent e)
4350 // start service discoverer, but ignore preference
4351 Desktop.instance.startServiceDiscovery(false,
4355 webService.add(enableJws2);
4359 build_urlServiceMenu(me.webService);
4360 build_fetchdbmenu(webService);
4361 for (JMenu item : wsmenu)
4363 if (item.getItemCount() == 0)
4365 item.setEnabled(false);
4369 item.setEnabled(true);
4372 } catch (Exception e)
4375 "Exception during web service menu building process.",
4380 } catch (Exception e)
4383 buildingMenu = false;
4390 * construct any groupURL type service menu entries.
4394 protected void build_urlServiceMenu(JMenu webService)
4396 // TODO: remove this code when 2.7 is released
4397 // DEBUG - alignmentView
4399 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4400 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4402 * @Override public void actionPerformed(ActionEvent e) {
4403 * jalview.datamodel.AlignmentView
4404 * .testSelectionViews(af.viewport.getAlignment(),
4405 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4407 * }); webService.add(testAlView);
4409 // TODO: refactor to RestClient discoverer and merge menu entries for
4410 // rest-style services with other types of analysis/calculation service
4411 // SHmmr test client - still being implemented.
4412 // DEBUG - alignmentView
4414 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4417 client.attachWSMenuEntry(
4418 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4424 * Searches the alignment sequences for xRefs and builds the Show
4425 * Cross-References menu (formerly called Show Products), with database
4426 * sources for which cross-references are found (protein sources for a
4427 * nucleotide alignment and vice versa)
4429 * @return true if Show Cross-references menu should be enabled
4431 public boolean canShowProducts()
4433 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4434 AlignmentI dataset = viewport.getAlignment().getDataset();
4436 showProducts.removeAll();
4437 final boolean dna = viewport.getAlignment().isNucleotide();
4439 if (seqs == null || seqs.length == 0)
4441 // nothing to see here.
4445 boolean showp = false;
4448 List<String> ptypes = new CrossRef(seqs, dataset)
4449 .findXrefSourcesForSequences(dna);
4451 for (final String source : ptypes)
4454 final AlignFrame af = this;
4455 JMenuItem xtype = new JMenuItem(source);
4456 xtype.addActionListener(new ActionListener()
4459 public void actionPerformed(ActionEvent e)
4461 showProductsFor(af.viewport.getSequenceSelection(), dna,
4465 showProducts.add(xtype);
4467 showProducts.setVisible(showp);
4468 showProducts.setEnabled(showp);
4469 } catch (Exception e)
4472 "canShowProducts threw an exception - please report to help@jalview.org",
4480 * Finds and displays cross-references for the selected sequences (protein
4481 * products for nucleotide sequences, dna coding sequences for peptides).
4484 * the sequences to show cross-references for
4486 * true if from a nucleotide alignment (so showing proteins)
4488 * the database to show cross-references for
4490 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4491 final String source)
4493 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4498 * Construct and display a new frame containing the translation of this
4499 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4502 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4504 AlignmentI al = null;
4507 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4509 al = dna.translateCdna(codeTable);
4510 } catch (Exception ex)
4512 Console.error("Exception during translation. Please report this !",
4514 final String msg = MessageManager.getString(
4515 "label.error_when_translating_sequences_submit_bug_report");
4516 final String errorTitle = MessageManager
4517 .getString("label.implementation_error")
4518 + MessageManager.getString("label.translation_failed");
4519 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4520 JvOptionPane.ERROR_MESSAGE);
4523 if (al == null || al.getHeight() == 0)
4525 final String msg = MessageManager.getString(
4526 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4527 final String errorTitle = MessageManager
4528 .getString("label.translation_failed");
4529 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4530 JvOptionPane.WARNING_MESSAGE);
4534 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4535 af.setFileFormat(this.currentFileFormat);
4536 final String newTitle = MessageManager
4537 .formatMessage("label.translation_of_params", new Object[]
4538 { this.getTitle(), codeTable.getId() });
4539 af.setTitle(newTitle);
4540 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4542 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4543 viewport.openSplitFrame(af, new Alignment(seqs));
4547 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4554 * Set the file format
4558 public void setFileFormat(FileFormatI format)
4560 this.currentFileFormat = format;
4564 * Try to load a features file onto the alignment.
4567 * contents or path to retrieve file or a File object
4569 * access mode of file (see jalview.io.AlignFile)
4570 * @return true if features file was parsed correctly.
4572 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4575 return avc.parseFeaturesFile(file, sourceType,
4576 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4581 public void refreshFeatureUI(boolean enableIfNecessary)
4583 // note - currently this is only still here rather than in the controller
4584 // because of the featureSettings hard reference that is yet to be
4586 if (enableIfNecessary)
4588 viewport.setShowSequenceFeatures(true);
4589 showSeqFeatures.setSelected(true);
4595 public void dragEnter(DropTargetDragEvent evt)
4600 public void dragExit(DropTargetEvent evt)
4605 public void dragOver(DropTargetDragEvent evt)
4610 public void dropActionChanged(DropTargetDragEvent evt)
4615 public void drop(DropTargetDropEvent evt)
4617 // JAL-1552 - acceptDrop required before getTransferable call for
4618 // Java's Transferable for native dnd
4619 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4620 Transferable t = evt.getTransferable();
4622 final AlignFrame thisaf = this;
4623 final List<Object> files = new ArrayList<>();
4624 List<DataSourceType> protocols = new ArrayList<>();
4628 Desktop.transferFromDropTarget(files, protocols, evt, t);
4629 } catch (Exception e)
4631 e.printStackTrace();
4635 new Thread(new Runnable()
4642 // check to see if any of these files have names matching sequences
4645 SequenceIdMatcher idm = new SequenceIdMatcher(
4646 viewport.getAlignment().getSequencesArray());
4648 * Object[] { String,SequenceI}
4650 ArrayList<Object[]> filesmatched = new ArrayList<>();
4651 ArrayList<Object> filesnotmatched = new ArrayList<>();
4652 for (int i = 0; i < files.size(); i++)
4655 Object file = files.get(i);
4656 String fileName = file.toString();
4658 DataSourceType protocol = (file instanceof File
4659 ? DataSourceType.FILE
4660 : FormatAdapter.checkProtocol(fileName));
4661 if (protocol == DataSourceType.FILE)
4664 if (file instanceof File)
4667 Platform.cacheFileData(fl);
4671 fl = new File(fileName);
4673 pdbfn = fl.getName();
4675 else if (protocol == DataSourceType.URL)
4677 URL url = new URL(fileName);
4678 pdbfn = url.getFile();
4680 if (pdbfn.length() > 0)
4682 // attempt to find a match in the alignment
4683 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4684 int l = 0, c = pdbfn.indexOf(".");
4685 while (mtch == null && c != -1)
4690 } while ((c = pdbfn.indexOf(".", l)) > l);
4693 pdbfn = pdbfn.substring(0, l);
4695 mtch = idm.findAllIdMatches(pdbfn);
4702 type = new IdentifyFile().identify(file, protocol);
4703 } catch (Exception ex)
4707 if (type != null && type.isStructureFile())
4709 filesmatched.add(new Object[] { file, protocol, mtch });
4713 // File wasn't named like one of the sequences or wasn't a PDB
4715 filesnotmatched.add(file);
4719 if (filesmatched.size() > 0)
4721 boolean autoAssociate = Cache
4722 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4725 String msg = MessageManager.formatMessage(
4726 "label.automatically_associate_structure_files_with_sequences_same_name",
4728 { Integer.valueOf(filesmatched.size())
4730 String ttl = MessageManager.getString(
4731 "label.automatically_associate_structure_files_by_name");
4732 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4733 ttl, JvOptionPane.YES_NO_OPTION);
4734 autoAssociate = choice == JvOptionPane.YES_OPTION;
4738 for (Object[] fm : filesmatched)
4740 // try and associate
4741 // TODO: may want to set a standard ID naming formalism for
4742 // associating PDB files which have no IDs.
4743 for (SequenceI toassoc : (SequenceI[]) fm[2])
4745 PDBEntry pe = new AssociatePdbFileWithSeq()
4746 .associatePdbWithSeq(fm[0].toString(),
4747 (DataSourceType) fm[1], toassoc, false,
4751 System.err.println("Associated file : "
4752 + (fm[0].toString()) + " with "
4753 + toassoc.getDisplayId(true));
4757 // TODO: do we need to update overview ? only if features are
4759 alignPanel.paintAlignment(true, false);
4765 * add declined structures as sequences
4767 for (Object[] o : filesmatched)
4769 filesnotmatched.add(o[0]);
4773 if (filesnotmatched.size() > 0)
4775 if (assocfiles > 0 && (Cache.getDefault(
4776 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4777 || JvOptionPane.showConfirmDialog(thisaf,
4778 "<html>" + MessageManager.formatMessage(
4779 "label.ignore_unmatched_dropped_files_info",
4782 filesnotmatched.size())
4785 MessageManager.getString(
4786 "label.ignore_unmatched_dropped_files"),
4787 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4791 for (Object fn : filesnotmatched)
4793 loadJalviewDataFile(fn, null, null, null);
4797 } catch (Exception ex)
4799 ex.printStackTrace();
4807 * Attempt to load a "dropped" file or URL string, by testing in turn for
4809 * <li>an Annotation file</li>
4810 * <li>a JNet file</li>
4811 * <li>a features file</li>
4812 * <li>else try to interpret as an alignment file</li>
4816 * either a filename or a URL string.
4818 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4819 FileFormatI format, SequenceI assocSeq)
4821 // BH 2018 was String file
4824 if (sourceType == null)
4826 sourceType = FormatAdapter.checkProtocol(file);
4828 // if the file isn't identified, or not positively identified as some
4829 // other filetype (PFAM is default unidentified alignment file type) then
4830 // try to parse as annotation.
4831 boolean isAnnotation = (format == null
4832 || FileFormat.Pfam.equals(format))
4833 ? new AnnotationFile().annotateAlignmentView(viewport,
4839 // first see if its a T-COFFEE score file
4840 TCoffeeScoreFile tcf = null;
4843 tcf = new TCoffeeScoreFile(file, sourceType);
4846 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4850 new TCoffeeColourScheme(viewport.getAlignment()));
4851 isAnnotation = true;
4852 setStatus(MessageManager.getString(
4853 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4857 // some problem - if no warning its probable that the ID matching
4858 // process didn't work
4859 JvOptionPane.showMessageDialog(Desktop.desktop,
4860 tcf.getWarningMessage() == null
4861 ? MessageManager.getString(
4862 "label.check_file_matches_sequence_ids_alignment")
4863 : tcf.getWarningMessage(),
4864 MessageManager.getString(
4865 "label.problem_reading_tcoffee_score_file"),
4866 JvOptionPane.WARNING_MESSAGE);
4873 } catch (Exception x)
4876 "Exception when processing data source as T-COFFEE score file",
4882 // try to see if its a JNet 'concise' style annotation file *before*
4884 // try to parse it as a features file
4887 format = new IdentifyFile().identify(file, sourceType);
4889 if (FileFormat.ScoreMatrix == format)
4891 ScoreMatrixFile sm = new ScoreMatrixFile(
4892 new FileParse(file, sourceType));
4894 // todo: i18n this message
4895 setStatus(MessageManager.formatMessage(
4896 "label.successfully_loaded_matrix",
4897 sm.getMatrixName()));
4899 else if (FileFormat.Jnet.equals(format))
4901 JPredFile predictions = new JPredFile(file, sourceType);
4902 new JnetAnnotationMaker();
4903 JnetAnnotationMaker.add_annotation(predictions,
4904 viewport.getAlignment(), 0, false);
4905 viewport.getAlignment().setupJPredAlignment();
4906 isAnnotation = true;
4908 // else if (IdentifyFile.FeaturesFile.equals(format))
4909 else if (FileFormat.Features.equals(format))
4911 if (parseFeaturesFile(file, sourceType))
4913 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4914 if (splitFrame != null)
4916 splitFrame.repaint();
4920 alignPanel.paintAlignment(true, true);
4926 new FileLoader().LoadFile(viewport, file, sourceType, format);
4933 alignPanel.adjustAnnotationHeight();
4934 viewport.updateSequenceIdColours();
4935 buildSortByAnnotationScoresMenu();
4936 alignPanel.paintAlignment(true, true);
4938 } catch (Exception ex)
4940 ex.printStackTrace();
4941 } catch (OutOfMemoryError oom)
4946 } catch (Exception x)
4951 + (sourceType != null
4952 ? (sourceType == DataSourceType.PASTE
4954 : "using " + sourceType + " from "
4958 ? "(parsing as '" + format + "' file)"
4960 oom, Desktop.desktop);
4965 * Method invoked by the ChangeListener on the tabbed pane, in other words
4966 * when a different tabbed pane is selected by the user or programmatically.
4969 public void tabSelectionChanged(int index)
4973 alignPanel = alignPanels.get(index);
4974 viewport = alignPanel.av;
4975 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4976 setMenusFromViewport(viewport);
4977 if (featureSettings != null && featureSettings.isOpen()
4978 && featureSettings.fr.getViewport() != viewport)
4980 if (viewport.isShowSequenceFeatures())
4982 // refresh the featureSettings to reflect UI change
4983 showFeatureSettingsUI();
4987 // close feature settings for this view.
4988 featureSettings.close();
4995 * 'focus' any colour slider that is open to the selected viewport
4997 if (viewport.getConservationSelected())
4999 SliderPanel.setConservationSlider(alignPanel,
5000 viewport.getResidueShading(), alignPanel.getViewName());
5004 SliderPanel.hideConservationSlider();
5006 if (viewport.getAbovePIDThreshold())
5008 SliderPanel.setPIDSliderSource(alignPanel,
5009 viewport.getResidueShading(), alignPanel.getViewName());
5013 SliderPanel.hidePIDSlider();
5017 * If there is a frame linked to this one in a SplitPane, switch it to the
5018 * same view tab index. No infinite recursion of calls should happen, since
5019 * tabSelectionChanged() should not get invoked on setting the selected
5020 * index to an unchanged value. Guard against setting an invalid index
5021 * before the new view peer tab has been created.
5023 final AlignViewportI peer = viewport.getCodingComplement();
5026 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5027 .getAlignPanel().alignFrame;
5028 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5030 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5036 * On right mouse click on view tab, prompt for and set new view name.
5039 public void tabbedPane_mousePressed(MouseEvent e)
5041 if (e.isPopupTrigger())
5043 String msg = MessageManager.getString("label.enter_view_name");
5044 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5045 String reply = JvOptionPane.showInputDialog(msg, ttl);
5049 viewport.setViewName(reply);
5050 // TODO warn if reply is in getExistingViewNames()?
5051 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5056 public AlignViewport getCurrentView()
5062 * Open the dialog for regex description parsing.
5065 protected void extractScores_actionPerformed(ActionEvent e)
5067 ParseProperties pp = new jalview.analysis.ParseProperties(
5068 viewport.getAlignment());
5069 // TODO: verify regex and introduce GUI dialog for version 2.5
5070 // if (pp.getScoresFromDescription("col", "score column ",
5071 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5073 if (pp.getScoresFromDescription("description column",
5074 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5076 buildSortByAnnotationScoresMenu();
5084 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5088 protected void showDbRefs_actionPerformed(ActionEvent e)
5090 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5096 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5100 protected void showNpFeats_actionPerformed(ActionEvent e)
5102 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5106 * find the viewport amongst the tabs in this alignment frame and close that
5111 public boolean closeView(AlignViewportI av)
5115 this.closeMenuItem_actionPerformed(false);
5118 Component[] comp = tabbedPane.getComponents();
5119 for (int i = 0; comp != null && i < comp.length; i++)
5121 if (comp[i] instanceof AlignmentPanel)
5123 if (((AlignmentPanel) comp[i]).av == av)
5126 closeView((AlignmentPanel) comp[i]);
5134 protected void build_fetchdbmenu(JMenu webService)
5136 // Temporary hack - DBRef Fetcher always top level ws entry.
5137 // TODO We probably want to store a sequence database checklist in
5138 // preferences and have checkboxes.. rather than individual sources selected
5140 final JMenu rfetch = new JMenu(
5141 MessageManager.getString("action.fetch_db_references"));
5142 rfetch.setToolTipText(MessageManager.getString(
5143 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5144 webService.add(rfetch);
5146 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5147 MessageManager.getString("option.trim_retrieved_seqs"));
5148 trimrs.setToolTipText(
5149 MessageManager.getString("label.trim_retrieved_sequences"));
5151 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5152 trimrs.addActionListener(new ActionListener()
5155 public void actionPerformed(ActionEvent e)
5157 trimrs.setSelected(trimrs.isSelected());
5158 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5159 Boolean.valueOf(trimrs.isSelected()).toString());
5163 JMenuItem fetchr = new JMenuItem(
5164 MessageManager.getString("label.standard_databases"));
5165 fetchr.setToolTipText(
5166 MessageManager.getString("label.fetch_embl_uniprot"));
5167 fetchr.addActionListener(new ActionListener()
5171 public void actionPerformed(ActionEvent e)
5173 new Thread(new Runnable()
5178 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5179 .getAlignment().isNucleotide();
5180 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5181 alignPanel.av.getSequenceSelection(),
5182 alignPanel.alignFrame, null,
5183 alignPanel.alignFrame.featureSettings, isNucleotide);
5184 dbRefFetcher.addListener(new FetchFinishedListenerI()
5187 public void finished()
5190 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5191 .getFeatureSettingsModels())
5194 alignPanel.av.mergeFeaturesStyle(srcSettings);
5196 AlignFrame.this.setMenusForViewport();
5199 dbRefFetcher.fetchDBRefs(false);
5207 new Thread(new Runnable()
5212 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5213 .getSequenceFetcherSingleton();
5214 javax.swing.SwingUtilities.invokeLater(new Runnable()
5219 String[] dbclasses = sf.getNonAlignmentSources();
5220 List<DbSourceProxy> otherdb;
5221 JMenu dfetch = new JMenu();
5222 JMenu ifetch = new JMenu();
5223 JMenuItem fetchr = null;
5224 int comp = 0, icomp = 0, mcomp = 15;
5225 String mname = null;
5227 for (String dbclass : dbclasses)
5229 otherdb = sf.getSourceProxy(dbclass);
5230 // add a single entry for this class, or submenu allowing 'fetch
5232 if (otherdb == null || otherdb.size() < 1)
5238 mname = "From " + dbclass;
5240 if (otherdb.size() == 1)
5242 final DbSourceProxy[] dassource = otherdb
5243 .toArray(new DbSourceProxy[0]);
5244 DbSourceProxy src = otherdb.get(0);
5245 fetchr = new JMenuItem(src.getDbSource());
5246 fetchr.addActionListener(new ActionListener()
5250 public void actionPerformed(ActionEvent e)
5252 new Thread(new Runnable()
5258 boolean isNucleotide = alignPanel.alignFrame
5259 .getViewport().getAlignment()
5261 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5262 alignPanel.av.getSequenceSelection(),
5263 alignPanel.alignFrame, dassource,
5264 alignPanel.alignFrame.featureSettings,
5267 .addListener(new FetchFinishedListenerI()
5270 public void finished()
5272 FeatureSettingsModelI srcSettings = dassource[0]
5273 .getFeatureColourScheme();
5274 alignPanel.av.mergeFeaturesStyle(
5276 AlignFrame.this.setMenusForViewport();
5279 dbRefFetcher.fetchDBRefs(false);
5285 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5286 MessageManager.formatMessage(
5287 "label.fetch_retrieve_from", new Object[]
5288 { src.getDbName() })));
5294 final DbSourceProxy[] dassource = otherdb
5295 .toArray(new DbSourceProxy[0]);
5297 DbSourceProxy src = otherdb.get(0);
5298 fetchr = new JMenuItem(MessageManager
5299 .formatMessage("label.fetch_all_param", new Object[]
5300 { src.getDbSource() }));
5301 fetchr.addActionListener(new ActionListener()
5304 public void actionPerformed(ActionEvent e)
5306 new Thread(new Runnable()
5312 boolean isNucleotide = alignPanel.alignFrame
5313 .getViewport().getAlignment()
5315 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5316 alignPanel.av.getSequenceSelection(),
5317 alignPanel.alignFrame, dassource,
5318 alignPanel.alignFrame.featureSettings,
5321 .addListener(new FetchFinishedListenerI()
5324 public void finished()
5326 AlignFrame.this.setMenusForViewport();
5329 dbRefFetcher.fetchDBRefs(false);
5335 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5336 MessageManager.formatMessage(
5337 "label.fetch_retrieve_from_all_sources",
5339 { Integer.valueOf(otherdb.size())
5341 src.getDbSource(), src.getDbName() })));
5344 // and then build the rest of the individual menus
5345 ifetch = new JMenu(MessageManager.formatMessage(
5346 "label.source_from_db_source", new Object[]
5347 { src.getDbSource() }));
5349 String imname = null;
5351 for (DbSourceProxy sproxy : otherdb)
5353 String dbname = sproxy.getDbName();
5354 String sname = dbname.length() > 5
5355 ? dbname.substring(0, 5) + "..."
5357 String msname = dbname.length() > 10
5358 ? dbname.substring(0, 10) + "..."
5362 imname = MessageManager
5363 .formatMessage("label.from_msname", new Object[]
5366 fetchr = new JMenuItem(msname);
5367 final DbSourceProxy[] dassrc = { sproxy };
5368 fetchr.addActionListener(new ActionListener()
5372 public void actionPerformed(ActionEvent e)
5374 new Thread(new Runnable()
5380 boolean isNucleotide = alignPanel.alignFrame
5381 .getViewport().getAlignment()
5383 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5384 alignPanel.av.getSequenceSelection(),
5385 alignPanel.alignFrame, dassrc,
5386 alignPanel.alignFrame.featureSettings,
5389 .addListener(new FetchFinishedListenerI()
5392 public void finished()
5394 AlignFrame.this.setMenusForViewport();
5397 dbRefFetcher.fetchDBRefs(false);
5403 fetchr.setToolTipText(
5404 "<html>" + MessageManager.formatMessage(
5405 "label.fetch_retrieve_from", new Object[]
5409 if (++icomp >= mcomp || i == (otherdb.size()))
5411 ifetch.setText(MessageManager.formatMessage(
5412 "label.source_to_target", imname, sname));
5414 ifetch = new JMenu();
5422 if (comp >= mcomp || dbi >= (dbclasses.length))
5424 dfetch.setText(MessageManager.formatMessage(
5425 "label.source_to_target", mname, dbclass));
5427 dfetch = new JMenu();
5440 * Left justify the whole alignment.
5443 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5445 AlignmentI al = viewport.getAlignment();
5447 viewport.firePropertyChange("alignment", null, al);
5451 * Right justify the whole alignment.
5454 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5456 AlignmentI al = viewport.getAlignment();
5458 viewport.firePropertyChange("alignment", null, al);
5462 public void setShowSeqFeatures(boolean b)
5464 showSeqFeatures.setSelected(b);
5465 viewport.setShowSequenceFeatures(b);
5472 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5473 * awt.event.ActionEvent)
5476 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5478 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5479 alignPanel.paintAlignment(false, false);
5486 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5490 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5492 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5493 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5501 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5502 * .event.ActionEvent)
5505 protected void showGroupConservation_actionPerformed(ActionEvent e)
5507 viewport.setShowGroupConservation(showGroupConservation.getState());
5508 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5515 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5516 * .event.ActionEvent)
5519 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5521 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5522 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5529 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5530 * .event.ActionEvent)
5533 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5535 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5536 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5540 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5542 showSequenceLogo.setState(true);
5543 viewport.setShowSequenceLogo(true);
5544 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5545 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5549 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5551 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5558 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5559 * .event.ActionEvent)
5562 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5564 if (avc.makeGroupsFromSelection())
5566 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5567 alignPanel.updateAnnotation();
5568 alignPanel.paintAlignment(true,
5569 viewport.needToUpdateStructureViews());
5573 public void clearAlignmentSeqRep()
5575 // TODO refactor alignmentseqrep to controller
5576 if (viewport.getAlignment().hasSeqrep())
5578 viewport.getAlignment().setSeqrep(null);
5579 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5580 alignPanel.updateAnnotation();
5581 alignPanel.paintAlignment(true, true);
5586 protected void createGroup_actionPerformed(ActionEvent e)
5588 if (avc.createGroup())
5590 if (applyAutoAnnotationSettings.isSelected())
5592 alignPanel.updateAnnotation(true, false);
5594 alignPanel.alignmentChanged();
5599 protected void unGroup_actionPerformed(ActionEvent e)
5603 alignPanel.alignmentChanged();
5608 * make the given alignmentPanel the currently selected tab
5610 * @param alignmentPanel
5612 public void setDisplayedView(AlignmentPanel alignmentPanel)
5614 if (!viewport.getSequenceSetId()
5615 .equals(alignmentPanel.av.getSequenceSetId()))
5617 throw new Error(MessageManager.getString(
5618 "error.implementation_error_cannot_show_view_alignment_frame"));
5620 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5621 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5623 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5628 * Action on selection of menu options to Show or Hide annotations.
5631 * @param forSequences
5632 * update sequence-related annotations
5633 * @param forAlignment
5634 * update non-sequence-related annotations
5637 protected void setAnnotationsVisibility(boolean visible,
5638 boolean forSequences, boolean forAlignment)
5640 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5641 .getAlignmentAnnotation();
5646 for (AlignmentAnnotation aa : anns)
5649 * don't display non-positional annotations on an alignment
5651 if (aa.annotations == null)
5655 boolean apply = (aa.sequenceRef == null && forAlignment)
5656 || (aa.sequenceRef != null && forSequences);
5659 aa.visible = visible;
5662 alignPanel.validateAnnotationDimensions(true);
5663 alignPanel.alignmentChanged();
5667 * Store selected annotation sort order for the view and repaint.
5670 protected void sortAnnotations_actionPerformed()
5672 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5674 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5675 alignPanel.paintAlignment(false, false);
5680 * @return alignment panels in this alignment frame
5682 public List<? extends AlignmentViewPanel> getAlignPanels()
5684 // alignPanels is never null
5685 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5690 * Open a new alignment window, with the cDNA associated with this (protein)
5691 * alignment, aligned as is the protein.
5693 protected void viewAsCdna_actionPerformed()
5695 // TODO no longer a menu action - refactor as required
5696 final AlignmentI alignment = getViewport().getAlignment();
5697 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5698 if (mappings == null)
5702 List<SequenceI> cdnaSeqs = new ArrayList<>();
5703 for (SequenceI aaSeq : alignment.getSequences())
5705 for (AlignedCodonFrame acf : mappings)
5707 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5711 * There is a cDNA mapping for this protein sequence - add to new
5712 * alignment. It will share the same dataset sequence as other mapped
5713 * cDNA (no new mappings need to be created).
5715 final Sequence newSeq = new Sequence(dnaSeq);
5716 newSeq.setDatasetSequence(dnaSeq);
5717 cdnaSeqs.add(newSeq);
5721 if (cdnaSeqs.size() == 0)
5723 // show a warning dialog no mapped cDNA
5726 AlignmentI cdna = new Alignment(
5727 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5728 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5729 AlignFrame.DEFAULT_HEIGHT);
5730 cdna.alignAs(alignment);
5731 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5733 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5734 AlignFrame.DEFAULT_HEIGHT);
5738 * Set visibility of dna/protein complement view (available when shown in a
5744 protected void showComplement_actionPerformed(boolean show)
5746 SplitContainerI sf = getSplitViewContainer();
5749 sf.setComplementVisible(this, show);
5754 * Generate the reverse (optionally complemented) of the selected sequences,
5755 * and add them to the alignment
5758 protected void showReverse_actionPerformed(boolean complement)
5760 AlignmentI al = null;
5763 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5764 al = dna.reverseCdna(complement);
5765 viewport.addAlignment(al, "");
5766 addHistoryItem(new EditCommand(
5767 MessageManager.getString("label.add_sequences"), Action.PASTE,
5768 al.getSequencesArray(), 0, al.getWidth(),
5769 viewport.getAlignment()));
5770 } catch (Exception ex)
5772 System.err.println(ex.getMessage());
5778 * Try to run a script in the Groovy console, having first ensured that this
5779 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5780 * be targeted at this alignment.
5783 protected void runGroovy_actionPerformed()
5785 Jalview.setCurrentAlignFrame(this);
5786 groovy.ui.Console console = Desktop.getGroovyConsole();
5787 if (console != null)
5791 console.runScript();
5792 } catch (Exception ex)
5794 System.err.println((ex.toString()));
5795 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5796 MessageManager.getString("label.couldnt_run_groovy_script"),
5797 MessageManager.getString("label.groovy_support_failed"),
5798 JvOptionPane.ERROR_MESSAGE);
5803 System.err.println("Can't run Groovy script as console not found");
5808 * Hides columns containing (or not containing) a specified feature, provided
5809 * that would not leave all columns hidden
5811 * @param featureType
5812 * @param columnsContaining
5815 public boolean hideFeatureColumns(String featureType,
5816 boolean columnsContaining)
5818 boolean notForHiding = avc.markColumnsContainingFeatures(
5819 columnsContaining, false, false, featureType);
5822 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5823 false, featureType))
5825 getViewport().hideSelectedColumns();
5833 protected void selectHighlightedColumns_actionPerformed(
5834 ActionEvent actionEvent)
5836 // include key modifier check in case user selects from menu
5837 avc.markHighlightedColumns(
5838 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5839 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5840 | ActionEvent.CTRL_MASK)) != 0);
5844 * Rebuilds the Colour menu, including any user-defined colours which have
5845 * been loaded either on startup or during the session
5847 public void buildColourMenu()
5849 colourMenu.removeAll();
5851 colourMenu.add(applyToAllGroups);
5852 colourMenu.add(textColour);
5853 colourMenu.addSeparator();
5855 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5856 viewport.getAlignment(), false);
5858 colourMenu.add(annotationColour);
5859 bg.add(annotationColour);
5860 colourMenu.addSeparator();
5861 colourMenu.add(conservationMenuItem);
5862 colourMenu.add(modifyConservation);
5863 colourMenu.add(abovePIDThreshold);
5864 colourMenu.add(modifyPID);
5866 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5867 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5871 * Open a dialog (if not already open) that allows the user to select and
5872 * calculate PCA or Tree analysis
5874 protected void openTreePcaDialog()
5876 if (alignPanel.getCalculationDialog() == null)
5878 new CalculationChooser(AlignFrame.this);
5883 protected void loadVcf_actionPerformed()
5885 JalviewFileChooser chooser = new JalviewFileChooser(
5886 Cache.getProperty("LAST_DIRECTORY"));
5887 chooser.setFileView(new JalviewFileView());
5888 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5889 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5890 final AlignFrame us = this;
5891 chooser.setResponseHandler(0, new Runnable()
5896 String choice = chooser.getSelectedFile().getPath();
5897 Cache.setProperty("LAST_DIRECTORY", choice);
5898 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5899 new VCFLoader(choice).loadVCF(seqs, us);
5902 chooser.showOpenDialog(null);
5906 private Rectangle lastFeatureSettingsBounds = null;
5909 public void setFeatureSettingsGeometry(Rectangle bounds)
5911 lastFeatureSettingsBounds = bounds;
5915 public Rectangle getFeatureSettingsGeometry()
5917 return lastFeatureSettingsBounds;
5921 class PrintThread extends Thread
5925 public PrintThread(AlignmentPanel ap)
5930 static PageFormat pf;
5935 PrinterJob printJob = PrinterJob.getPrinterJob();
5939 printJob.setPrintable(ap, pf);
5943 printJob.setPrintable(ap);
5946 if (printJob.printDialog())
5951 } catch (Exception PrintException)
5953 PrintException.printStackTrace();