2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenMarkovModel;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.hmmer.HMMAlignThread;
67 import jalview.hmmer.HMMBuildThread;
68 import jalview.hmmer.HMMERParamStore;
69 import jalview.hmmer.HMMERPreset;
70 import jalview.hmmer.HMMSearchThread;
71 import jalview.io.AlignmentProperties;
72 import jalview.io.AnnotationFile;
73 import jalview.io.BioJsHTMLOutput;
74 import jalview.io.DataSourceType;
75 import jalview.io.FileFormat;
76 import jalview.io.FileFormatI;
77 import jalview.io.FileFormats;
78 import jalview.io.FileLoader;
79 import jalview.io.FileParse;
80 import jalview.io.FormatAdapter;
81 import jalview.io.HtmlSvgOutput;
82 import jalview.io.IdentifyFile;
83 import jalview.io.JPredFile;
84 import jalview.io.JalviewFileChooser;
85 import jalview.io.JalviewFileView;
86 import jalview.io.JnetAnnotationMaker;
87 import jalview.io.NewickFile;
88 import jalview.io.ScoreMatrixFile;
89 import jalview.io.TCoffeeScoreFile;
90 import jalview.jbgui.GAlignFrame;
91 import jalview.schemes.ColourSchemeI;
92 import jalview.schemes.ColourSchemes;
93 import jalview.schemes.ResidueColourScheme;
94 import jalview.schemes.TCoffeeColourScheme;
95 import jalview.util.MessageManager;
96 import jalview.util.StringUtils;
97 import jalview.viewmodel.AlignmentViewport;
98 import jalview.viewmodel.ViewportRanges;
99 import jalview.ws.DBRefFetcher;
100 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
101 import jalview.ws.jws1.Discoverer;
102 import jalview.ws.jws2.Jws2Discoverer;
103 import jalview.ws.jws2.jabaws2.Jws2Instance;
104 import jalview.ws.params.ArgumentI;
105 import jalview.ws.params.ParamDatastoreI;
106 import jalview.ws.params.WsParamSetI;
107 import jalview.ws.seqfetcher.DbSourceProxy;
109 import java.awt.BorderLayout;
110 import java.awt.Component;
111 import java.awt.Rectangle;
112 import java.awt.Toolkit;
113 import java.awt.datatransfer.Clipboard;
114 import java.awt.datatransfer.DataFlavor;
115 import java.awt.datatransfer.StringSelection;
116 import java.awt.datatransfer.Transferable;
117 import java.awt.dnd.DnDConstants;
118 import java.awt.dnd.DropTargetDragEvent;
119 import java.awt.dnd.DropTargetDropEvent;
120 import java.awt.dnd.DropTargetEvent;
121 import java.awt.dnd.DropTargetListener;
122 import java.awt.event.ActionEvent;
123 import java.awt.event.ActionListener;
124 import java.awt.event.FocusAdapter;
125 import java.awt.event.FocusEvent;
126 import java.awt.event.ItemEvent;
127 import java.awt.event.ItemListener;
128 import java.awt.event.KeyAdapter;
129 import java.awt.event.KeyEvent;
130 import java.awt.event.MouseEvent;
131 import java.awt.print.PageFormat;
132 import java.awt.print.PrinterJob;
133 import java.beans.PropertyChangeEvent;
135 import java.io.FileWriter;
136 import java.io.IOException;
137 import java.io.PrintWriter;
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Deque;
142 import java.util.Enumeration;
143 import java.util.HashMap;
144 import java.util.Hashtable;
145 import java.util.List;
146 import java.util.Map;
147 import java.util.Scanner;
148 import java.util.Vector;
150 import javax.swing.JCheckBoxMenuItem;
151 import javax.swing.JEditorPane;
152 import javax.swing.JFileChooser;
153 import javax.swing.JFrame;
154 import javax.swing.JInternalFrame;
155 import javax.swing.JLayeredPane;
156 import javax.swing.JMenu;
157 import javax.swing.JMenuItem;
158 import javax.swing.JOptionPane;
159 import javax.swing.JScrollPane;
160 import javax.swing.SwingUtilities;
166 * @version $Revision$
168 public class AlignFrame extends GAlignFrame implements DropTargetListener,
169 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
172 Map<String, Float> distribution = new HashMap<>(); // temporary
174 public static final int DEFAULT_WIDTH = 700;
176 public static final int DEFAULT_HEIGHT = 500;
179 * The currently displayed panel (selected tabbed view if more than one)
181 public AlignmentPanel alignPanel;
183 AlignViewport viewport;
185 ViewportRanges vpRanges;
187 public AlignViewControllerI avc;
189 * The selected HMM for this align frame
191 SequenceI selectedHMMSequence;
193 List<AlignmentPanel> alignPanels = new ArrayList<>();
196 * Last format used to load or save alignments in this window
198 FileFormatI currentFileFormat = null;
201 * Current filename for this alignment
203 String fileName = null;
207 * Creates a new AlignFrame object with specific width and height.
213 public AlignFrame(AlignmentI al, int width, int height)
215 this(al, null, width, height);
219 * Creates a new AlignFrame object with specific width, height and
225 * @param sequenceSetId
227 public AlignFrame(AlignmentI al, int width, int height,
228 String sequenceSetId)
230 this(al, null, width, height, sequenceSetId);
234 * Creates a new AlignFrame object with specific width, height and
240 * @param sequenceSetId
243 public AlignFrame(AlignmentI al, int width, int height,
244 String sequenceSetId, String viewId)
246 this(al, null, width, height, sequenceSetId, viewId);
250 * new alignment window with hidden columns
254 * @param hiddenColumns
255 * ColumnSelection or null
257 * Width of alignment frame
261 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
264 this(al, hiddenColumns, width, height, null);
268 * Create alignment frame for al with hiddenColumns, a specific width and
269 * height, and specific sequenceId
272 * @param hiddenColumns
275 * @param sequenceSetId
278 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
279 int height, String sequenceSetId)
281 this(al, hiddenColumns, width, height, sequenceSetId, null);
285 * Create alignment frame for al with hiddenColumns, a specific width and
286 * height, and specific sequenceId
289 * @param hiddenColumns
292 * @param sequenceSetId
297 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
298 int height, String sequenceSetId, String viewId)
300 setSize(width, height);
302 if (al.getDataset() == null)
307 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
309 alignPanel = new AlignmentPanel(this, viewport);
311 addAlignmentPanel(alignPanel, true);
315 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
316 HiddenColumns hiddenColumns, int width, int height)
318 setSize(width, height);
320 if (al.getDataset() == null)
325 viewport = new AlignViewport(al, hiddenColumns);
327 if (hiddenSeqs != null && hiddenSeqs.length > 0)
329 viewport.hideSequence(hiddenSeqs);
331 alignPanel = new AlignmentPanel(this, viewport);
332 addAlignmentPanel(alignPanel, true);
337 * Make a new AlignFrame from existing alignmentPanels
344 public AlignFrame(AlignmentPanel ap)
348 addAlignmentPanel(ap, false);
353 * initalise the alignframe from the underlying viewport data and the
358 if (!Jalview.isHeadlessMode())
360 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
363 vpRanges = viewport.getRanges();
364 avc = new jalview.controller.AlignViewController(this, viewport,
366 if (viewport.getAlignmentConservationAnnotation() == null)
368 // BLOSUM62Colour.setEnabled(false);
369 conservationMenuItem.setEnabled(false);
370 modifyConservation.setEnabled(false);
371 // PIDColour.setEnabled(false);
372 // abovePIDThreshold.setEnabled(false);
373 // modifyPID.setEnabled(false);
376 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
379 if (sortby.equals("Id"))
381 sortIDMenuItem_actionPerformed(null);
383 else if (sortby.equals("Pairwise Identity"))
385 sortPairwiseMenuItem_actionPerformed(null);
389 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
391 setMenusFromViewport(viewport);
392 buildSortByAnnotationScoresMenu();
393 calculateTree.addActionListener(new ActionListener()
397 public void actionPerformed(ActionEvent e)
405 if (Desktop.desktop != null)
407 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
408 addServiceListeners();
412 if (viewport.getWrapAlignment())
414 wrapMenuItem_actionPerformed(null);
417 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
419 this.overviewMenuItem_actionPerformed(null);
424 final List<AlignmentPanel> selviews = new ArrayList<>();
425 final List<AlignmentPanel> origview = new ArrayList<>();
426 final String menuLabel = MessageManager
427 .getString("label.copy_format_from");
428 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
429 new ViewSetProvider()
433 public AlignmentPanel[] getAllAlignmentPanels()
436 origview.add(alignPanel);
437 // make an array of all alignment panels except for this one
438 List<AlignmentPanel> aps = new ArrayList<>(
439 Arrays.asList(Desktop.getAlignmentPanels(null)));
440 aps.remove(AlignFrame.this.alignPanel);
441 return aps.toArray(new AlignmentPanel[aps.size()]);
443 }, selviews, new ItemListener()
447 public void itemStateChanged(ItemEvent e)
449 if (origview.size() > 0)
451 final AlignmentPanel ap = origview.get(0);
454 * Copy the ViewStyle of the selected panel to 'this one'.
455 * Don't change value of 'scaleProteinAsCdna' unless copying
458 ViewStyleI vs = selviews.get(0).getAlignViewport()
460 boolean fromSplitFrame = selviews.get(0)
461 .getAlignViewport().getCodingComplement() != null;
464 vs.setScaleProteinAsCdna(ap.getAlignViewport()
465 .getViewStyle().isScaleProteinAsCdna());
467 ap.getAlignViewport().setViewStyle(vs);
470 * Also rescale ViewStyle of SplitFrame complement if there is
471 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
472 * the whole ViewStyle (allow cDNA protein to have different
475 AlignViewportI complement = ap.getAlignViewport()
476 .getCodingComplement();
477 if (complement != null && vs.isScaleProteinAsCdna())
479 AlignFrame af = Desktop.getAlignFrameFor(complement);
480 ((SplitFrame) af.getSplitViewContainer())
482 af.setMenusForViewport();
486 ap.setSelected(true);
487 ap.alignFrame.setMenusForViewport();
492 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
493 .indexOf("devel") > -1
494 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
495 .indexOf("test") > -1)
497 formatMenu.add(vsel);
499 addFocusListener(new FocusAdapter()
502 public void focusGained(FocusEvent e)
504 Jalview.setCurrentAlignFrame(AlignFrame.this);
511 * Adds all menu items to the HMMER menu
513 private void buildHMMERMenu()
515 hmmerMenu.removeAll();
517 hmmerMenu.add(hmmAlign);
518 hmmerMenu.add(hmmBuild);
519 hmmerMenu.add(hmmSearch);
523 * Change the filename and format for the alignment, and enable the 'reload'
524 * button functionality.
531 public void setFileName(String file, FileFormatI format)
534 setFileFormat(format);
535 reload.setEnabled(true);
539 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
542 void addKeyListener()
544 addKeyListener(new KeyAdapter()
547 public void keyPressed(KeyEvent evt)
549 if (viewport.cursorMode
550 && ((evt.getKeyCode() >= KeyEvent.VK_0
551 && evt.getKeyCode() <= KeyEvent.VK_9)
552 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
553 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
554 && Character.isDigit(evt.getKeyChar()))
556 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
559 switch (evt.getKeyCode())
562 case 27: // escape key
563 deselectAllSequenceMenuItem_actionPerformed(null);
567 case KeyEvent.VK_DOWN:
568 if (evt.isAltDown() || !viewport.cursorMode)
570 moveSelectedSequences(false);
572 if (viewport.cursorMode)
574 alignPanel.getSeqPanel().moveCursor(0, 1);
579 if (evt.isAltDown() || !viewport.cursorMode)
581 moveSelectedSequences(true);
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().moveCursor(0, -1);
590 case KeyEvent.VK_LEFT:
591 if (evt.isAltDown() || !viewport.cursorMode)
593 slideSequences(false,
594 alignPanel.getSeqPanel().getKeyboardNo1());
598 alignPanel.getSeqPanel().moveCursor(-1, 0);
603 case KeyEvent.VK_RIGHT:
604 if (evt.isAltDown() || !viewport.cursorMode)
606 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
610 alignPanel.getSeqPanel().moveCursor(1, 0);
614 case KeyEvent.VK_SPACE:
615 if (viewport.cursorMode)
617 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
618 || evt.isShiftDown() || evt.isAltDown());
622 // case KeyEvent.VK_A:
623 // if (viewport.cursorMode)
625 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
626 // //System.out.println("A");
630 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
631 * System.out.println("closing bracket"); } break;
633 case KeyEvent.VK_DELETE:
634 case KeyEvent.VK_BACK_SPACE:
635 if (!viewport.cursorMode)
637 cut_actionPerformed(null);
641 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
642 || evt.isShiftDown() || evt.isAltDown());
648 if (viewport.cursorMode)
650 alignPanel.getSeqPanel().setCursorRow();
654 if (viewport.cursorMode && !evt.isControlDown())
656 alignPanel.getSeqPanel().setCursorColumn();
660 if (viewport.cursorMode)
662 alignPanel.getSeqPanel().setCursorPosition();
666 case KeyEvent.VK_ENTER:
667 case KeyEvent.VK_COMMA:
668 if (viewport.cursorMode)
670 alignPanel.getSeqPanel().setCursorRowAndColumn();
675 if (viewport.cursorMode)
677 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
681 if (viewport.cursorMode)
683 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
688 viewport.cursorMode = !viewport.cursorMode;
689 statusBar.setText(MessageManager
690 .formatMessage("label.keyboard_editing_mode", new String[]
691 { (viewport.cursorMode ? "on" : "off") }));
692 if (viewport.cursorMode)
694 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
696 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
699 alignPanel.getSeqPanel().seqCanvas.repaint();
705 Help.showHelpWindow();
706 } catch (Exception ex)
708 ex.printStackTrace();
713 boolean toggleSeqs = !evt.isControlDown();
714 boolean toggleCols = !evt.isShiftDown();
715 toggleHiddenRegions(toggleSeqs, toggleCols);
720 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
721 boolean modifyExisting = true; // always modify, don't clear
722 // evt.isShiftDown();
723 boolean invertHighlighted = evt.isAltDown();
724 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
728 case KeyEvent.VK_PAGE_UP:
731 case KeyEvent.VK_PAGE_DOWN:
738 public void keyReleased(KeyEvent evt)
740 switch (evt.getKeyCode())
742 case KeyEvent.VK_LEFT:
743 if (evt.isAltDown() || !viewport.cursorMode)
745 viewport.firePropertyChange("alignment", null,
746 viewport.getAlignment().getSequences());
750 case KeyEvent.VK_RIGHT:
751 if (evt.isAltDown() || !viewport.cursorMode)
753 viewport.firePropertyChange("alignment", null,
754 viewport.getAlignment().getSequences());
762 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
764 ap.alignFrame = this;
765 avc = new jalview.controller.AlignViewController(this, viewport,
770 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
772 int aSize = alignPanels.size();
774 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
776 if (aSize == 1 && ap.av.viewName == null)
778 this.getContentPane().add(ap, BorderLayout.CENTER);
784 setInitialTabVisible();
787 expandViews.setEnabled(true);
788 gatherViews.setEnabled(true);
789 tabbedPane.addTab(ap.av.viewName, ap);
791 ap.setVisible(false);
796 if (ap.av.isPadGaps())
798 ap.av.getAlignment().padGaps();
800 ap.av.updateConservation(ap);
801 ap.av.updateConsensus(ap);
802 ap.av.updateStrucConsensus(ap);
803 ap.av.updateInformation(ap);
807 public void setInitialTabVisible()
809 expandViews.setEnabled(true);
810 gatherViews.setEnabled(true);
811 tabbedPane.setVisible(true);
812 AlignmentPanel first = alignPanels.get(0);
813 tabbedPane.addTab(first.av.viewName, first);
814 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
817 public AlignViewport getViewport()
822 /* Set up intrinsic listeners for dynamically generated GUI bits. */
823 private void addServiceListeners()
825 final java.beans.PropertyChangeListener thisListener;
826 Desktop.instance.addJalviewPropertyChangeListener("services",
827 thisListener = new java.beans.PropertyChangeListener()
830 public void propertyChange(PropertyChangeEvent evt)
832 // // System.out.println("Discoverer property change.");
833 // if (evt.getPropertyName().equals("services"))
835 SwingUtilities.invokeLater(new Runnable()
842 "Rebuild WS Menu for service change");
843 BuildWebServiceMenu();
850 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
853 public void internalFrameClosed(
854 javax.swing.event.InternalFrameEvent evt)
856 // System.out.println("deregistering discoverer listener");
857 Desktop.instance.removeJalviewPropertyChangeListener("services",
859 closeMenuItem_actionPerformed(true);
862 // Finally, build the menu once to get current service state
863 new Thread(new Runnable()
868 BuildWebServiceMenu();
874 * Configure menu items that vary according to whether the alignment is
875 * nucleotide or protein
877 public void setGUINucleotide()
879 AlignmentI al = getViewport().getAlignment();
880 boolean nucleotide = al.isNucleotide();
882 showTranslation.setVisible(nucleotide);
883 showReverse.setVisible(nucleotide);
884 showReverseComplement.setVisible(nucleotide);
885 conservationMenuItem.setEnabled(!nucleotide);
887 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
888 showGroupConservation.setEnabled(!nucleotide);
890 showComplementMenuItem
891 .setText(nucleotide ? MessageManager.getString("label.protein")
892 : MessageManager.getString("label.nucleotide"));
896 * set up menus for the current viewport. This may be called after any
897 * operation that affects the data in the current view (selection changed,
898 * etc) to update the menus to reflect the new state.
901 public void setMenusForViewport()
903 setMenusFromViewport(viewport);
907 * Need to call this method when tabs are selected for multiple views, or when
908 * loading from Jalview2XML.java
913 void setMenusFromViewport(AlignViewport av)
915 padGapsMenuitem.setSelected(av.isPadGaps());
916 colourTextMenuItem.setSelected(av.isShowColourText());
917 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
918 modifyPID.setEnabled(abovePIDThreshold.isSelected());
919 conservationMenuItem.setSelected(av.getConservationSelected());
920 modifyConservation.setEnabled(conservationMenuItem.isSelected());
921 seqLimits.setSelected(av.getShowJVSuffix());
922 idRightAlign.setSelected(av.isRightAlignIds());
923 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
924 renderGapsMenuItem.setSelected(av.isRenderGaps());
925 wrapMenuItem.setSelected(av.getWrapAlignment());
926 scaleAbove.setVisible(av.getWrapAlignment());
927 scaleLeft.setVisible(av.getWrapAlignment());
928 scaleRight.setVisible(av.getWrapAlignment());
929 annotationPanelMenuItem.setState(av.isShowAnnotation());
931 * Show/hide annotations only enabled if annotation panel is shown
933 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
934 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
935 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
936 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
937 viewBoxesMenuItem.setSelected(av.getShowBoxes());
938 viewTextMenuItem.setSelected(av.getShowText());
939 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
940 showGroupConsensus.setSelected(av.isShowGroupConsensus());
941 showGroupConservation.setSelected(av.isShowGroupConservation());
942 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
943 showSequenceLogo.setSelected(av.isShowSequenceLogo());
944 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
945 showInformationHistogram.setSelected(av.isShowInformationHistogram());
946 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
947 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
949 ColourMenuHelper.setColourSelected(colourMenu,
950 av.getGlobalColourScheme());
952 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
953 hiddenMarkers.setState(av.getShowHiddenMarkers());
954 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
955 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
956 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
957 autoCalculate.setSelected(av.autoCalculateConsensus);
958 sortByTree.setSelected(av.sortByTree);
959 listenToViewSelections.setSelected(av.followSelection);
961 showProducts.setEnabled(canShowProducts());
962 setGroovyEnabled(Desktop.getGroovyConsole() != null);
968 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
972 public void setGroovyEnabled(boolean b)
974 runGroovy.setEnabled(b);
977 private IProgressIndicator progressBar;
982 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
985 public void setProgressBar(String message, long id)
987 progressBar.setProgressBar(message, id);
991 public void registerHandler(final long id,
992 final IProgressIndicatorHandler handler)
994 progressBar.registerHandler(id, handler);
999 * @return true if any progress bars are still active
1002 public boolean operationInProgress()
1004 return progressBar.operationInProgress();
1008 public void setStatus(String text)
1010 statusBar.setText(text);
1014 * Added so Castor Mapping file can obtain Jalview Version
1016 public String getVersion()
1018 return jalview.bin.Cache.getProperty("VERSION");
1021 public FeatureRenderer getFeatureRenderer()
1023 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1027 public void fetchSequence_actionPerformed(ActionEvent e)
1029 new jalview.gui.SequenceFetcher(this);
1033 public void addFromFile_actionPerformed(ActionEvent e)
1035 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1039 public void hmmBuildSettings_actionPerformed(ActionEvent e)
1040 throws IOException, InterruptedException
1042 if (!(alignmentIsSufficient(1)))
1046 WsParamSetI set = new HMMERPreset();
1047 List<ArgumentI> args = new ArrayList<>();
1048 ParamDatastoreI store = new HMMERParamStore("hmmalign");
1049 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1051 params.showRunDialog();
1052 new Thread(new HMMBuildThread(this, params.getJobParams())).start();
1053 alignPanel.repaint();
1058 public void hmmAlignSettings_actionPerformed(ActionEvent e)
1059 throws IOException, InterruptedException
1061 if (!(checkForHMM() && alignmentIsSufficient(2)))
1065 WsParamSetI set = new HMMERPreset();
1066 List<ArgumentI> args = new ArrayList<>();
1067 ParamDatastoreI store = new HMMERParamStore("hmmalign");
1068 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1070 params.showRunDialog();
1071 new Thread(new HMMAlignThread(this, true, params.getJobParams()))
1073 alignPanel.repaint();
1077 public void hmmSearchSettings_actionPerformed(ActionEvent e)
1083 WsParamSetI set = new HMMERPreset();
1084 List<ArgumentI> args = new ArrayList<>();
1085 ParamDatastoreI store = new HMMERParamStore("hmmsearch");
1086 WsJobParameters params = new WsJobParameters(new JFrame(), store, set,
1088 params.showRunDialog();
1089 new Thread(new HMMSearchThread(this, true, params.getJobParams()))
1091 alignPanel.repaint();
1095 public void hmmBuildRun_actionPerformed(ActionEvent e)
1096 throws IOException, InterruptedException
1098 if (!alignmentIsSufficient(1))
1102 new Thread(new HMMBuildThread(this, null)).start();
1103 alignPanel.repaint();
1108 public void hmmAlignRun_actionPerformed(ActionEvent e)
1109 throws IOException, InterruptedException
1111 if (!(checkForHMM() && alignmentIsSufficient(2)))
1115 new Thread(new HMMAlignThread(this, true, null))
1117 alignPanel.repaint();
1121 public void hmmSearchRun_actionPerformed(ActionEvent e)
1127 new Thread(new HMMSearchThread(this, true, null))
1129 alignPanel.repaint();
1133 * Checks if the frame has a selected hidden Markov model
1137 private boolean checkForHMM()
1139 if (getSelectedHMM() == null)
1141 JOptionPane.showMessageDialog(this,
1142 MessageManager.getString("warn.no_selected_hmm"));
1149 * Checks if the alignment contains the required number of sequences.
1154 public boolean alignmentIsSufficient(int required)
1156 if (getViewport().getAlignment().getSequences().size() < required)
1158 JOptionPane.showMessageDialog(this,
1159 MessageManager.getString("warn.not_enough_sequences"));
1166 public void addDatabase_actionPerformed(ActionEvent e) throws IOException
1168 if (Cache.getProperty(Preferences.HMMSEARCH_DB_PATHS) == null)
1170 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1171 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, "");
1174 String path = openFileChooser(false);
1175 if (new File(path).exists())
1177 IdentifyFile identifier = new IdentifyFile();
1178 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1179 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1180 || format == FileFormat.Pfam)
1182 String currentDbs = Cache.getProperty(Preferences.HMMSEARCH_DBS);
1183 String currentDbPaths = Cache
1184 .getProperty(Preferences.HMMSEARCH_DB_PATHS);
1185 currentDbPaths += " " + path;
1187 String fileName = StringUtils.getLastToken(path, new String("/"));
1188 Scanner scanner = new Scanner(fileName).useDelimiter(".");
1189 String name = scanner.next();
1191 currentDbs += " " + path; // TODO remove path from file name
1194 Cache.setProperty(Preferences.HMMSEARCH_DB_PATHS, currentDbPaths);
1195 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1199 JOptionPane.showMessageDialog(this,
1200 MessageManager.getString("warn.invalid_format"));
1205 JOptionPane.showMessageDialog(this,
1206 MessageManager.getString("warn.not_enough_sequences"));
1211 * Opens a file chooser
1216 protected String openFileChooser(boolean forFolder)
1218 String choice = null;
1219 JFileChooser chooser = new JFileChooser();
1222 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1224 chooser.setDialogTitle(
1225 MessageManager.getString("label.open_local_file"));
1226 chooser.setToolTipText(MessageManager.getString("action.open"));
1228 int value = chooser.showOpenDialog(this);
1230 if (value == JFileChooser.APPROVE_OPTION)
1232 choice = chooser.getSelectedFile().getPath();
1238 public void reload_actionPerformed(ActionEvent e)
1240 if (fileName != null)
1242 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1243 // originating file's format
1244 // TODO: work out how to recover feature settings for correct view(s) when
1245 // file is reloaded.
1246 if (FileFormat.Jalview.equals(currentFileFormat))
1248 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1249 for (int i = 0; i < frames.length; i++)
1251 if (frames[i] instanceof AlignFrame && frames[i] != this
1252 && ((AlignFrame) frames[i]).fileName != null
1253 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1257 frames[i].setSelected(true);
1258 Desktop.instance.closeAssociatedWindows();
1259 } catch (java.beans.PropertyVetoException ex)
1265 Desktop.instance.closeAssociatedWindows();
1267 FileLoader loader = new FileLoader();
1268 DataSourceType protocol = fileName.startsWith("http:")
1269 ? DataSourceType.URL
1270 : DataSourceType.FILE;
1271 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1275 Rectangle bounds = this.getBounds();
1277 FileLoader loader = new FileLoader();
1278 DataSourceType protocol = fileName.startsWith("http:")
1279 ? DataSourceType.URL
1280 : DataSourceType.FILE;
1281 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1282 protocol, currentFileFormat);
1284 newframe.setBounds(bounds);
1285 if (featureSettings != null && featureSettings.isShowing())
1287 final Rectangle fspos = featureSettings.frame.getBounds();
1288 // TODO: need a 'show feature settings' function that takes bounds -
1289 // need to refactor Desktop.addFrame
1290 newframe.featureSettings_actionPerformed(null);
1291 final FeatureSettings nfs = newframe.featureSettings;
1292 SwingUtilities.invokeLater(new Runnable()
1297 nfs.frame.setBounds(fspos);
1300 this.featureSettings.close();
1301 this.featureSettings = null;
1303 this.closeMenuItem_actionPerformed(true);
1309 public void addFromText_actionPerformed(ActionEvent e)
1312 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1316 public void addFromURL_actionPerformed(ActionEvent e)
1318 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1322 public void save_actionPerformed(ActionEvent e)
1324 if (fileName == null || (currentFileFormat == null)
1325 || fileName.startsWith("http"))
1327 saveAs_actionPerformed(null);
1331 saveAlignment(fileName, currentFileFormat);
1342 public void saveAs_actionPerformed(ActionEvent e)
1344 String format = currentFileFormat == null ? null
1345 : currentFileFormat.getName();
1346 JalviewFileChooser chooser = JalviewFileChooser
1347 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1349 chooser.setFileView(new JalviewFileView());
1350 chooser.setDialogTitle(
1351 MessageManager.getString("label.save_alignment_to_file"));
1352 chooser.setToolTipText(MessageManager.getString("action.save"));
1354 int value = chooser.showSaveDialog(this);
1356 if (value == JalviewFileChooser.APPROVE_OPTION)
1358 currentFileFormat = chooser.getSelectedFormat();
1359 while (currentFileFormat == null)
1361 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1362 MessageManager.getString(
1363 "label.select_file_format_before_saving"),
1364 MessageManager.getString("label.file_format_not_specified"),
1365 JvOptionPane.WARNING_MESSAGE);
1366 currentFileFormat = chooser.getSelectedFormat();
1367 value = chooser.showSaveDialog(this);
1368 if (value != JalviewFileChooser.APPROVE_OPTION)
1374 fileName = chooser.getSelectedFile().getPath();
1376 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1378 Cache.setProperty("LAST_DIRECTORY", fileName);
1379 saveAlignment(fileName, currentFileFormat);
1383 public boolean saveAlignment(String file, FileFormatI format)
1385 boolean success = true;
1387 if (FileFormat.Jalview.equals(format))
1389 String shortName = title;
1391 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1393 shortName = shortName.substring(
1394 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1397 success = new Jalview2XML().saveAlignment(this, file, shortName);
1399 statusBar.setText(MessageManager.formatMessage(
1400 "label.successfully_saved_to_file_in_format", new Object[]
1401 { fileName, format }));
1406 AlignmentExportData exportData = getAlignmentForExport(format,
1408 if (exportData.getSettings().isCancelled())
1412 FormatAdapter f = new FormatAdapter(alignPanel,
1413 exportData.getSettings());
1414 String output = f.formatSequences(format, exportData.getAlignment(), // class
1418 // occur in the distant future
1419 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1420 f.getCacheSuffixDefault(format),
1421 viewport.getAlignment().getHiddenColumns());
1431 PrintWriter out = new PrintWriter(new FileWriter(file));
1435 this.setTitle(file);
1436 statusBar.setText(MessageManager.formatMessage(
1437 "label.successfully_saved_to_file_in_format", new Object[]
1438 { fileName, format.getName() }));
1439 } catch (Exception ex)
1442 ex.printStackTrace();
1449 JvOptionPane.showInternalMessageDialog(this, MessageManager
1450 .formatMessage("label.couldnt_save_file", new Object[]
1452 MessageManager.getString("label.error_saving_file"),
1453 JvOptionPane.WARNING_MESSAGE);
1459 private void warningMessage(String warning, String title)
1461 if (new jalview.util.Platform().isHeadless())
1463 System.err.println("Warning: " + title + "\nWarning: " + warning);
1468 JvOptionPane.showInternalMessageDialog(this, warning, title,
1469 JvOptionPane.WARNING_MESSAGE);
1481 protected void outputText_actionPerformed(ActionEvent e)
1483 FileFormatI fileFormat = FileFormats.getInstance()
1484 .forName(e.getActionCommand());
1485 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1487 if (exportData.getSettings().isCancelled())
1491 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1492 cap.setForInput(null);
1495 FileFormatI format = fileFormat;
1496 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1497 .formatSequences(format, exportData.getAlignment(),
1498 exportData.getOmitHidden(),
1499 exportData.getStartEndPostions(),
1500 viewport.getAlignment().getHiddenColumns()));
1501 Desktop.addInternalFrame(cap, MessageManager
1502 .formatMessage("label.alignment_output_command", new Object[]
1503 { e.getActionCommand() }), 600, 500);
1504 } catch (OutOfMemoryError oom)
1506 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1513 public static AlignmentExportData getAlignmentForExport(
1514 FileFormatI format, AlignViewportI viewport,
1515 AlignExportSettingI exportSettings)
1517 AlignmentI alignmentToExport = null;
1518 AlignExportSettingI settings = exportSettings;
1519 String[] omitHidden = null;
1521 HiddenSequences hiddenSeqs = viewport.getAlignment()
1522 .getHiddenSequences();
1524 alignmentToExport = viewport.getAlignment();
1526 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1527 if (settings == null)
1529 settings = new AlignExportSettings(hasHiddenSeqs,
1530 viewport.hasHiddenColumns(), format);
1532 // settings.isExportAnnotations();
1534 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1536 omitHidden = viewport.getViewAsString(false,
1537 settings.isExportHiddenSequences());
1540 int[] alignmentStartEnd = new int[2];
1541 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1543 alignmentToExport = hiddenSeqs.getFullAlignment();
1547 alignmentToExport = viewport.getAlignment();
1549 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1550 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1551 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1552 omitHidden, alignmentStartEnd, settings);
1563 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1565 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1566 htmlSVG.exportHTML(null);
1570 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1572 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1573 bjs.exportHTML(null);
1576 public void createImageMap(File file, String image)
1578 alignPanel.makePNGImageMap(file, image);
1588 public void createPNG(File f)
1590 alignPanel.makePNG(f);
1600 public void createEPS(File f)
1602 alignPanel.makeEPS(f);
1606 public void createSVG(File f)
1608 alignPanel.makeSVG(f);
1612 public void pageSetup_actionPerformed(ActionEvent e)
1614 PrinterJob printJob = PrinterJob.getPrinterJob();
1615 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1625 public void printMenuItem_actionPerformed(ActionEvent e)
1627 // Putting in a thread avoids Swing painting problems
1628 PrintThread thread = new PrintThread(alignPanel);
1633 public void exportFeatures_actionPerformed(ActionEvent e)
1635 new AnnotationExporter().exportFeatures(alignPanel);
1639 public void exportAnnotations_actionPerformed(ActionEvent e)
1641 new AnnotationExporter().exportAnnotations(alignPanel);
1645 public void associatedData_actionPerformed(ActionEvent e)
1646 throws IOException, InterruptedException
1648 // Pick the tree file
1649 JalviewFileChooser chooser = new JalviewFileChooser(
1650 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1651 chooser.setFileView(new JalviewFileView());
1652 chooser.setDialogTitle(
1653 MessageManager.getString("label.load_jalview_annotations"));
1654 chooser.setToolTipText(
1655 MessageManager.getString("label.load_jalview_annotations"));
1657 int value = chooser.showOpenDialog(null);
1659 if (value == JalviewFileChooser.APPROVE_OPTION)
1661 String choice = chooser.getSelectedFile().getPath();
1662 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1663 loadJalviewDataFile(choice, null, null, null);
1669 * Close the current view or all views in the alignment frame. If the frame
1670 * only contains one view then the alignment will be removed from memory.
1672 * @param closeAllTabs
1675 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1677 if (alignPanels != null && alignPanels.size() < 2)
1679 closeAllTabs = true;
1684 if (alignPanels != null)
1688 if (this.isClosed())
1690 // really close all the windows - otherwise wait till
1691 // setClosed(true) is called
1692 for (int i = 0; i < alignPanels.size(); i++)
1694 AlignmentPanel ap = alignPanels.get(i);
1701 closeView(alignPanel);
1708 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1709 * be called recursively, with the frame now in 'closed' state
1711 this.setClosed(true);
1713 } catch (Exception ex)
1715 ex.printStackTrace();
1720 * Close the specified panel and close up tabs appropriately.
1722 * @param panelToClose
1724 public void closeView(AlignmentPanel panelToClose)
1726 int index = tabbedPane.getSelectedIndex();
1727 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1728 alignPanels.remove(panelToClose);
1729 panelToClose.closePanel();
1730 panelToClose = null;
1732 tabbedPane.removeTabAt(closedindex);
1733 tabbedPane.validate();
1735 if (index > closedindex || index == tabbedPane.getTabCount())
1737 // modify currently selected tab index if necessary.
1741 this.tabSelectionChanged(index);
1747 void updateEditMenuBar()
1750 if (viewport.getHistoryList().size() > 0)
1752 undoMenuItem.setEnabled(true);
1753 CommandI command = viewport.getHistoryList().peek();
1754 undoMenuItem.setText(MessageManager
1755 .formatMessage("label.undo_command", new Object[]
1756 { command.getDescription() }));
1760 undoMenuItem.setEnabled(false);
1761 undoMenuItem.setText(MessageManager.getString("action.undo"));
1764 if (viewport.getRedoList().size() > 0)
1766 redoMenuItem.setEnabled(true);
1768 CommandI command = viewport.getRedoList().peek();
1769 redoMenuItem.setText(MessageManager
1770 .formatMessage("label.redo_command", new Object[]
1771 { command.getDescription() }));
1775 redoMenuItem.setEnabled(false);
1776 redoMenuItem.setText(MessageManager.getString("action.redo"));
1781 public void addHistoryItem(CommandI command)
1783 if (command.getSize() > 0)
1785 viewport.addToHistoryList(command);
1786 viewport.clearRedoList();
1787 updateEditMenuBar();
1788 viewport.updateHiddenColumns();
1789 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1790 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1791 // viewport.getColumnSelection()
1792 // .getHiddenColumns().size() > 0);
1798 * @return alignment objects for all views
1800 AlignmentI[] getViewAlignments()
1802 if (alignPanels != null)
1804 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1806 for (AlignmentPanel ap : alignPanels)
1808 als[i++] = ap.av.getAlignment();
1812 if (viewport != null)
1814 return new AlignmentI[] { viewport.getAlignment() };
1826 protected void undoMenuItem_actionPerformed(ActionEvent e)
1828 if (viewport.getHistoryList().isEmpty())
1832 CommandI command = viewport.getHistoryList().pop();
1833 viewport.addToRedoList(command);
1834 command.undoCommand(getViewAlignments());
1836 AlignmentViewport originalSource = getOriginatingSource(command);
1837 updateEditMenuBar();
1839 if (originalSource != null)
1841 if (originalSource != viewport)
1844 "Implementation worry: mismatch of viewport origin for undo");
1846 originalSource.updateHiddenColumns();
1847 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1849 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1850 // viewport.getColumnSelection()
1851 // .getHiddenColumns().size() > 0);
1852 originalSource.firePropertyChange("alignment", null,
1853 originalSource.getAlignment().getSequences());
1864 protected void redoMenuItem_actionPerformed(ActionEvent e)
1866 if (viewport.getRedoList().size() < 1)
1871 CommandI command = viewport.getRedoList().pop();
1872 viewport.addToHistoryList(command);
1873 command.doCommand(getViewAlignments());
1875 AlignmentViewport originalSource = getOriginatingSource(command);
1876 updateEditMenuBar();
1878 if (originalSource != null)
1881 if (originalSource != viewport)
1884 "Implementation worry: mismatch of viewport origin for redo");
1886 originalSource.updateHiddenColumns();
1887 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1889 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1890 // viewport.getColumnSelection()
1891 // .getHiddenColumns().size() > 0);
1892 originalSource.firePropertyChange("alignment", null,
1893 originalSource.getAlignment().getSequences());
1897 AlignmentViewport getOriginatingSource(CommandI command)
1899 AlignmentViewport originalSource = null;
1900 // For sequence removal and addition, we need to fire
1901 // the property change event FROM the viewport where the
1902 // original alignment was altered
1903 AlignmentI al = null;
1904 if (command instanceof EditCommand)
1906 EditCommand editCommand = (EditCommand) command;
1907 al = editCommand.getAlignment();
1908 List<Component> comps = PaintRefresher.components
1909 .get(viewport.getSequenceSetId());
1911 for (Component comp : comps)
1913 if (comp instanceof AlignmentPanel)
1915 if (al == ((AlignmentPanel) comp).av.getAlignment())
1917 originalSource = ((AlignmentPanel) comp).av;
1924 if (originalSource == null)
1926 // The original view is closed, we must validate
1927 // the current view against the closed view first
1930 PaintRefresher.validateSequences(al, viewport.getAlignment());
1933 originalSource = viewport;
1936 return originalSource;
1945 public void moveSelectedSequences(boolean up)
1947 SequenceGroup sg = viewport.getSelectionGroup();
1953 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1954 viewport.getHiddenRepSequences(), up);
1955 alignPanel.paintAlignment(true);
1958 synchronized void slideSequences(boolean right, int size)
1960 List<SequenceI> sg = new ArrayList<>();
1961 if (viewport.cursorMode)
1963 sg.add(viewport.getAlignment()
1964 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1966 else if (viewport.getSelectionGroup() != null
1967 && viewport.getSelectionGroup().getSize() != viewport
1968 .getAlignment().getHeight())
1970 sg = viewport.getSelectionGroup()
1971 .getSequences(viewport.getHiddenRepSequences());
1979 List<SequenceI> invertGroup = new ArrayList<>();
1981 for (SequenceI seq : viewport.getAlignment().getSequences())
1983 if (!sg.contains(seq))
1985 invertGroup.add(seq);
1989 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1991 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1992 for (int i = 0; i < invertGroup.size(); i++)
1994 seqs2[i] = invertGroup.get(i);
1997 SlideSequencesCommand ssc;
2000 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2001 viewport.getGapCharacter());
2005 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2006 viewport.getGapCharacter());
2009 int groupAdjustment = 0;
2010 if (ssc.getGapsInsertedBegin() && right)
2012 if (viewport.cursorMode)
2014 alignPanel.getSeqPanel().moveCursor(size, 0);
2018 groupAdjustment = size;
2021 else if (!ssc.getGapsInsertedBegin() && !right)
2023 if (viewport.cursorMode)
2025 alignPanel.getSeqPanel().moveCursor(-size, 0);
2029 groupAdjustment = -size;
2033 if (groupAdjustment != 0)
2035 viewport.getSelectionGroup().setStartRes(
2036 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2037 viewport.getSelectionGroup().setEndRes(
2038 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2042 * just extend the last slide command if compatible; but not if in
2043 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2045 boolean appendHistoryItem = false;
2046 Deque<CommandI> historyList = viewport.getHistoryList();
2047 boolean inSplitFrame = getSplitViewContainer() != null;
2048 if (!inSplitFrame && historyList != null && historyList.size() > 0
2049 && historyList.peek() instanceof SlideSequencesCommand)
2051 appendHistoryItem = ssc.appendSlideCommand(
2052 (SlideSequencesCommand) historyList.peek());
2055 if (!appendHistoryItem)
2057 addHistoryItem(ssc);
2070 protected void copy_actionPerformed(ActionEvent e)
2073 if (viewport.getSelectionGroup() == null)
2077 // TODO: preserve the ordering of displayed alignment annotation in any
2078 // internal paste (particularly sequence associated annotation)
2079 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2080 String[] omitHidden = null;
2082 if (viewport.hasHiddenColumns())
2084 omitHidden = viewport.getViewAsString(true);
2087 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2088 seqs, omitHidden, null);
2090 StringSelection ss = new StringSelection(output);
2094 jalview.gui.Desktop.internalCopy = true;
2095 // Its really worth setting the clipboard contents
2096 // to empty before setting the large StringSelection!!
2097 Toolkit.getDefaultToolkit().getSystemClipboard()
2098 .setContents(new StringSelection(""), null);
2100 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2102 } catch (OutOfMemoryError er)
2104 new OOMWarning("copying region", er);
2108 ArrayList<int[]> hiddenColumns = null;
2109 if (viewport.hasHiddenColumns())
2111 hiddenColumns = new ArrayList<>();
2113 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2114 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2115 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
2116 .getHiddenColumns().getHiddenColumnsCopy();
2117 for (int[] region : hiddenRegions)
2120 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
2124 { region[0] - hiddenOffset, region[1] - hiddenOffset });
2129 Desktop.jalviewClipboard = new Object[] { seqs,
2130 viewport.getAlignment().getDataset(), hiddenColumns };
2131 statusBar.setText(MessageManager.formatMessage(
2132 "label.copied_sequences_to_clipboard", new Object[]
2133 { Integer.valueOf(seqs.length).toString() }));
2141 * @throws InterruptedException
2142 * @throws IOException
2145 protected void pasteNew_actionPerformed(ActionEvent e)
2146 throws IOException, InterruptedException
2156 * @throws InterruptedException
2157 * @throws IOException
2160 protected void pasteThis_actionPerformed(ActionEvent e)
2161 throws IOException, InterruptedException
2167 * Paste contents of Jalview clipboard
2169 * @param newAlignment
2170 * true to paste to a new alignment, otherwise add to this.
2171 * @throws InterruptedException
2172 * @throws IOException
2174 void paste(boolean newAlignment) throws IOException, InterruptedException
2176 boolean externalPaste = true;
2179 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2180 Transferable contents = c.getContents(this);
2182 if (contents == null)
2191 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2192 if (str.length() < 1)
2197 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2199 } catch (OutOfMemoryError er)
2201 new OOMWarning("Out of memory pasting sequences!!", er);
2205 SequenceI[] sequences;
2206 boolean annotationAdded = false;
2207 AlignmentI alignment = null;
2209 if (Desktop.jalviewClipboard != null)
2211 // The clipboard was filled from within Jalview, we must use the
2213 // And dataset from the copied alignment
2214 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2215 // be doubly sure that we create *new* sequence objects.
2216 sequences = new SequenceI[newseq.length];
2217 for (int i = 0; i < newseq.length; i++)
2219 sequences[i] = new Sequence(newseq[i]);
2221 alignment = new Alignment(sequences);
2222 externalPaste = false;
2226 // parse the clipboard as an alignment.
2227 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2229 sequences = alignment.getSequencesArray();
2233 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2239 if (Desktop.jalviewClipboard != null)
2241 // dataset is inherited
2242 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2246 // new dataset is constructed
2247 alignment.setDataset(null);
2249 alwidth = alignment.getWidth() + 1;
2253 AlignmentI pastedal = alignment; // preserve pasted alignment object
2254 // Add pasted sequences and dataset into existing alignment.
2255 alignment = viewport.getAlignment();
2256 alwidth = alignment.getWidth() + 1;
2257 // decide if we need to import sequences from an existing dataset
2258 boolean importDs = Desktop.jalviewClipboard != null
2259 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2260 // importDs==true instructs us to copy over new dataset sequences from
2261 // an existing alignment
2262 Vector newDs = (importDs) ? new Vector() : null; // used to create
2263 // minimum dataset set
2265 for (int i = 0; i < sequences.length; i++)
2269 newDs.addElement(null);
2271 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2273 if (importDs && ds != null)
2275 if (!newDs.contains(ds))
2277 newDs.setElementAt(ds, i);
2278 ds = new Sequence(ds);
2279 // update with new dataset sequence
2280 sequences[i].setDatasetSequence(ds);
2284 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2289 // copy and derive new dataset sequence
2290 sequences[i] = sequences[i].deriveSequence();
2291 alignment.getDataset()
2292 .addSequence(sequences[i].getDatasetSequence());
2293 // TODO: avoid creation of duplicate dataset sequences with a
2294 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2296 alignment.addSequence(sequences[i]); // merges dataset
2300 newDs.clear(); // tidy up
2302 if (alignment.getAlignmentAnnotation() != null)
2304 for (AlignmentAnnotation alan : alignment
2305 .getAlignmentAnnotation())
2307 if (alan.graphGroup > fgroup)
2309 fgroup = alan.graphGroup;
2313 if (pastedal.getAlignmentAnnotation() != null)
2315 // Add any annotation attached to alignment.
2316 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2317 for (int i = 0; i < alann.length; i++)
2319 annotationAdded = true;
2320 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2322 AlignmentAnnotation newann = new AlignmentAnnotation(
2324 if (newann.graphGroup > -1)
2326 if (newGraphGroups.size() <= newann.graphGroup
2327 || newGraphGroups.get(newann.graphGroup) == null)
2329 for (int q = newGraphGroups
2330 .size(); q <= newann.graphGroup; q++)
2332 newGraphGroups.add(q, null);
2334 newGraphGroups.set(newann.graphGroup,
2335 new Integer(++fgroup));
2337 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2341 newann.padAnnotation(alwidth);
2342 alignment.addAnnotation(newann);
2352 addHistoryItem(new EditCommand(
2353 MessageManager.getString("label.add_sequences"),
2354 Action.PASTE, sequences, 0, alignment.getWidth(),
2357 // Add any annotations attached to sequences
2358 for (int i = 0; i < sequences.length; i++)
2360 if (sequences[i].getAnnotation() != null)
2362 AlignmentAnnotation newann;
2363 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2365 annotationAdded = true;
2366 newann = sequences[i].getAnnotation()[a];
2367 newann.adjustForAlignment();
2368 newann.padAnnotation(alwidth);
2369 if (newann.graphGroup > -1)
2371 if (newann.graphGroup > -1)
2373 if (newGraphGroups.size() <= newann.graphGroup
2374 || newGraphGroups.get(newann.graphGroup) == null)
2376 for (int q = newGraphGroups
2377 .size(); q <= newann.graphGroup; q++)
2379 newGraphGroups.add(q, null);
2381 newGraphGroups.set(newann.graphGroup,
2382 new Integer(++fgroup));
2384 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2388 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2392 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2400 // propagate alignment changed.
2401 vpRanges.setEndSeq(alignment.getHeight());
2402 if (annotationAdded)
2404 // Duplicate sequence annotation in all views.
2405 AlignmentI[] alview = this.getViewAlignments();
2406 for (int i = 0; i < sequences.length; i++)
2408 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2413 for (int avnum = 0; avnum < alview.length; avnum++)
2415 if (alview[avnum] != alignment)
2417 // duplicate in a view other than the one with input focus
2418 int avwidth = alview[avnum].getWidth() + 1;
2419 // this relies on sann being preserved after we
2420 // modify the sequence's annotation array for each duplication
2421 for (int a = 0; a < sann.length; a++)
2423 AlignmentAnnotation newann = new AlignmentAnnotation(
2425 sequences[i].addAlignmentAnnotation(newann);
2426 newann.padAnnotation(avwidth);
2427 alview[avnum].addAnnotation(newann); // annotation was
2428 // duplicated earlier
2429 // TODO JAL-1145 graphGroups are not updated for sequence
2430 // annotation added to several views. This may cause
2432 alview[avnum].setAnnotationIndex(newann, a);
2437 buildSortByAnnotationScoresMenu();
2439 viewport.firePropertyChange("alignment", null,
2440 alignment.getSequences());
2441 if (alignPanels != null)
2443 for (AlignmentPanel ap : alignPanels)
2445 ap.validateAnnotationDimensions(false);
2450 alignPanel.validateAnnotationDimensions(false);
2456 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2458 String newtitle = new String("Copied sequences");
2460 if (Desktop.jalviewClipboard != null
2461 && Desktop.jalviewClipboard[2] != null)
2463 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2464 for (int[] region : hc)
2466 af.viewport.hideColumns(region[0], region[1]);
2470 // >>>This is a fix for the moment, until a better solution is
2472 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2473 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2474 .getFeatureRenderer());
2476 // TODO: maintain provenance of an alignment, rather than just make the
2477 // title a concatenation of operations.
2480 if (title.startsWith("Copied sequences"))
2486 newtitle = newtitle.concat("- from " + title);
2491 newtitle = new String("Pasted sequences");
2494 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2499 } catch (Exception ex)
2501 ex.printStackTrace();
2502 System.out.println("Exception whilst pasting: " + ex);
2503 // could be anything being pasted in here
2508 protected void expand_newalign(ActionEvent e)
2512 AlignmentI alignment = AlignmentUtils
2513 .expandContext(getViewport().getAlignment(), -1);
2514 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2516 String newtitle = new String("Flanking alignment");
2518 if (Desktop.jalviewClipboard != null
2519 && Desktop.jalviewClipboard[2] != null)
2521 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2522 for (int region[] : hc)
2524 af.viewport.hideColumns(region[0], region[1]);
2528 // >>>This is a fix for the moment, until a better solution is
2530 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2531 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2532 .getFeatureRenderer());
2534 // TODO: maintain provenance of an alignment, rather than just make the
2535 // title a concatenation of operations.
2537 if (title.startsWith("Copied sequences"))
2543 newtitle = newtitle.concat("- from " + title);
2547 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2549 } catch (Exception ex)
2551 ex.printStackTrace();
2552 System.out.println("Exception whilst pasting: " + ex);
2553 // could be anything being pasted in here
2554 } catch (OutOfMemoryError oom)
2556 new OOMWarning("Viewing flanking region of alignment", oom);
2567 protected void cut_actionPerformed(ActionEvent e)
2569 copy_actionPerformed(null);
2570 delete_actionPerformed(null);
2580 protected void delete_actionPerformed(ActionEvent evt)
2583 SequenceGroup sg = viewport.getSelectionGroup();
2590 * If the cut affects all sequences, warn, remove highlighted columns
2592 if (sg.getSize() == viewport.getAlignment().getHeight())
2594 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2595 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2596 if (isEntireAlignWidth)
2598 int confirm = JvOptionPane.showConfirmDialog(this,
2599 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2600 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2601 JvOptionPane.OK_CANCEL_OPTION);
2603 if (confirm == JvOptionPane.CANCEL_OPTION
2604 || confirm == JvOptionPane.CLOSED_OPTION)
2609 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2610 sg.getEndRes() + 1);
2612 SequenceI[] cut = sg.getSequences()
2613 .toArray(new SequenceI[sg.getSize()]);
2615 addHistoryItem(new EditCommand(
2616 MessageManager.getString("label.cut_sequences"), Action.CUT,
2617 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2618 viewport.getAlignment()));
2620 viewport.setSelectionGroup(null);
2621 viewport.sendSelection();
2622 viewport.getAlignment().deleteGroup(sg);
2624 viewport.firePropertyChange("alignment", null,
2625 viewport.getAlignment().getSequences());
2626 if (viewport.getAlignment().getHeight() < 1)
2630 this.setClosed(true);
2631 } catch (Exception ex)
2644 protected void deleteGroups_actionPerformed(ActionEvent e)
2646 if (avc.deleteGroups())
2648 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2649 alignPanel.updateAnnotation();
2650 alignPanel.paintAlignment(true);
2661 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2663 SequenceGroup sg = new SequenceGroup();
2665 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2667 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2670 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2671 viewport.setSelectionGroup(sg);
2672 viewport.sendSelection();
2673 // JAL-2034 - should delegate to
2674 // alignPanel to decide if overview needs
2676 alignPanel.paintAlignment(false);
2677 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2687 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2689 if (viewport.cursorMode)
2691 alignPanel.getSeqPanel().keyboardNo1 = null;
2692 alignPanel.getSeqPanel().keyboardNo2 = null;
2694 viewport.setSelectionGroup(null);
2695 viewport.getColumnSelection().clear();
2696 viewport.setSelectionGroup(null);
2697 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2698 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2699 // JAL-2034 - should delegate to
2700 // alignPanel to decide if overview needs
2702 alignPanel.paintAlignment(false);
2703 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2704 viewport.sendSelection();
2714 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2716 SequenceGroup sg = viewport.getSelectionGroup();
2720 selectAllSequenceMenuItem_actionPerformed(null);
2725 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2727 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2729 // JAL-2034 - should delegate to
2730 // alignPanel to decide if overview needs
2733 alignPanel.paintAlignment(true);
2734 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2735 viewport.sendSelection();
2739 public void invertColSel_actionPerformed(ActionEvent e)
2741 viewport.invertColumnSelection();
2742 alignPanel.paintAlignment(true);
2743 viewport.sendSelection();
2753 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2755 trimAlignment(true);
2765 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2767 trimAlignment(false);
2770 void trimAlignment(boolean trimLeft)
2772 ColumnSelection colSel = viewport.getColumnSelection();
2775 if (!colSel.isEmpty())
2779 column = colSel.getMin();
2783 column = colSel.getMax();
2787 if (viewport.getSelectionGroup() != null)
2789 seqs = viewport.getSelectionGroup()
2790 .getSequencesAsArray(viewport.getHiddenRepSequences());
2794 seqs = viewport.getAlignment().getSequencesArray();
2797 TrimRegionCommand trimRegion;
2800 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2801 column, viewport.getAlignment());
2802 vpRanges.setStartRes(0);
2806 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2807 column, viewport.getAlignment());
2810 statusBar.setText(MessageManager
2811 .formatMessage("label.removed_columns", new String[]
2812 { Integer.valueOf(trimRegion.getSize()).toString() }));
2814 addHistoryItem(trimRegion);
2816 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2818 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2819 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2821 viewport.getAlignment().deleteGroup(sg);
2825 viewport.firePropertyChange("alignment", null,
2826 viewport.getAlignment().getSequences());
2837 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2839 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2842 if (viewport.getSelectionGroup() != null)
2844 seqs = viewport.getSelectionGroup()
2845 .getSequencesAsArray(viewport.getHiddenRepSequences());
2846 start = viewport.getSelectionGroup().getStartRes();
2847 end = viewport.getSelectionGroup().getEndRes();
2851 seqs = viewport.getAlignment().getSequencesArray();
2854 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2855 "Remove Gapped Columns", seqs, start, end,
2856 viewport.getAlignment());
2858 addHistoryItem(removeGapCols);
2860 statusBar.setText(MessageManager
2861 .formatMessage("label.removed_empty_columns", new Object[]
2862 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2864 // This is to maintain viewport position on first residue
2865 // of first sequence
2866 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2867 int startRes = seq.findPosition(vpRanges.getStartRes());
2868 // ShiftList shifts;
2869 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2870 // edit.alColumnChanges=shifts.getInverse();
2871 // if (viewport.hasHiddenColumns)
2872 // viewport.getColumnSelection().compensateForEdits(shifts);
2873 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2874 viewport.firePropertyChange("alignment", null,
2875 viewport.getAlignment().getSequences());
2886 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2888 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2891 if (viewport.getSelectionGroup() != null)
2893 seqs = viewport.getSelectionGroup()
2894 .getSequencesAsArray(viewport.getHiddenRepSequences());
2895 start = viewport.getSelectionGroup().getStartRes();
2896 end = viewport.getSelectionGroup().getEndRes();
2900 seqs = viewport.getAlignment().getSequencesArray();
2903 // This is to maintain viewport position on first residue
2904 // of first sequence
2905 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2906 int startRes = seq.findPosition(vpRanges.getStartRes());
2908 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2909 viewport.getAlignment()));
2911 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2913 viewport.firePropertyChange("alignment", null,
2914 viewport.getAlignment().getSequences());
2925 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2927 viewport.setPadGaps(padGapsMenuitem.isSelected());
2928 viewport.firePropertyChange("alignment", null,
2929 viewport.getAlignment().getSequences());
2939 public void findMenuItem_actionPerformed(ActionEvent e)
2945 * Create a new view of the current alignment.
2948 public void newView_actionPerformed(ActionEvent e)
2950 newView(null, true);
2954 * Creates and shows a new view of the current alignment.
2957 * title of newly created view; if null, one will be generated
2958 * @param copyAnnotation
2959 * if true then duplicate all annnotation, groups and settings
2960 * @return new alignment panel, already displayed.
2962 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2965 * Create a new AlignmentPanel (with its own, new Viewport)
2967 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2969 if (!copyAnnotation)
2972 * remove all groups and annotation except for the automatic stuff
2974 newap.av.getAlignment().deleteAllGroups();
2975 newap.av.getAlignment().deleteAllAnnotations(false);
2978 newap.av.setGatherViewsHere(false);
2980 if (viewport.viewName == null)
2982 viewport.viewName = MessageManager
2983 .getString("label.view_name_original");
2987 * Views share the same edits undo and redo stacks
2989 newap.av.setHistoryList(viewport.getHistoryList());
2990 newap.av.setRedoList(viewport.getRedoList());
2993 * Views share the same mappings; need to deregister any new mappings
2994 * created by copyAlignPanel, and register the new reference to the shared
2997 newap.av.replaceMappings(viewport.getAlignment());
3000 * start up cDNA consensus (if applicable) now mappings are in place
3002 if (newap.av.initComplementConsensus())
3004 newap.refresh(true); // adjust layout of annotations
3007 newap.av.viewName = getNewViewName(viewTitle);
3009 addAlignmentPanel(newap, true);
3010 newap.alignmentChanged();
3012 if (alignPanels.size() == 2)
3014 viewport.setGatherViewsHere(true);
3016 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3021 * Make a new name for the view, ensuring it is unique within the current
3022 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3023 * these now use viewId. Unique view names are still desirable for usability.)
3028 protected String getNewViewName(String viewTitle)
3030 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3031 boolean addFirstIndex = false;
3032 if (viewTitle == null || viewTitle.trim().length() == 0)
3034 viewTitle = MessageManager.getString("action.view");
3035 addFirstIndex = true;
3039 index = 1;// we count from 1 if given a specific name
3041 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3043 List<Component> comps = PaintRefresher.components
3044 .get(viewport.getSequenceSetId());
3046 List<String> existingNames = getExistingViewNames(comps);
3048 while (existingNames.contains(newViewName))
3050 newViewName = viewTitle + " " + (++index);
3056 * Returns a list of distinct view names found in the given list of
3057 * components. View names are held on the viewport of an AlignmentPanel.
3062 protected List<String> getExistingViewNames(List<Component> comps)
3064 List<String> existingNames = new ArrayList<>();
3065 for (Component comp : comps)
3067 if (comp instanceof AlignmentPanel)
3069 AlignmentPanel ap = (AlignmentPanel) comp;
3070 if (!existingNames.contains(ap.av.viewName))
3072 existingNames.add(ap.av.viewName);
3076 return existingNames;
3080 * Explode tabbed views into separate windows.
3083 public void expandViews_actionPerformed(ActionEvent e)
3085 Desktop.explodeViews(this);
3089 * Gather views in separate windows back into a tabbed presentation.
3092 public void gatherViews_actionPerformed(ActionEvent e)
3094 Desktop.instance.gatherViews(this);
3104 public void font_actionPerformed(ActionEvent e)
3106 new FontChooser(alignPanel);
3116 protected void seqLimit_actionPerformed(ActionEvent e)
3118 viewport.setShowJVSuffix(seqLimits.isSelected());
3120 alignPanel.getIdPanel().getIdCanvas()
3121 .setPreferredSize(alignPanel.calculateIdWidth());
3122 alignPanel.paintAlignment(true);
3126 public void idRightAlign_actionPerformed(ActionEvent e)
3128 viewport.setRightAlignIds(idRightAlign.isSelected());
3129 alignPanel.paintAlignment(true);
3133 public void centreColumnLabels_actionPerformed(ActionEvent e)
3135 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3136 alignPanel.paintAlignment(true);
3142 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3145 protected void followHighlight_actionPerformed()
3148 * Set the 'follow' flag on the Viewport (and scroll to position if now
3151 final boolean state = this.followHighlightMenuItem.getState();
3152 viewport.setFollowHighlight(state);
3155 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
3166 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3168 viewport.setColourText(colourTextMenuItem.isSelected());
3169 alignPanel.paintAlignment(true);
3179 public void wrapMenuItem_actionPerformed(ActionEvent e)
3181 scaleAbove.setVisible(wrapMenuItem.isSelected());
3182 scaleLeft.setVisible(wrapMenuItem.isSelected());
3183 scaleRight.setVisible(wrapMenuItem.isSelected());
3184 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3185 alignPanel.updateLayout();
3189 public void showAllSeqs_actionPerformed(ActionEvent e)
3191 viewport.showAllHiddenSeqs();
3195 public void showAllColumns_actionPerformed(ActionEvent e)
3197 viewport.showAllHiddenColumns();
3198 alignPanel.paintAlignment(true);
3199 viewport.sendSelection();
3203 public void hideSelSequences_actionPerformed(ActionEvent e)
3205 viewport.hideAllSelectedSeqs();
3209 * called by key handler and the hide all/show all menu items
3214 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3217 boolean hide = false;
3218 SequenceGroup sg = viewport.getSelectionGroup();
3219 if (!toggleSeqs && !toggleCols)
3221 // Hide everything by the current selection - this is a hack - we do the
3222 // invert and then hide
3223 // first check that there will be visible columns after the invert.
3224 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3225 && sg.getStartRes() <= sg.getEndRes()))
3227 // now invert the sequence set, if required - empty selection implies
3228 // that no hiding is required.
3231 invertSequenceMenuItem_actionPerformed(null);
3232 sg = viewport.getSelectionGroup();
3236 viewport.expandColSelection(sg, true);
3237 // finally invert the column selection and get the new sequence
3239 invertColSel_actionPerformed(null);
3246 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3248 hideSelSequences_actionPerformed(null);
3251 else if (!(toggleCols && viewport.hasSelectedColumns()))
3253 showAllSeqs_actionPerformed(null);
3259 if (viewport.hasSelectedColumns())
3261 hideSelColumns_actionPerformed(null);
3264 viewport.setSelectionGroup(sg);
3269 showAllColumns_actionPerformed(null);
3278 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3279 * event.ActionEvent)
3282 public void hideAllButSelection_actionPerformed(ActionEvent e)
3284 toggleHiddenRegions(false, false);
3285 viewport.sendSelection();
3292 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3296 public void hideAllSelection_actionPerformed(ActionEvent e)
3298 SequenceGroup sg = viewport.getSelectionGroup();
3299 viewport.expandColSelection(sg, false);
3300 viewport.hideAllSelectedSeqs();
3301 viewport.hideSelectedColumns();
3302 alignPanel.paintAlignment(true);
3303 viewport.sendSelection();
3310 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3314 public void showAllhidden_actionPerformed(ActionEvent e)
3316 viewport.showAllHiddenColumns();
3317 viewport.showAllHiddenSeqs();
3318 alignPanel.paintAlignment(true);
3319 viewport.sendSelection();
3323 public void hideSelColumns_actionPerformed(ActionEvent e)
3325 viewport.hideSelectedColumns();
3326 alignPanel.paintAlignment(true);
3327 viewport.sendSelection();
3331 public void hiddenMarkers_actionPerformed(ActionEvent e)
3333 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3344 protected void scaleAbove_actionPerformed(ActionEvent e)
3346 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3347 alignPanel.paintAlignment(true);
3357 protected void scaleLeft_actionPerformed(ActionEvent e)
3359 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3360 alignPanel.paintAlignment(true);
3370 protected void scaleRight_actionPerformed(ActionEvent e)
3372 viewport.setScaleRightWrapped(scaleRight.isSelected());
3373 alignPanel.paintAlignment(true);
3383 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3385 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3386 alignPanel.paintAlignment(true);
3396 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3398 viewport.setShowText(viewTextMenuItem.isSelected());
3399 alignPanel.paintAlignment(true);
3409 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3411 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3412 alignPanel.paintAlignment(true);
3415 public FeatureSettings featureSettings;
3418 public FeatureSettingsControllerI getFeatureSettingsUI()
3420 return featureSettings;
3424 public void featureSettings_actionPerformed(ActionEvent e)
3426 if (featureSettings != null)
3428 featureSettings.close();
3429 featureSettings = null;
3431 if (!showSeqFeatures.isSelected())
3433 // make sure features are actually displayed
3434 showSeqFeatures.setSelected(true);
3435 showSeqFeatures_actionPerformed(null);
3437 featureSettings = new FeatureSettings(this);
3441 * Set or clear 'Show Sequence Features'
3447 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3449 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3450 alignPanel.paintAlignment(true);
3454 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3455 * the annotations panel as a whole.
3457 * The options to show/hide all annotations should be enabled when the panel
3458 * is shown, and disabled when the panel is hidden.
3463 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3465 final boolean setVisible = annotationPanelMenuItem.isSelected();
3466 viewport.setShowAnnotation(setVisible);
3467 this.showAllSeqAnnotations.setEnabled(setVisible);
3468 this.hideAllSeqAnnotations.setEnabled(setVisible);
3469 this.showAllAlAnnotations.setEnabled(setVisible);
3470 this.hideAllAlAnnotations.setEnabled(setVisible);
3471 alignPanel.updateLayout();
3475 public void alignmentProperties()
3477 JEditorPane editPane = new JEditorPane("text/html", "");
3478 editPane.setEditable(false);
3479 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3482 MessageManager.formatMessage("label.html_content", new Object[]
3483 { contents.toString() }));
3484 JInternalFrame frame = new JInternalFrame();
3485 frame.getContentPane().add(new JScrollPane(editPane));
3487 Desktop.addInternalFrame(frame, MessageManager
3488 .formatMessage("label.alignment_properties", new Object[]
3489 { getTitle() }), 500, 400);
3499 public void overviewMenuItem_actionPerformed(ActionEvent e)
3501 if (alignPanel.overviewPanel != null)
3506 JInternalFrame frame = new JInternalFrame();
3507 final OverviewPanel overview = new OverviewPanel(alignPanel);
3508 frame.setContentPane(overview);
3509 Desktop.addInternalFrame(frame, MessageManager
3510 .formatMessage("label.overview_params", new Object[]
3511 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3514 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3515 frame.addInternalFrameListener(
3516 new javax.swing.event.InternalFrameAdapter()
3519 public void internalFrameClosed(
3520 javax.swing.event.InternalFrameEvent evt)
3523 alignPanel.setOverviewPanel(null);
3527 alignPanel.setOverviewPanel(overview);
3531 public void textColour_actionPerformed()
3533 new TextColourChooser().chooseColour(alignPanel, null);
3537 * public void covariationColour_actionPerformed() {
3539 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3543 public void annotationColour_actionPerformed()
3545 new AnnotationColourChooser(viewport, alignPanel);
3549 public void annotationColumn_actionPerformed(ActionEvent e)
3551 new AnnotationColumnChooser(viewport, alignPanel);
3555 * Action on the user checking or unchecking the option to apply the selected
3556 * colour scheme to all groups. If unchecked, groups may have their own
3557 * independent colour schemes.
3562 public void applyToAllGroups_actionPerformed(boolean selected)
3564 viewport.setColourAppliesToAllGroups(selected);
3568 * Action on user selecting a colour from the colour menu
3571 * the name (not the menu item label!) of the colour scheme
3574 public void changeColour_actionPerformed(String name)
3577 * 'User Defined' opens a panel to configure or load a
3578 * user-defined colour scheme
3580 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3582 new UserDefinedColours(alignPanel);
3587 * otherwise set the chosen colour scheme (or null for 'None')
3589 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3590 viewport.getAlignment(), viewport.getHiddenRepSequences());
3595 * Actions on setting or changing the alignment colour scheme
3600 public void changeColour(ColourSchemeI cs)
3602 // TODO: pull up to controller method
3603 ColourMenuHelper.setColourSelected(colourMenu, cs);
3605 viewport.setGlobalColourScheme(cs);
3607 alignPanel.paintAlignment(true);
3611 * Show the PID threshold slider panel
3614 protected void modifyPID_actionPerformed()
3616 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3617 alignPanel.getViewName());
3618 SliderPanel.showPIDSlider();
3622 * Show the Conservation slider panel
3625 protected void modifyConservation_actionPerformed()
3627 SliderPanel.setConservationSlider(alignPanel,
3628 viewport.getResidueShading(), alignPanel.getViewName());
3629 SliderPanel.showConservationSlider();
3633 * Action on selecting or deselecting (Colour) By Conservation
3636 public void conservationMenuItem_actionPerformed(boolean selected)
3638 modifyConservation.setEnabled(selected);
3639 viewport.setConservationSelected(selected);
3640 viewport.getResidueShading().setConservationApplied(selected);
3642 changeColour(viewport.getGlobalColourScheme());
3645 modifyConservation_actionPerformed();
3649 SliderPanel.hideConservationSlider();
3654 * Action on selecting or deselecting (Colour) Above PID Threshold
3657 public void abovePIDThreshold_actionPerformed(boolean selected)
3659 modifyPID.setEnabled(selected);
3660 viewport.setAbovePIDThreshold(selected);
3663 viewport.getResidueShading().setThreshold(0,
3664 viewport.isIgnoreGapsConsensus());
3667 changeColour(viewport.getGlobalColourScheme());
3670 modifyPID_actionPerformed();
3674 SliderPanel.hidePIDSlider();
3685 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3687 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3688 AlignmentSorter.sortByPID(viewport.getAlignment(),
3689 viewport.getAlignment().getSequenceAt(0));
3690 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3691 viewport.getAlignment()));
3692 alignPanel.paintAlignment(true);
3702 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3704 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3705 AlignmentSorter.sortByID(viewport.getAlignment());
3707 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3708 alignPanel.paintAlignment(true);
3718 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3720 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3721 AlignmentSorter.sortByLength(viewport.getAlignment());
3722 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3723 viewport.getAlignment()));
3724 alignPanel.paintAlignment(true);
3734 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3736 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3737 AlignmentSorter.sortByGroup(viewport.getAlignment());
3738 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3739 viewport.getAlignment()));
3741 alignPanel.paintAlignment(true);
3751 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3753 new RedundancyPanel(alignPanel, this);
3763 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3765 if ((viewport.getSelectionGroup() == null)
3766 || (viewport.getSelectionGroup().getSize() < 2))
3768 JvOptionPane.showInternalMessageDialog(this,
3769 MessageManager.getString(
3770 "label.you_must_select_least_two_sequences"),
3771 MessageManager.getString("label.invalid_selection"),
3772 JvOptionPane.WARNING_MESSAGE);
3776 JInternalFrame frame = new JInternalFrame();
3777 frame.setContentPane(new PairwiseAlignPanel(viewport));
3778 Desktop.addInternalFrame(frame,
3779 MessageManager.getString("action.pairwise_alignment"), 600,
3785 public void autoCalculate_actionPerformed(ActionEvent e)
3787 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3788 if (viewport.autoCalculateConsensus)
3790 viewport.firePropertyChange("alignment", null,
3791 viewport.getAlignment().getSequences());
3796 public void sortByTreeOption_actionPerformed(ActionEvent e)
3798 viewport.sortByTree = sortByTree.isSelected();
3802 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3804 viewport.followSelection = listenToViewSelections.isSelected();
3808 * Constructs a tree panel and adds it to the desktop
3811 * tree type (NJ or AV)
3813 * name of score model used to compute the tree
3815 * parameters for the distance or similarity calculation
3817 void newTreePanel(String type, String modelName,
3818 SimilarityParamsI options)
3820 String frameTitle = "";
3823 boolean onSelection = false;
3824 if (viewport.getSelectionGroup() != null
3825 && viewport.getSelectionGroup().getSize() > 0)
3827 SequenceGroup sg = viewport.getSelectionGroup();
3829 /* Decide if the selection is a column region */
3830 for (SequenceI _s : sg.getSequences())
3832 if (_s.getLength() < sg.getEndRes())
3834 JvOptionPane.showMessageDialog(Desktop.desktop,
3835 MessageManager.getString(
3836 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3837 MessageManager.getString(
3838 "label.sequences_selection_not_aligned"),
3839 JvOptionPane.WARNING_MESSAGE);
3848 if (viewport.getAlignment().getHeight() < 2)
3854 tp = new TreePanel(alignPanel, type, modelName, options);
3855 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3857 frameTitle += " from ";
3859 if (viewport.viewName != null)
3861 frameTitle += viewport.viewName + " of ";
3864 frameTitle += this.title;
3866 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3877 public void addSortByOrderMenuItem(String title,
3878 final AlignmentOrder order)
3880 final JMenuItem item = new JMenuItem(MessageManager
3881 .formatMessage("action.by_title_param", new Object[]
3884 item.addActionListener(new java.awt.event.ActionListener()
3887 public void actionPerformed(ActionEvent e)
3889 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3891 // TODO: JBPNote - have to map order entries to curent SequenceI
3893 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3895 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3896 viewport.getAlignment()));
3898 alignPanel.paintAlignment(true);
3904 * Add a new sort by annotation score menu item
3907 * the menu to add the option to
3909 * the label used to retrieve scores for each sequence on the
3912 public void addSortByAnnotScoreMenuItem(JMenu sort,
3913 final String scoreLabel)
3915 final JMenuItem item = new JMenuItem(scoreLabel);
3917 item.addActionListener(new java.awt.event.ActionListener()
3920 public void actionPerformed(ActionEvent e)
3922 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3923 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3924 viewport.getAlignment());// ,viewport.getSelectionGroup());
3925 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3926 viewport.getAlignment()));
3927 alignPanel.paintAlignment(true);
3933 * last hash for alignment's annotation array - used to minimise cost of
3936 protected int _annotationScoreVectorHash;
3939 * search the alignment and rebuild the sort by annotation score submenu the
3940 * last alignment annotation vector hash is stored to minimize cost of
3941 * rebuilding in subsequence calls.
3945 public void buildSortByAnnotationScoresMenu()
3947 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3952 if (viewport.getAlignment().getAlignmentAnnotation()
3953 .hashCode() != _annotationScoreVectorHash)
3955 sortByAnnotScore.removeAll();
3956 // almost certainly a quicker way to do this - but we keep it simple
3957 Hashtable scoreSorts = new Hashtable();
3958 AlignmentAnnotation aann[];
3959 for (SequenceI sqa : viewport.getAlignment().getSequences())
3961 aann = sqa.getAnnotation();
3962 for (int i = 0; aann != null && i < aann.length; i++)
3964 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3966 scoreSorts.put(aann[i].label, aann[i].label);
3970 Enumeration labels = scoreSorts.keys();
3971 while (labels.hasMoreElements())
3973 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3974 (String) labels.nextElement());
3976 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3979 _annotationScoreVectorHash = viewport.getAlignment()
3980 .getAlignmentAnnotation().hashCode();
3985 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3986 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3987 * call. Listeners are added to remove the menu item when the treePanel is
3988 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3992 public void buildTreeSortMenu()
3994 sortByTreeMenu.removeAll();
3996 List<Component> comps = PaintRefresher.components
3997 .get(viewport.getSequenceSetId());
3998 List<TreePanel> treePanels = new ArrayList<>();
3999 for (Component comp : comps)
4001 if (comp instanceof TreePanel)
4003 treePanels.add((TreePanel) comp);
4007 if (treePanels.size() < 1)
4009 sortByTreeMenu.setVisible(false);
4013 sortByTreeMenu.setVisible(true);
4015 for (final TreePanel tp : treePanels)
4017 final JMenuItem item = new JMenuItem(tp.getTitle());
4018 item.addActionListener(new java.awt.event.ActionListener()
4021 public void actionPerformed(ActionEvent e)
4023 tp.sortByTree_actionPerformed();
4024 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4029 sortByTreeMenu.add(item);
4033 public boolean sortBy(AlignmentOrder alorder, String undoname)
4035 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4036 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4037 if (undoname != null)
4039 addHistoryItem(new OrderCommand(undoname, oldOrder,
4040 viewport.getAlignment()));
4042 alignPanel.paintAlignment(true);
4047 * Work out whether the whole set of sequences or just the selected set will
4048 * be submitted for multiple alignment.
4051 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4053 // Now, check we have enough sequences
4054 AlignmentView msa = null;
4056 if ((viewport.getSelectionGroup() != null)
4057 && (viewport.getSelectionGroup().getSize() > 1))
4059 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4060 // some common interface!
4062 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4063 * SequenceI[sz = seqs.getSize(false)];
4065 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4066 * seqs.getSequenceAt(i); }
4068 msa = viewport.getAlignmentView(true);
4070 else if (viewport.getSelectionGroup() != null
4071 && viewport.getSelectionGroup().getSize() == 1)
4073 int option = JvOptionPane.showConfirmDialog(this,
4074 MessageManager.getString("warn.oneseq_msainput_selection"),
4075 MessageManager.getString("label.invalid_selection"),
4076 JvOptionPane.OK_CANCEL_OPTION);
4077 if (option == JvOptionPane.OK_OPTION)
4079 msa = viewport.getAlignmentView(false);
4084 msa = viewport.getAlignmentView(false);
4090 * Decides what is submitted to a secondary structure prediction service: the
4091 * first sequence in the alignment, or in the current selection, or, if the
4092 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4093 * region or the whole alignment. (where the first sequence in the set is the
4094 * one that the prediction will be for).
4096 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4098 AlignmentView seqs = null;
4100 if ((viewport.getSelectionGroup() != null)
4101 && (viewport.getSelectionGroup().getSize() > 0))
4103 seqs = viewport.getAlignmentView(true);
4107 seqs = viewport.getAlignmentView(false);
4109 // limit sequences - JBPNote in future - could spawn multiple prediction
4111 // TODO: viewport.getAlignment().isAligned is a global state - the local
4112 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4113 if (!viewport.getAlignment().isAligned(false))
4115 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4116 // TODO: if seqs.getSequences().length>1 then should really have warned
4130 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4132 // Pick the tree file
4133 JalviewFileChooser chooser = new JalviewFileChooser(
4134 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4135 chooser.setFileView(new JalviewFileView());
4136 chooser.setDialogTitle(
4137 MessageManager.getString("label.select_newick_like_tree_file"));
4138 chooser.setToolTipText(
4139 MessageManager.getString("label.load_tree_file"));
4141 int value = chooser.showOpenDialog(null);
4143 if (value == JalviewFileChooser.APPROVE_OPTION)
4145 String filePath = chooser.getSelectedFile().getPath();
4146 Cache.setProperty("LAST_DIRECTORY", filePath);
4147 NewickFile fin = null;
4150 fin = new NewickFile(filePath, DataSourceType.FILE);
4151 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4152 } catch (Exception ex)
4154 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4155 MessageManager.getString("label.problem_reading_tree_file"),
4156 JvOptionPane.WARNING_MESSAGE);
4157 ex.printStackTrace();
4159 if (fin != null && fin.hasWarningMessage())
4161 JvOptionPane.showMessageDialog(Desktop.desktop,
4162 fin.getWarningMessage(),
4164 .getString("label.possible_problem_with_tree_file"),
4165 JvOptionPane.WARNING_MESSAGE);
4170 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4172 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4175 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4176 int h, int x, int y)
4178 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4182 * Add a treeviewer for the tree extracted from a Newick file object to the
4183 * current alignment view
4190 * Associated alignment input data (or null)
4199 * @return TreePanel handle
4201 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4202 AlignmentView input, int w, int h, int x, int y)
4204 TreePanel tp = null;
4210 if (nf.getTree() != null)
4212 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4218 tp.setLocation(x, y);
4221 Desktop.addInternalFrame(tp, treeTitle, w, h);
4223 } catch (Exception ex)
4225 ex.printStackTrace();
4231 private boolean buildingMenu = false;
4234 * Generates menu items and listener event actions for web service clients
4237 public void BuildWebServiceMenu()
4239 while (buildingMenu)
4243 System.err.println("Waiting for building menu to finish.");
4245 } catch (Exception e)
4249 final AlignFrame me = this;
4250 buildingMenu = true;
4251 new Thread(new Runnable()
4256 final List<JMenuItem> legacyItems = new ArrayList<>();
4259 // System.err.println("Building ws menu again "
4260 // + Thread.currentThread());
4261 // TODO: add support for context dependent disabling of services based
4263 // alignment and current selection
4264 // TODO: add additional serviceHandle parameter to specify abstract
4266 // class independently of AbstractName
4267 // TODO: add in rediscovery GUI function to restart discoverer
4268 // TODO: group services by location as well as function and/or
4270 // object broker mechanism.
4271 final Vector<JMenu> wsmenu = new Vector<>();
4272 final IProgressIndicator af = me;
4275 * do not i18n these strings - they are hard-coded in class
4276 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4277 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4279 final JMenu msawsmenu = new JMenu("Alignment");
4280 final JMenu secstrmenu = new JMenu(
4281 "Secondary Structure Prediction");
4282 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4283 final JMenu analymenu = new JMenu("Analysis");
4284 final JMenu dismenu = new JMenu("Protein Disorder");
4285 // JAL-940 - only show secondary structure prediction services from
4286 // the legacy server
4287 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4289 Discoverer.services != null && (Discoverer.services.size() > 0))
4291 // TODO: refactor to allow list of AbstractName/Handler bindings to
4293 // stored or retrieved from elsewhere
4294 // No MSAWS used any more:
4295 // Vector msaws = null; // (Vector)
4296 // Discoverer.services.get("MsaWS");
4297 Vector secstrpr = (Vector) Discoverer.services
4299 if (secstrpr != null)
4301 // Add any secondary structure prediction services
4302 for (int i = 0, j = secstrpr.size(); i < j; i++)
4304 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4306 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4307 .getServiceClient(sh);
4308 int p = secstrmenu.getItemCount();
4309 impl.attachWSMenuEntry(secstrmenu, me);
4310 int q = secstrmenu.getItemCount();
4311 for (int litm = p; litm < q; litm++)
4313 legacyItems.add(secstrmenu.getItem(litm));
4319 // Add all submenus in the order they should appear on the web
4321 wsmenu.add(msawsmenu);
4322 wsmenu.add(secstrmenu);
4323 wsmenu.add(dismenu);
4324 wsmenu.add(analymenu);
4325 // No search services yet
4326 // wsmenu.add(seqsrchmenu);
4328 javax.swing.SwingUtilities.invokeLater(new Runnable()
4335 webService.removeAll();
4336 // first, add discovered services onto the webservices menu
4337 if (wsmenu.size() > 0)
4339 for (int i = 0, j = wsmenu.size(); i < j; i++)
4341 webService.add(wsmenu.get(i));
4346 webService.add(me.webServiceNoServices);
4348 // TODO: move into separate menu builder class.
4349 boolean new_sspred = false;
4350 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4352 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4353 if (jws2servs != null)
4355 if (jws2servs.hasServices())
4357 jws2servs.attachWSMenuEntry(webService, me);
4358 for (Jws2Instance sv : jws2servs.getServices())
4360 if (sv.description.toLowerCase().contains("jpred"))
4362 for (JMenuItem jmi : legacyItems)
4364 jmi.setVisible(false);
4370 if (jws2servs.isRunning())
4372 JMenuItem tm = new JMenuItem(
4373 "Still discovering JABA Services");
4374 tm.setEnabled(false);
4379 build_urlServiceMenu(me.webService);
4380 build_fetchdbmenu(webService);
4381 for (JMenu item : wsmenu)
4383 if (item.getItemCount() == 0)
4385 item.setEnabled(false);
4389 item.setEnabled(true);
4392 } catch (Exception e)
4395 "Exception during web service menu building process.",
4400 } catch (Exception e)
4403 buildingMenu = false;
4410 * construct any groupURL type service menu entries.
4414 private void build_urlServiceMenu(JMenu webService)
4416 // TODO: remove this code when 2.7 is released
4417 // DEBUG - alignmentView
4419 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4420 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4422 * @Override public void actionPerformed(ActionEvent e) {
4423 * jalview.datamodel.AlignmentView
4424 * .testSelectionViews(af.viewport.getAlignment(),
4425 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4427 * }); webService.add(testAlView);
4429 // TODO: refactor to RestClient discoverer and merge menu entries for
4430 // rest-style services with other types of analysis/calculation service
4431 // SHmmr test client - still being implemented.
4432 // DEBUG - alignmentView
4434 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4437 client.attachWSMenuEntry(
4438 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4444 * Searches the alignment sequences for xRefs and builds the Show
4445 * Cross-References menu (formerly called Show Products), with database
4446 * sources for which cross-references are found (protein sources for a
4447 * nucleotide alignment and vice versa)
4449 * @return true if Show Cross-references menu should be enabled
4451 public boolean canShowProducts()
4453 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4454 AlignmentI dataset = viewport.getAlignment().getDataset();
4456 showProducts.removeAll();
4457 final boolean dna = viewport.getAlignment().isNucleotide();
4459 if (seqs == null || seqs.length == 0)
4461 // nothing to see here.
4465 boolean showp = false;
4468 List<String> ptypes = new CrossRef(seqs, dataset)
4469 .findXrefSourcesForSequences(dna);
4471 for (final String source : ptypes)
4474 final AlignFrame af = this;
4475 JMenuItem xtype = new JMenuItem(source);
4476 xtype.addActionListener(new ActionListener()
4479 public void actionPerformed(ActionEvent e)
4481 showProductsFor(af.viewport.getSequenceSelection(), dna,
4485 showProducts.add(xtype);
4487 showProducts.setVisible(showp);
4488 showProducts.setEnabled(showp);
4489 } catch (Exception e)
4492 "canShowProducts threw an exception - please report to help@jalview.org",
4500 * Finds and displays cross-references for the selected sequences (protein
4501 * products for nucleotide sequences, dna coding sequences for peptides).
4504 * the sequences to show cross-references for
4506 * true if from a nucleotide alignment (so showing proteins)
4508 * the database to show cross-references for
4510 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4511 final String source)
4513 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4518 * Construct and display a new frame containing the translation of this
4519 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4522 public void showTranslation_actionPerformed(ActionEvent e)
4524 AlignmentI al = null;
4527 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4529 al = dna.translateCdna();
4530 } catch (Exception ex)
4532 jalview.bin.Cache.log.error(
4533 "Exception during translation. Please report this !", ex);
4534 final String msg = MessageManager.getString(
4535 "label.error_when_translating_sequences_submit_bug_report");
4536 final String errorTitle = MessageManager
4537 .getString("label.implementation_error")
4538 + MessageManager.getString("label.translation_failed");
4539 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4540 JvOptionPane.ERROR_MESSAGE);
4543 if (al == null || al.getHeight() == 0)
4545 final String msg = MessageManager.getString(
4546 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4547 final String errorTitle = MessageManager
4548 .getString("label.translation_failed");
4549 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4550 JvOptionPane.WARNING_MESSAGE);
4554 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4555 af.setFileFormat(this.currentFileFormat);
4556 final String newTitle = MessageManager
4557 .formatMessage("label.translation_of_params", new Object[]
4558 { this.getTitle() });
4559 af.setTitle(newTitle);
4560 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4562 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4563 viewport.openSplitFrame(af, new Alignment(seqs));
4567 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4574 * Set the file format
4578 public void setFileFormat(FileFormatI format)
4580 this.currentFileFormat = format;
4584 * Try to load a features file onto the alignment.
4587 * contents or path to retrieve file
4589 * access mode of file (see jalview.io.AlignFile)
4590 * @return true if features file was parsed correctly.
4592 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4594 return avc.parseFeaturesFile(file, sourceType,
4595 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4600 public void refreshFeatureUI(boolean enableIfNecessary)
4602 // note - currently this is only still here rather than in the controller
4603 // because of the featureSettings hard reference that is yet to be
4605 if (enableIfNecessary)
4607 viewport.setShowSequenceFeatures(true);
4608 showSeqFeatures.setSelected(true);
4614 public void dragEnter(DropTargetDragEvent evt)
4619 public void dragExit(DropTargetEvent evt)
4624 public void dragOver(DropTargetDragEvent evt)
4629 public void dropActionChanged(DropTargetDragEvent evt)
4634 public void drop(DropTargetDropEvent evt)
4636 // JAL-1552 - acceptDrop required before getTransferable call for
4637 // Java's Transferable for native dnd
4638 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4639 Transferable t = evt.getTransferable();
4640 List<String> files = new ArrayList<>();
4641 List<DataSourceType> protocols = new ArrayList<>();
4645 Desktop.transferFromDropTarget(files, protocols, evt, t);
4646 } catch (Exception e)
4648 e.printStackTrace();
4654 // check to see if any of these files have names matching sequences in
4656 SequenceIdMatcher idm = new SequenceIdMatcher(
4657 viewport.getAlignment().getSequencesArray());
4659 * Object[] { String,SequenceI}
4661 ArrayList<Object[]> filesmatched = new ArrayList<>();
4662 ArrayList<String> filesnotmatched = new ArrayList<>();
4663 for (int i = 0; i < files.size(); i++)
4665 String file = files.get(i).toString();
4667 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4668 if (protocol == DataSourceType.FILE)
4670 File fl = new File(file);
4671 pdbfn = fl.getName();
4673 else if (protocol == DataSourceType.URL)
4675 URL url = new URL(file);
4676 pdbfn = url.getFile();
4678 if (pdbfn.length() > 0)
4680 // attempt to find a match in the alignment
4681 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4682 int l = 0, c = pdbfn.indexOf(".");
4683 while (mtch == null && c != -1)
4688 } while ((c = pdbfn.indexOf(".", l)) > l);
4691 pdbfn = pdbfn.substring(0, l);
4693 mtch = idm.findAllIdMatches(pdbfn);
4697 FileFormatI type = null;
4700 type = new IdentifyFile().identify(file, protocol);
4701 } catch (Exception ex)
4705 if (type != null && type.isStructureFile())
4707 filesmatched.add(new Object[] { file, protocol, mtch });
4711 // File wasn't named like one of the sequences or wasn't a PDB file.
4712 filesnotmatched.add(file);
4716 if (filesmatched.size() > 0)
4718 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4719 || JvOptionPane.showConfirmDialog(this,
4720 MessageManager.formatMessage(
4721 "label.automatically_associate_structure_files_with_sequences_same_name",
4723 { Integer.valueOf(filesmatched.size())
4725 MessageManager.getString(
4726 "label.automatically_associate_structure_files_by_name"),
4727 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4730 for (Object[] fm : filesmatched)
4732 // try and associate
4733 // TODO: may want to set a standard ID naming formalism for
4734 // associating PDB files which have no IDs.
4735 for (SequenceI toassoc : (SequenceI[]) fm[2])
4737 PDBEntry pe = new AssociatePdbFileWithSeq()
4738 .associatePdbWithSeq((String) fm[0],
4739 (DataSourceType) fm[1], toassoc, false,
4743 System.err.println("Associated file : " + ((String) fm[0])
4744 + " with " + toassoc.getDisplayId(true));
4748 alignPanel.paintAlignment(true);
4752 if (filesnotmatched.size() > 0)
4754 if (assocfiles > 0 && (Cache.getDefault(
4755 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4756 || JvOptionPane.showConfirmDialog(this,
4757 "<html>" + MessageManager.formatMessage(
4758 "label.ignore_unmatched_dropped_files_info",
4760 { Integer.valueOf(filesnotmatched.size())
4763 MessageManager.getString(
4764 "label.ignore_unmatched_dropped_files"),
4765 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4769 for (String fn : filesnotmatched)
4771 loadJalviewDataFile(fn, null, null, null);
4775 } catch (Exception ex)
4777 ex.printStackTrace();
4783 * Attempt to load a "dropped" file or URL string, by testing in turn for
4785 * <li>an Annotation file</li>
4786 * <li>a JNet file</li>
4787 * <li>a features file</li>
4788 * <li>else try to interpret as an alignment file</li>
4792 * either a filename or a URL string.
4793 * @throws InterruptedException
4794 * @throws IOException
4796 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4797 FileFormatI format, SequenceI assocSeq)
4801 if (sourceType == null)
4803 sourceType = FormatAdapter.checkProtocol(file);
4805 // if the file isn't identified, or not positively identified as some
4806 // other filetype (PFAM is default unidentified alignment file type) then
4807 // try to parse as annotation.
4808 boolean isAnnotation = (format == null
4809 || FileFormat.Pfam.equals(format))
4810 ? new AnnotationFile().annotateAlignmentView(viewport,
4816 // first see if its a T-COFFEE score file
4817 TCoffeeScoreFile tcf = null;
4820 tcf = new TCoffeeScoreFile(file, sourceType);
4823 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4827 new TCoffeeColourScheme(viewport.getAlignment()));
4828 isAnnotation = true;
4829 statusBar.setText(MessageManager.getString(
4830 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4834 // some problem - if no warning its probable that the ID matching
4835 // process didn't work
4836 JvOptionPane.showMessageDialog(Desktop.desktop,
4837 tcf.getWarningMessage() == null
4838 ? MessageManager.getString(
4839 "label.check_file_matches_sequence_ids_alignment")
4840 : tcf.getWarningMessage(),
4841 MessageManager.getString(
4842 "label.problem_reading_tcoffee_score_file"),
4843 JvOptionPane.WARNING_MESSAGE);
4850 } catch (Exception x)
4853 "Exception when processing data source as T-COFFEE score file",
4859 // try to see if its a JNet 'concise' style annotation file *before*
4861 // try to parse it as a features file
4864 format = new IdentifyFile().identify(file, sourceType);
4866 if (FileFormat.ScoreMatrix == format)
4868 ScoreMatrixFile sm = new ScoreMatrixFile(
4869 new FileParse(file, sourceType));
4871 // todo: i18n this message
4872 statusBar.setText(MessageManager.formatMessage(
4873 "label.successfully_loaded_matrix",
4874 sm.getMatrixName()));
4876 else if (FileFormat.Jnet.equals(format))
4878 JPredFile predictions = new JPredFile(file, sourceType);
4879 new JnetAnnotationMaker();
4880 JnetAnnotationMaker.add_annotation(predictions,
4881 viewport.getAlignment(), 0, false);
4882 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4883 viewport.getAlignment().setSeqrep(repseq);
4884 HiddenColumns cs = new HiddenColumns();
4885 cs.hideInsertionsFor(repseq);
4886 viewport.getAlignment().setHiddenColumns(cs);
4887 isAnnotation = true;
4889 // else if (IdentifyFile.FeaturesFile.equals(format))
4890 else if (FileFormat.Features.equals(format))
4892 if (parseFeaturesFile(file, sourceType))
4894 alignPanel.paintAlignment(true);
4899 new FileLoader().LoadFile(viewport, file, sourceType, format);
4905 alignPanel.adjustAnnotationHeight();
4906 viewport.updateSequenceIdColours();
4907 buildSortByAnnotationScoresMenu();
4908 alignPanel.paintAlignment(true);
4910 } catch (Exception ex)
4912 ex.printStackTrace();
4913 } catch (OutOfMemoryError oom)
4918 } catch (Exception x)
4923 + (sourceType != null
4924 ? (sourceType == DataSourceType.PASTE
4926 : "using " + sourceType + " from "
4930 ? "(parsing as '" + format + "' file)"
4932 oom, Desktop.desktop);
4937 * Method invoked by the ChangeListener on the tabbed pane, in other words
4938 * when a different tabbed pane is selected by the user or programmatically.
4941 public void tabSelectionChanged(int index)
4945 alignPanel = alignPanels.get(index);
4946 viewport = alignPanel.av;
4947 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4948 setMenusFromViewport(viewport);
4952 * 'focus' any colour slider that is open to the selected viewport
4954 if (viewport.getConservationSelected())
4956 SliderPanel.setConservationSlider(alignPanel,
4957 viewport.getResidueShading(), alignPanel.getViewName());
4961 SliderPanel.hideConservationSlider();
4963 if (viewport.getAbovePIDThreshold())
4965 SliderPanel.setPIDSliderSource(alignPanel,
4966 viewport.getResidueShading(), alignPanel.getViewName());
4970 SliderPanel.hidePIDSlider();
4974 * If there is a frame linked to this one in a SplitPane, switch it to the
4975 * same view tab index. No infinite recursion of calls should happen, since
4976 * tabSelectionChanged() should not get invoked on setting the selected
4977 * index to an unchanged value. Guard against setting an invalid index
4978 * before the new view peer tab has been created.
4980 final AlignViewportI peer = viewport.getCodingComplement();
4983 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4984 .getAlignPanel().alignFrame;
4985 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4987 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4993 * On right mouse click on view tab, prompt for and set new view name.
4996 public void tabbedPane_mousePressed(MouseEvent e)
4998 if (e.isPopupTrigger())
5000 String msg = MessageManager.getString("label.enter_view_name");
5001 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
5002 JvOptionPane.QUESTION_MESSAGE);
5006 viewport.viewName = reply;
5007 // TODO warn if reply is in getExistingViewNames()?
5008 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5013 public AlignViewport getCurrentView()
5019 * Open the dialog for regex description parsing.
5022 protected void extractScores_actionPerformed(ActionEvent e)
5024 ParseProperties pp = new jalview.analysis.ParseProperties(
5025 viewport.getAlignment());
5026 // TODO: verify regex and introduce GUI dialog for version 2.5
5027 // if (pp.getScoresFromDescription("col", "score column ",
5028 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5030 if (pp.getScoresFromDescription("description column",
5031 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5033 buildSortByAnnotationScoresMenu();
5041 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5045 protected void showDbRefs_actionPerformed(ActionEvent e)
5047 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5053 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5057 protected void showNpFeats_actionPerformed(ActionEvent e)
5059 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5063 * find the viewport amongst the tabs in this alignment frame and close that
5068 public boolean closeView(AlignViewportI av)
5072 this.closeMenuItem_actionPerformed(false);
5075 Component[] comp = tabbedPane.getComponents();
5076 for (int i = 0; comp != null && i < comp.length; i++)
5078 if (comp[i] instanceof AlignmentPanel)
5080 if (((AlignmentPanel) comp[i]).av == av)
5083 closeView((AlignmentPanel) comp[i]);
5091 protected void build_fetchdbmenu(JMenu webService)
5093 // Temporary hack - DBRef Fetcher always top level ws entry.
5094 // TODO We probably want to store a sequence database checklist in
5095 // preferences and have checkboxes.. rather than individual sources selected
5097 final JMenu rfetch = new JMenu(
5098 MessageManager.getString("action.fetch_db_references"));
5099 rfetch.setToolTipText(MessageManager.getString(
5100 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5101 webService.add(rfetch);
5103 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5104 MessageManager.getString("option.trim_retrieved_seqs"));
5105 trimrs.setToolTipText(
5106 MessageManager.getString("label.trim_retrieved_sequences"));
5107 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5108 trimrs.addActionListener(new ActionListener()
5111 public void actionPerformed(ActionEvent e)
5113 trimrs.setSelected(trimrs.isSelected());
5114 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5115 Boolean.valueOf(trimrs.isSelected()).toString());
5119 JMenuItem fetchr = new JMenuItem(
5120 MessageManager.getString("label.standard_databases"));
5121 fetchr.setToolTipText(
5122 MessageManager.getString("label.fetch_embl_uniprot"));
5123 fetchr.addActionListener(new ActionListener()
5127 public void actionPerformed(ActionEvent e)
5129 new Thread(new Runnable()
5134 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5135 .getAlignment().isNucleotide();
5136 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5137 alignPanel.av.getSequenceSelection(),
5138 alignPanel.alignFrame, null,
5139 alignPanel.alignFrame.featureSettings, isNucleotide);
5140 dbRefFetcher.addListener(new FetchFinishedListenerI()
5143 public void finished()
5145 AlignFrame.this.setMenusForViewport();
5148 dbRefFetcher.fetchDBRefs(false);
5156 final AlignFrame me = this;
5157 new Thread(new Runnable()
5162 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5163 .getSequenceFetcherSingleton(me);
5164 javax.swing.SwingUtilities.invokeLater(new Runnable()
5169 String[] dbclasses = sf.getOrderedSupportedSources();
5170 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5171 // jalview.util.QuickSort.sort(otherdb, otherdb);
5172 List<DbSourceProxy> otherdb;
5173 JMenu dfetch = new JMenu();
5174 JMenu ifetch = new JMenu();
5175 JMenuItem fetchr = null;
5176 int comp = 0, icomp = 0, mcomp = 15;
5177 String mname = null;
5179 for (String dbclass : dbclasses)
5181 otherdb = sf.getSourceProxy(dbclass);
5182 // add a single entry for this class, or submenu allowing 'fetch
5184 if (otherdb == null || otherdb.size() < 1)
5188 // List<DbSourceProxy> dbs=otherdb;
5189 // otherdb=new ArrayList<DbSourceProxy>();
5190 // for (DbSourceProxy db:dbs)
5192 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5196 mname = "From " + dbclass;
5198 if (otherdb.size() == 1)
5200 final DbSourceProxy[] dassource = otherdb
5201 .toArray(new DbSourceProxy[0]);
5202 DbSourceProxy src = otherdb.get(0);
5203 fetchr = new JMenuItem(src.getDbSource());
5204 fetchr.addActionListener(new ActionListener()
5208 public void actionPerformed(ActionEvent e)
5210 new Thread(new Runnable()
5216 boolean isNucleotide = alignPanel.alignFrame
5217 .getViewport().getAlignment()
5219 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5220 alignPanel.av.getSequenceSelection(),
5221 alignPanel.alignFrame, dassource,
5222 alignPanel.alignFrame.featureSettings,
5225 .addListener(new FetchFinishedListenerI()
5228 public void finished()
5230 AlignFrame.this.setMenusForViewport();
5233 dbRefFetcher.fetchDBRefs(false);
5239 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5240 MessageManager.formatMessage(
5241 "label.fetch_retrieve_from", new Object[]
5242 { src.getDbName() })));
5248 final DbSourceProxy[] dassource = otherdb
5249 .toArray(new DbSourceProxy[0]);
5251 DbSourceProxy src = otherdb.get(0);
5252 fetchr = new JMenuItem(MessageManager
5253 .formatMessage("label.fetch_all_param", new Object[]
5254 { src.getDbSource() }));
5255 fetchr.addActionListener(new ActionListener()
5258 public void actionPerformed(ActionEvent e)
5260 new Thread(new Runnable()
5266 boolean isNucleotide = alignPanel.alignFrame
5267 .getViewport().getAlignment()
5269 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5270 alignPanel.av.getSequenceSelection(),
5271 alignPanel.alignFrame, dassource,
5272 alignPanel.alignFrame.featureSettings,
5275 .addListener(new FetchFinishedListenerI()
5278 public void finished()
5280 AlignFrame.this.setMenusForViewport();
5283 dbRefFetcher.fetchDBRefs(false);
5289 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5290 MessageManager.formatMessage(
5291 "label.fetch_retrieve_from_all_sources",
5293 { Integer.valueOf(otherdb.size())
5295 src.getDbSource(), src.getDbName() })));
5298 // and then build the rest of the individual menus
5299 ifetch = new JMenu(MessageManager.formatMessage(
5300 "label.source_from_db_source", new Object[]
5301 { src.getDbSource() }));
5303 String imname = null;
5305 for (DbSourceProxy sproxy : otherdb)
5307 String dbname = sproxy.getDbName();
5308 String sname = dbname.length() > 5
5309 ? dbname.substring(0, 5) + "..."
5311 String msname = dbname.length() > 10
5312 ? dbname.substring(0, 10) + "..."
5316 imname = MessageManager
5317 .formatMessage("label.from_msname", new Object[]
5320 fetchr = new JMenuItem(msname);
5321 final DbSourceProxy[] dassrc = { sproxy };
5322 fetchr.addActionListener(new ActionListener()
5326 public void actionPerformed(ActionEvent e)
5328 new Thread(new Runnable()
5334 boolean isNucleotide = alignPanel.alignFrame
5335 .getViewport().getAlignment()
5337 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5338 alignPanel.av.getSequenceSelection(),
5339 alignPanel.alignFrame, dassrc,
5340 alignPanel.alignFrame.featureSettings,
5343 .addListener(new FetchFinishedListenerI()
5346 public void finished()
5348 AlignFrame.this.setMenusForViewport();
5351 dbRefFetcher.fetchDBRefs(false);
5357 fetchr.setToolTipText(
5358 "<html>" + MessageManager.formatMessage(
5359 "label.fetch_retrieve_from", new Object[]
5363 if (++icomp >= mcomp || i == (otherdb.size()))
5365 ifetch.setText(MessageManager.formatMessage(
5366 "label.source_to_target", imname, sname));
5368 ifetch = new JMenu();
5376 if (comp >= mcomp || dbi >= (dbclasses.length))
5378 dfetch.setText(MessageManager.formatMessage(
5379 "label.source_to_target", mname, dbclass));
5381 dfetch = new JMenu();
5394 * Left justify the whole alignment.
5397 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5399 AlignmentI al = viewport.getAlignment();
5401 viewport.firePropertyChange("alignment", null, al);
5405 * Right justify the whole alignment.
5408 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5410 AlignmentI al = viewport.getAlignment();
5412 viewport.firePropertyChange("alignment", null, al);
5416 public void setShowSeqFeatures(boolean b)
5418 showSeqFeatures.setSelected(b);
5419 viewport.setShowSequenceFeatures(b);
5426 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5427 * awt.event.ActionEvent)
5430 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5432 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5433 alignPanel.paintAlignment(true);
5440 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5444 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5446 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5447 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5455 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5456 * .event.ActionEvent)
5459 protected void showGroupConservation_actionPerformed(ActionEvent e)
5461 viewport.setShowGroupConservation(showGroupConservation.getState());
5462 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5469 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5470 * .event.ActionEvent)
5473 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5475 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5476 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5483 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5484 * .event.ActionEvent)
5487 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5489 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5490 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5494 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5496 showSequenceLogo.setState(true);
5497 viewport.setShowSequenceLogo(true);
5498 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5499 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5503 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5505 viewport.setShowInformationHistogram(
5506 showInformationHistogram.getState());
5507 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5511 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5513 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5514 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5518 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5520 showHMMSequenceLogo.setState(true);
5521 viewport.setShowHMMSequenceLogo(true);
5522 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5523 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5527 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5529 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5536 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5537 * .event.ActionEvent)
5540 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5542 if (avc.makeGroupsFromSelection())
5544 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5545 alignPanel.updateAnnotation();
5546 alignPanel.paintAlignment(true);
5550 public void clearAlignmentSeqRep()
5552 // TODO refactor alignmentseqrep to controller
5553 if (viewport.getAlignment().hasSeqrep())
5555 viewport.getAlignment().setSeqrep(null);
5556 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5557 alignPanel.updateAnnotation();
5558 alignPanel.paintAlignment(true);
5563 protected void createGroup_actionPerformed(ActionEvent e)
5565 if (avc.createGroup())
5567 alignPanel.alignmentChanged();
5572 protected void unGroup_actionPerformed(ActionEvent e)
5576 alignPanel.alignmentChanged();
5581 * make the given alignmentPanel the currently selected tab
5583 * @param alignmentPanel
5585 public void setDisplayedView(AlignmentPanel alignmentPanel)
5587 if (!viewport.getSequenceSetId()
5588 .equals(alignmentPanel.av.getSequenceSetId()))
5590 throw new Error(MessageManager.getString(
5591 "error.implementation_error_cannot_show_view_alignment_frame"));
5593 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5594 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5596 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5601 * Action on selection of menu options to Show or Hide annotations.
5604 * @param forSequences
5605 * update sequence-related annotations
5606 * @param forAlignment
5607 * update non-sequence-related annotations
5610 protected void setAnnotationsVisibility(boolean visible,
5611 boolean forSequences, boolean forAlignment)
5613 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5614 .getAlignmentAnnotation();
5619 for (AlignmentAnnotation aa : anns)
5622 * don't display non-positional annotations on an alignment
5624 if (aa.annotations == null)
5628 boolean apply = (aa.sequenceRef == null && forAlignment)
5629 || (aa.sequenceRef != null && forSequences);
5632 aa.visible = visible;
5635 alignPanel.validateAnnotationDimensions(true);
5636 alignPanel.alignmentChanged();
5640 * Store selected annotation sort order for the view and repaint.
5643 protected void sortAnnotations_actionPerformed()
5645 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5647 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5648 alignPanel.paintAlignment(true);
5653 * @return alignment panels in this alignment frame
5655 public List<? extends AlignmentViewPanel> getAlignPanels()
5657 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5661 * Open a new alignment window, with the cDNA associated with this (protein)
5662 * alignment, aligned as is the protein.
5664 protected void viewAsCdna_actionPerformed()
5666 // TODO no longer a menu action - refactor as required
5667 final AlignmentI alignment = getViewport().getAlignment();
5668 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5669 if (mappings == null)
5673 List<SequenceI> cdnaSeqs = new ArrayList<>();
5674 for (SequenceI aaSeq : alignment.getSequences())
5676 for (AlignedCodonFrame acf : mappings)
5678 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5682 * There is a cDNA mapping for this protein sequence - add to new
5683 * alignment. It will share the same dataset sequence as other mapped
5684 * cDNA (no new mappings need to be created).
5686 final Sequence newSeq = new Sequence(dnaSeq);
5687 newSeq.setDatasetSequence(dnaSeq);
5688 cdnaSeqs.add(newSeq);
5692 if (cdnaSeqs.size() == 0)
5694 // show a warning dialog no mapped cDNA
5697 AlignmentI cdna = new Alignment(
5698 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5699 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5700 AlignFrame.DEFAULT_HEIGHT);
5701 cdna.alignAs(alignment);
5702 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5704 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5705 AlignFrame.DEFAULT_HEIGHT);
5709 * Set visibility of dna/protein complement view (available when shown in a
5715 protected void showComplement_actionPerformed(boolean show)
5717 SplitContainerI sf = getSplitViewContainer();
5720 sf.setComplementVisible(this, show);
5725 * Generate the reverse (optionally complemented) of the selected sequences,
5726 * and add them to the alignment
5729 protected void showReverse_actionPerformed(boolean complement)
5731 AlignmentI al = null;
5734 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5735 al = dna.reverseCdna(complement);
5736 viewport.addAlignment(al, "");
5737 addHistoryItem(new EditCommand(
5738 MessageManager.getString("label.add_sequences"), Action.PASTE,
5739 al.getSequencesArray(), 0, al.getWidth(),
5740 viewport.getAlignment()));
5741 } catch (Exception ex)
5743 System.err.println(ex.getMessage());
5749 * Try to run a script in the Groovy console, having first ensured that this
5750 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5751 * be targeted at this alignment.
5754 protected void runGroovy_actionPerformed()
5756 Jalview.setCurrentAlignFrame(this);
5757 groovy.ui.Console console = Desktop.getGroovyConsole();
5758 if (console != null)
5762 console.runScript();
5763 } catch (Exception ex)
5765 System.err.println((ex.toString()));
5766 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5767 MessageManager.getString("label.couldnt_run_groovy_script"),
5768 MessageManager.getString("label.groovy_support_failed"),
5769 JvOptionPane.ERROR_MESSAGE);
5774 System.err.println("Can't run Groovy script as console not found");
5779 * Hides columns containing (or not containing) a specified feature, provided
5780 * that would not leave all columns hidden
5782 * @param featureType
5783 * @param columnsContaining
5786 public boolean hideFeatureColumns(String featureType,
5787 boolean columnsContaining)
5789 boolean notForHiding = avc.markColumnsContainingFeatures(
5790 columnsContaining, false, false, featureType);
5793 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5794 false, featureType))
5796 getViewport().hideSelectedColumns();
5804 protected void selectHighlightedColumns_actionPerformed(
5805 ActionEvent actionEvent)
5807 // include key modifier check in case user selects from menu
5808 avc.markHighlightedColumns(
5809 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5810 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5811 | ActionEvent.CTRL_MASK)) != 0);
5815 * Rebuilds the Colour menu, including any user-defined colours which have
5816 * been loaded either on startup or during the session
5818 public void buildColourMenu()
5820 colourMenu.removeAll();
5822 colourMenu.add(applyToAllGroups);
5823 colourMenu.add(textColour);
5824 colourMenu.addSeparator();
5826 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5829 colourMenu.addSeparator();
5830 colourMenu.add(conservationMenuItem);
5831 colourMenu.add(modifyConservation);
5832 colourMenu.add(abovePIDThreshold);
5833 colourMenu.add(modifyPID);
5834 colourMenu.add(annotationColour);
5836 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5837 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5841 * Open a dialog (if not already open) that allows the user to select and
5842 * calculate PCA or Tree analysis
5844 protected void openTreePcaDialog()
5846 if (alignPanel.getCalculationDialog() == null)
5848 new CalculationChooser(AlignFrame.this);
5853 * Sets the status of the HMMER menu
5857 public void updateHMMERStatus(boolean status)
5859 hmmerMenu.setEnabled(status);
5863 * Returns the selected hidden Markov model.
5867 public HiddenMarkovModel getSelectedHMM()
5869 if (selectedHMMSequence == null)
5873 return selectedHMMSequence.getHMM();
5877 * Returns the selected hidden Markov model.
5881 public SequenceI getSelectedHMMSequence()
5883 return selectedHMMSequence;
5887 * Sets the selected hidden Markov model
5889 * @param selectedHMM
5891 public void setSelectedHMMSequence(SequenceI selectedHMM)
5893 this.selectedHMMSequence = selectedHMM;
5894 hmmAlign.setText(MessageManager.getString("label.hmmalign") + " to "
5895 + selectedHMM.getHMM().getName() + "_HMM");
5896 hmmSearch.setText(MessageManager.getString("label.hmmsearch") + " with "
5897 + selectedHMM.getHMM().getName() + "_HMM");
5901 public void hmmerMenu_actionPerformed(ActionEvent e)
5903 SequenceGroup grp = getViewport().getSelectionGroup();
5906 hmmBuild.setText(MessageManager.getString("label.hmmbuild") + " from "
5911 hmmBuild.setText(MessageManager.getString("label.hmmbuild")
5912 + " from Alignment");
5918 class PrintThread extends Thread
5922 public PrintThread(AlignmentPanel ap)
5927 static PageFormat pf;
5932 PrinterJob printJob = PrinterJob.getPrinterJob();
5936 printJob.setPrintable(ap, pf);
5940 printJob.setPrintable(ap);
5943 if (printJob.printDialog())
5948 } catch (Exception PrintException)
5950 PrintException.printStackTrace();