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.analysis.TreeModel;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.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.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.ext.archaeopteryx.AptxInit;
64 import jalview.ext.forester.io.SupportedTreeFileFilter;
65 import jalview.ext.forester.io.TreeParser;
66 import jalview.gui.ColourMenuHelper.ColourChangeListener;
67 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
68 import jalview.io.AlignmentProperties;
69 import jalview.io.AnnotationFile;
70 import jalview.io.BioJsHTMLOutput;
71 import jalview.io.DataSourceType;
72 import jalview.io.FileFormat;
73 import jalview.io.FileFormatI;
74 import jalview.io.FileFormats;
75 import jalview.io.FileLoader;
76 import jalview.io.FileParse;
77 import jalview.io.FormatAdapter;
78 import jalview.io.HtmlSvgOutput;
79 import jalview.io.IdentifyFile;
80 import jalview.io.JPredFile;
81 import jalview.io.JalviewFileChooser;
82 import jalview.io.JalviewFileView;
83 import jalview.io.JnetAnnotationMaker;
84 import jalview.io.NewickFile;
85 import jalview.io.ScoreMatrixFile;
86 import jalview.io.TCoffeeScoreFile;
87 import jalview.jbgui.GAlignFrame;
88 import jalview.schemes.ColourSchemeI;
89 import jalview.schemes.ColourSchemes;
90 import jalview.schemes.ResidueColourScheme;
91 import jalview.schemes.TCoffeeColourScheme;
92 import jalview.util.MessageManager;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.ViewportRanges;
95 import jalview.ws.DBRefFetcher;
96 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Component;
104 import java.awt.Dimension;
105 import java.awt.GridLayout;
106 import java.awt.Rectangle;
107 import java.awt.Toolkit;
108 import java.awt.datatransfer.Clipboard;
109 import java.awt.datatransfer.DataFlavor;
110 import java.awt.datatransfer.StringSelection;
111 import java.awt.datatransfer.Transferable;
112 import java.awt.dnd.DnDConstants;
113 import java.awt.dnd.DropTargetDragEvent;
114 import java.awt.dnd.DropTargetDropEvent;
115 import java.awt.dnd.DropTargetEvent;
116 import java.awt.dnd.DropTargetListener;
117 import java.awt.event.ActionEvent;
118 import java.awt.event.ActionListener;
119 import java.awt.event.FocusAdapter;
120 import java.awt.event.FocusEvent;
121 import java.awt.event.ItemEvent;
122 import java.awt.event.ItemListener;
123 import java.awt.event.KeyAdapter;
124 import java.awt.event.KeyEvent;
125 import java.awt.event.MouseEvent;
126 import java.awt.print.PageFormat;
127 import java.awt.print.PrinterJob;
128 import java.beans.PropertyChangeEvent;
130 import java.io.FileWriter;
131 import java.io.IOException;
132 import java.io.PrintWriter;
134 import java.util.ArrayList;
135 import java.util.Arrays;
136 import java.util.Deque;
137 import java.util.Enumeration;
138 import java.util.Hashtable;
139 import java.util.List;
140 import java.util.StringTokenizer;
141 import java.util.Vector;
143 import javax.swing.JCheckBoxMenuItem;
144 import javax.swing.JComboBox;
145 import javax.swing.JEditorPane;
146 import javax.swing.JInternalFrame;
147 import javax.swing.JLabel;
148 import javax.swing.JLayeredPane;
149 import javax.swing.JMenu;
150 import javax.swing.JMenuItem;
151 import javax.swing.JPanel;
152 import javax.swing.JScrollPane;
153 import javax.swing.SwingUtilities;
159 * @version $Revision$
161 public class AlignFrame extends GAlignFrame implements DropTargetListener,
162 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
165 public static final int DEFAULT_WIDTH = 700;
167 public static final int DEFAULT_HEIGHT = 500;
170 * The currently displayed panel (selected tabbed view if more than one)
172 public AlignmentPanel alignPanel;
174 AlignViewport viewport;
176 public AlignViewControllerI avc;
178 List<AlignmentPanel> alignPanels = new ArrayList<>();
181 * Last format used to load or save alignments in this window
183 FileFormatI currentFileFormat = null;
186 * Current filename for this alignment
188 String fileName = null;
191 * Creates a new AlignFrame object with specific width and height.
197 public AlignFrame(AlignmentI al, int width, int height)
199 this(al, null, width, height);
203 * Creates a new AlignFrame object with specific width, height and
209 * @param sequenceSetId
211 public AlignFrame(AlignmentI al, int width, int height,
212 String sequenceSetId)
214 this(al, null, width, height, sequenceSetId);
218 * Creates a new AlignFrame object with specific width, height and
224 * @param sequenceSetId
227 public AlignFrame(AlignmentI al, int width, int height,
228 String sequenceSetId, String viewId)
230 this(al, null, width, height, sequenceSetId, viewId);
234 * new alignment window with hidden columns
238 * @param hiddenColumns
239 * ColumnSelection or null
241 * Width of alignment frame
245 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
248 this(al, hiddenColumns, width, height, null);
252 * Create alignment frame for al with hiddenColumns, a specific width and
253 * height, and specific sequenceId
256 * @param hiddenColumns
259 * @param sequenceSetId
262 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
263 int height, String sequenceSetId)
265 this(al, hiddenColumns, width, height, sequenceSetId, null);
269 * Create alignment frame for al with hiddenColumns, a specific width and
270 * height, and specific sequenceId
273 * @param hiddenColumns
276 * @param sequenceSetId
281 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
282 int height, String sequenceSetId, String viewId)
284 setSize(width, height);
286 if (al.getDataset() == null)
291 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
293 alignPanel = new AlignmentPanel(this, viewport);
295 addAlignmentPanel(alignPanel, true);
299 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
300 HiddenColumns hiddenColumns, int width, int height)
302 setSize(width, height);
304 if (al.getDataset() == null)
309 viewport = new AlignViewport(al, hiddenColumns);
311 if (hiddenSeqs != null && hiddenSeqs.length > 0)
313 viewport.hideSequence(hiddenSeqs);
315 alignPanel = new AlignmentPanel(this, viewport);
316 addAlignmentPanel(alignPanel, true);
321 * Make a new AlignFrame from existing alignmentPanels
328 public AlignFrame(AlignmentPanel ap)
332 addAlignmentPanel(ap, false);
337 * initalise the alignframe from the underlying viewport data and the
342 if (!Jalview.isHeadlessMode())
344 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
347 avc = new jalview.controller.AlignViewController(this, viewport,
349 if (viewport.getAlignmentConservationAnnotation() == null)
351 // BLOSUM62Colour.setEnabled(false);
352 conservationMenuItem.setEnabled(false);
353 modifyConservation.setEnabled(false);
354 // PIDColour.setEnabled(false);
355 // abovePIDThreshold.setEnabled(false);
356 // modifyPID.setEnabled(false);
359 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
362 if (sortby.equals("Id"))
364 sortIDMenuItem_actionPerformed(null);
366 else if (sortby.equals("Pairwise Identity"))
368 sortPairwiseMenuItem_actionPerformed(null);
372 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
374 setMenusFromViewport(viewport);
375 buildSortByAnnotationScoresMenu();
376 calculateTree.addActionListener(new ActionListener()
380 public void actionPerformed(ActionEvent e)
387 if (Desktop.desktop != null)
389 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
390 addServiceListeners();
394 if (viewport.getWrapAlignment())
396 wrapMenuItem_actionPerformed(null);
399 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
401 this.overviewMenuItem_actionPerformed(null);
406 final List<AlignmentPanel> selviews = new ArrayList<>();
407 final List<AlignmentPanel> origview = new ArrayList<>();
408 final String menuLabel = MessageManager
409 .getString("label.copy_format_from");
410 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
411 new ViewSetProvider()
415 public AlignmentPanel[] getAllAlignmentPanels()
418 origview.add(alignPanel);
419 // make an array of all alignment panels except for this one
420 List<AlignmentPanel> aps = new ArrayList<>(
421 Arrays.asList(Desktop.getAlignmentPanels(null)));
422 aps.remove(AlignFrame.this.alignPanel);
423 return aps.toArray(new AlignmentPanel[aps.size()]);
425 }, selviews, new ItemListener()
429 public void itemStateChanged(ItemEvent e)
431 if (origview.size() > 0)
433 final AlignmentPanel ap = origview.get(0);
436 * Copy the ViewStyle of the selected panel to 'this one'.
437 * Don't change value of 'scaleProteinAsCdna' unless copying
440 ViewStyleI vs = selviews.get(0).getAlignViewport()
442 boolean fromSplitFrame = selviews.get(0)
443 .getAlignViewport().getCodingComplement() != null;
446 vs.setScaleProteinAsCdna(ap.getAlignViewport()
447 .getViewStyle().isScaleProteinAsCdna());
449 ap.getAlignViewport().setViewStyle(vs);
452 * Also rescale ViewStyle of SplitFrame complement if there is
453 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
454 * the whole ViewStyle (allow cDNA protein to have different
457 AlignViewportI complement = ap.getAlignViewport()
458 .getCodingComplement();
459 if (complement != null && vs.isScaleProteinAsCdna())
461 AlignFrame af = Desktop.getAlignFrameFor(complement);
462 ((SplitFrame) af.getSplitViewContainer())
464 af.setMenusForViewport();
468 ap.setSelected(true);
469 ap.alignFrame.setMenusForViewport();
474 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
475 .indexOf("devel") > -1
476 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
477 .indexOf("test") > -1)
479 formatMenu.add(vsel);
481 addFocusListener(new FocusAdapter()
484 public void focusGained(FocusEvent e)
486 Jalview.setCurrentAlignFrame(AlignFrame.this);
493 * Change the filename and format for the alignment, and enable the 'reload'
494 * button functionality.
501 public void setFileName(String file, FileFormatI format)
504 setFileFormat(format);
505 reload.setEnabled(true);
509 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
512 void addKeyListener()
514 addKeyListener(new KeyAdapter()
517 public void keyPressed(KeyEvent evt)
519 if (viewport.cursorMode
520 && ((evt.getKeyCode() >= KeyEvent.VK_0
521 && evt.getKeyCode() <= KeyEvent.VK_9)
522 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
523 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
524 && Character.isDigit(evt.getKeyChar()))
526 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
529 switch (evt.getKeyCode())
532 case 27: // escape key
533 deselectAllSequenceMenuItem_actionPerformed(null);
537 case KeyEvent.VK_DOWN:
538 if (evt.isAltDown() || !viewport.cursorMode)
540 moveSelectedSequences(false);
542 if (viewport.cursorMode)
544 alignPanel.getSeqPanel().moveCursor(0, 1);
549 if (evt.isAltDown() || !viewport.cursorMode)
551 moveSelectedSequences(true);
553 if (viewport.cursorMode)
555 alignPanel.getSeqPanel().moveCursor(0, -1);
560 case KeyEvent.VK_LEFT:
561 if (evt.isAltDown() || !viewport.cursorMode)
563 slideSequences(false,
564 alignPanel.getSeqPanel().getKeyboardNo1());
568 alignPanel.getSeqPanel().moveCursor(-1, 0);
573 case KeyEvent.VK_RIGHT:
574 if (evt.isAltDown() || !viewport.cursorMode)
576 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
580 alignPanel.getSeqPanel().moveCursor(1, 0);
584 case KeyEvent.VK_SPACE:
585 if (viewport.cursorMode)
587 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
588 || evt.isShiftDown() || evt.isAltDown());
592 // case KeyEvent.VK_A:
593 // if (viewport.cursorMode)
595 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
596 // //System.out.println("A");
600 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
601 * System.out.println("closing bracket"); } break;
603 case KeyEvent.VK_DELETE:
604 case KeyEvent.VK_BACK_SPACE:
605 if (!viewport.cursorMode)
607 cut_actionPerformed(null);
611 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
612 || evt.isShiftDown() || evt.isAltDown());
618 if (viewport.cursorMode)
620 alignPanel.getSeqPanel().setCursorRow();
624 if (viewport.cursorMode && !evt.isControlDown())
626 alignPanel.getSeqPanel().setCursorColumn();
630 if (viewport.cursorMode)
632 alignPanel.getSeqPanel().setCursorPosition();
636 case KeyEvent.VK_ENTER:
637 case KeyEvent.VK_COMMA:
638 if (viewport.cursorMode)
640 alignPanel.getSeqPanel().setCursorRowAndColumn();
645 if (viewport.cursorMode)
647 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
651 if (viewport.cursorMode)
653 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
658 viewport.cursorMode = !viewport.cursorMode;
659 statusBar.setText(MessageManager
660 .formatMessage("label.keyboard_editing_mode", new String[]
661 { (viewport.cursorMode ? "on" : "off") }));
662 if (viewport.cursorMode)
664 ViewportRanges ranges = viewport.getRanges();
665 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
667 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
670 alignPanel.getSeqPanel().seqCanvas.repaint();
676 Help.showHelpWindow();
677 } catch (Exception ex)
679 ex.printStackTrace();
684 boolean toggleSeqs = !evt.isControlDown();
685 boolean toggleCols = !evt.isShiftDown();
686 toggleHiddenRegions(toggleSeqs, toggleCols);
691 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
692 boolean modifyExisting = true; // always modify, don't clear
693 // evt.isShiftDown();
694 boolean invertHighlighted = evt.isAltDown();
695 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
699 case KeyEvent.VK_PAGE_UP:
700 viewport.getRanges().pageUp();
702 case KeyEvent.VK_PAGE_DOWN:
703 viewport.getRanges().pageDown();
709 public void keyReleased(KeyEvent evt)
711 switch (evt.getKeyCode())
713 case KeyEvent.VK_LEFT:
714 if (evt.isAltDown() || !viewport.cursorMode)
716 viewport.firePropertyChange("alignment", null,
717 viewport.getAlignment().getSequences());
721 case KeyEvent.VK_RIGHT:
722 if (evt.isAltDown() || !viewport.cursorMode)
724 viewport.firePropertyChange("alignment", null,
725 viewport.getAlignment().getSequences());
733 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
735 ap.alignFrame = this;
736 avc = new jalview.controller.AlignViewController(this, viewport,
741 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
743 int aSize = alignPanels.size();
745 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
747 if (aSize == 1 && ap.av.viewName == null)
749 this.getContentPane().add(ap, BorderLayout.CENTER);
755 setInitialTabVisible();
758 expandViews.setEnabled(true);
759 gatherViews.setEnabled(true);
760 tabbedPane.addTab(ap.av.viewName, ap);
762 ap.setVisible(false);
767 if (ap.av.isPadGaps())
769 ap.av.getAlignment().padGaps();
771 ap.av.updateConservation(ap);
772 ap.av.updateConsensus(ap);
773 ap.av.updateStrucConsensus(ap);
777 public void setInitialTabVisible()
779 expandViews.setEnabled(true);
780 gatherViews.setEnabled(true);
781 tabbedPane.setVisible(true);
782 AlignmentPanel first = alignPanels.get(0);
783 tabbedPane.addTab(first.av.viewName, first);
784 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
787 public AlignViewport getViewport()
792 /* Set up intrinsic listeners for dynamically generated GUI bits. */
793 private void addServiceListeners()
795 final java.beans.PropertyChangeListener thisListener;
796 Desktop.instance.addJalviewPropertyChangeListener("services",
797 thisListener = new java.beans.PropertyChangeListener()
800 public void propertyChange(PropertyChangeEvent evt)
802 // // System.out.println("Discoverer property change.");
803 // if (evt.getPropertyName().equals("services"))
805 SwingUtilities.invokeLater(new Runnable()
812 "Rebuild WS Menu for service change");
813 BuildWebServiceMenu();
820 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
823 public void internalFrameClosed(
824 javax.swing.event.InternalFrameEvent evt)
826 // System.out.println("deregistering discoverer listener");
827 Desktop.instance.removeJalviewPropertyChangeListener("services",
829 closeMenuItem_actionPerformed(true);
832 // Finally, build the menu once to get current service state
833 new Thread(new Runnable()
838 BuildWebServiceMenu();
844 * Configure menu items that vary according to whether the alignment is
845 * nucleotide or protein
847 public void setGUINucleotide()
849 AlignmentI al = getViewport().getAlignment();
850 boolean nucleotide = al.isNucleotide();
852 showTranslation.setVisible(nucleotide);
853 showReverse.setVisible(nucleotide);
854 showReverseComplement.setVisible(nucleotide);
855 conservationMenuItem.setEnabled(!nucleotide);
857 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
858 showGroupConservation.setEnabled(!nucleotide);
860 showComplementMenuItem
861 .setText(nucleotide ? MessageManager.getString("label.protein")
862 : MessageManager.getString("label.nucleotide"));
866 * set up menus for the current viewport. This may be called after any
867 * operation that affects the data in the current view (selection changed,
868 * etc) to update the menus to reflect the new state.
871 public void setMenusForViewport()
873 setMenusFromViewport(viewport);
877 * Need to call this method when tabs are selected for multiple views, or when
878 * loading from Jalview2XML.java
883 void setMenusFromViewport(AlignViewport av)
885 padGapsMenuitem.setSelected(av.isPadGaps());
886 colourTextMenuItem.setSelected(av.isShowColourText());
887 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
888 modifyPID.setEnabled(abovePIDThreshold.isSelected());
889 conservationMenuItem.setSelected(av.getConservationSelected());
890 modifyConservation.setEnabled(conservationMenuItem.isSelected());
891 seqLimits.setSelected(av.getShowJVSuffix());
892 idRightAlign.setSelected(av.isRightAlignIds());
893 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
894 renderGapsMenuItem.setSelected(av.isRenderGaps());
895 wrapMenuItem.setSelected(av.getWrapAlignment());
896 scaleAbove.setVisible(av.getWrapAlignment());
897 scaleLeft.setVisible(av.getWrapAlignment());
898 scaleRight.setVisible(av.getWrapAlignment());
899 annotationPanelMenuItem.setState(av.isShowAnnotation());
901 * Show/hide annotations only enabled if annotation panel is shown
903 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
904 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
905 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
906 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
907 viewBoxesMenuItem.setSelected(av.getShowBoxes());
908 viewTextMenuItem.setSelected(av.getShowText());
909 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
910 showGroupConsensus.setSelected(av.isShowGroupConsensus());
911 showGroupConservation.setSelected(av.isShowGroupConservation());
912 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
913 showSequenceLogo.setSelected(av.isShowSequenceLogo());
914 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
916 ColourMenuHelper.setColourSelected(colourMenu,
917 av.getGlobalColourScheme());
919 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
920 hiddenMarkers.setState(av.getShowHiddenMarkers());
921 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
922 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
923 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
924 autoCalculate.setSelected(av.autoCalculateConsensus);
925 sortByTree.setSelected(av.sortByTree);
926 listenToViewSelections.setSelected(av.followSelection);
928 showProducts.setEnabled(canShowProducts());
929 setGroovyEnabled(Desktop.getGroovyConsole() != null);
935 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
939 public void setGroovyEnabled(boolean b)
941 runGroovy.setEnabled(b);
944 private IProgressIndicator progressBar;
949 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
952 public void setProgressBar(String message, long id)
954 progressBar.setProgressBar(message, id);
958 public void registerHandler(final long id,
959 final IProgressIndicatorHandler handler)
961 progressBar.registerHandler(id, handler);
966 * @return true if any progress bars are still active
969 public boolean operationInProgress()
971 return progressBar.operationInProgress();
975 public void setStatus(String text)
977 statusBar.setText(text);
981 * Added so Castor Mapping file can obtain Jalview Version
983 public String getVersion()
985 return jalview.bin.Cache.getProperty("VERSION");
988 public FeatureRenderer getFeatureRenderer()
990 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
994 public void fetchSequence_actionPerformed(ActionEvent e)
996 new jalview.gui.SequenceFetcher(this);
1000 public void addFromFile_actionPerformed(ActionEvent e)
1002 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1006 public void reload_actionPerformed(ActionEvent e)
1008 if (fileName != null)
1010 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1011 // originating file's format
1012 // TODO: work out how to recover feature settings for correct view(s) when
1013 // file is reloaded.
1014 if (FileFormat.Jalview.equals(currentFileFormat))
1016 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1017 for (int i = 0; i < frames.length; i++)
1019 if (frames[i] instanceof AlignFrame && frames[i] != this
1020 && ((AlignFrame) frames[i]).fileName != null
1021 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1025 frames[i].setSelected(true);
1026 Desktop.instance.closeAssociatedWindows();
1027 } catch (java.beans.PropertyVetoException ex)
1033 Desktop.instance.closeAssociatedWindows();
1035 FileLoader loader = new FileLoader();
1036 DataSourceType protocol = fileName.startsWith("http:")
1037 ? DataSourceType.URL
1038 : DataSourceType.FILE;
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 DataSourceType protocol = fileName.startsWith("http:")
1047 ? DataSourceType.URL
1048 : DataSourceType.FILE;
1049 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1050 protocol, currentFileFormat);
1052 newframe.setBounds(bounds);
1053 if (featureSettings != null && featureSettings.isShowing())
1055 final Rectangle fspos = featureSettings.frame.getBounds();
1056 // TODO: need a 'show feature settings' function that takes bounds -
1057 // need to refactor Desktop.addFrame
1058 newframe.featureSettings_actionPerformed(null);
1059 final FeatureSettings nfs = newframe.featureSettings;
1060 SwingUtilities.invokeLater(new Runnable()
1065 nfs.frame.setBounds(fspos);
1068 this.featureSettings.close();
1069 this.featureSettings = null;
1071 this.closeMenuItem_actionPerformed(true);
1077 public void addFromText_actionPerformed(ActionEvent e)
1080 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1084 public void addFromURL_actionPerformed(ActionEvent e)
1086 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1090 public void save_actionPerformed(ActionEvent e)
1092 if (fileName == null || (currentFileFormat == null)
1093 || fileName.startsWith("http"))
1095 saveAs_actionPerformed(null);
1099 saveAlignment(fileName, currentFileFormat);
1110 public void saveAs_actionPerformed(ActionEvent e)
1112 String format = currentFileFormat == null ? null
1113 : currentFileFormat.getName();
1114 JalviewFileChooser chooser = JalviewFileChooser
1115 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1117 chooser.setFileView(new JalviewFileView());
1118 chooser.setDialogTitle(
1119 MessageManager.getString("label.save_alignment_to_file"));
1120 chooser.setToolTipText(MessageManager.getString("action.save"));
1122 int value = chooser.showSaveDialog(this);
1124 if (value == JalviewFileChooser.APPROVE_OPTION)
1126 currentFileFormat = chooser.getSelectedFormat();
1127 while (currentFileFormat == null)
1129 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1130 MessageManager.getString(
1131 "label.select_file_format_before_saving"),
1132 MessageManager.getString("label.file_format_not_specified"),
1133 JvOptionPane.WARNING_MESSAGE);
1134 currentFileFormat = chooser.getSelectedFormat();
1135 value = chooser.showSaveDialog(this);
1136 if (value != JalviewFileChooser.APPROVE_OPTION)
1142 fileName = chooser.getSelectedFile().getPath();
1144 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1146 Cache.setProperty("LAST_DIRECTORY", fileName);
1147 saveAlignment(fileName, currentFileFormat);
1151 public boolean saveAlignment(String file, FileFormatI format)
1153 boolean success = true;
1155 if (FileFormat.Jalview.equals(format))
1157 String shortName = title;
1159 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1161 shortName = shortName.substring(
1162 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1165 success = new Jalview2XML().saveAlignment(this, file, shortName);
1167 statusBar.setText(MessageManager.formatMessage(
1168 "label.successfully_saved_to_file_in_format", new Object[]
1169 { fileName, format }));
1174 AlignmentExportData exportData = getAlignmentForExport(format,
1176 if (exportData.getSettings().isCancelled())
1180 FormatAdapter f = new FormatAdapter(alignPanel,
1181 exportData.getSettings());
1182 String output = f.formatSequences(format, exportData.getAlignment(), // class
1186 // occur in the distant future
1187 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1188 f.getCacheSuffixDefault(format),
1189 viewport.getAlignment().getHiddenColumns());
1199 PrintWriter out = new PrintWriter(new FileWriter(file));
1203 this.setTitle(file);
1204 statusBar.setText(MessageManager.formatMessage(
1205 "label.successfully_saved_to_file_in_format", new Object[]
1206 { fileName, format.getName() }));
1207 } catch (Exception ex)
1210 ex.printStackTrace();
1217 JvOptionPane.showInternalMessageDialog(this, MessageManager
1218 .formatMessage("label.couldnt_save_file", new Object[]
1220 MessageManager.getString("label.error_saving_file"),
1221 JvOptionPane.WARNING_MESSAGE);
1227 private void warningMessage(String warning, String title)
1229 if (new jalview.util.Platform().isHeadless())
1231 System.err.println("Warning: " + title + "\nWarning: " + warning);
1236 JvOptionPane.showInternalMessageDialog(this, warning, title,
1237 JvOptionPane.WARNING_MESSAGE);
1249 protected void outputText_actionPerformed(ActionEvent e)
1251 FileFormatI fileFormat = FileFormats.getInstance()
1252 .forName(e.getActionCommand());
1253 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1255 if (exportData.getSettings().isCancelled())
1259 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1260 cap.setForInput(null);
1263 FileFormatI format = fileFormat;
1264 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1265 .formatSequences(format, exportData.getAlignment(),
1266 exportData.getOmitHidden(),
1267 exportData.getStartEndPostions(),
1268 viewport.getAlignment().getHiddenColumns()));
1269 Desktop.addInternalFrame(cap, MessageManager
1270 .formatMessage("label.alignment_output_command", new Object[]
1271 { e.getActionCommand() }), 600, 500);
1272 } catch (OutOfMemoryError oom)
1274 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1281 public static AlignmentExportData getAlignmentForExport(
1282 FileFormatI format, AlignViewportI viewport,
1283 AlignExportSettingI exportSettings)
1285 AlignmentI alignmentToExport = null;
1286 AlignExportSettingI settings = exportSettings;
1287 String[] omitHidden = null;
1289 HiddenSequences hiddenSeqs = viewport.getAlignment()
1290 .getHiddenSequences();
1292 alignmentToExport = viewport.getAlignment();
1294 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1295 if (settings == null)
1297 settings = new AlignExportSettings(hasHiddenSeqs,
1298 viewport.hasHiddenColumns(), format);
1300 // settings.isExportAnnotations();
1302 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1304 omitHidden = viewport.getViewAsString(false,
1305 settings.isExportHiddenSequences());
1308 int[] alignmentStartEnd = new int[2];
1309 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1311 alignmentToExport = hiddenSeqs.getFullAlignment();
1315 alignmentToExport = viewport.getAlignment();
1317 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1318 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1319 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1320 omitHidden, alignmentStartEnd, settings);
1331 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1333 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1334 htmlSVG.exportHTML(null);
1338 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1340 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1341 bjs.exportHTML(null);
1344 public void createImageMap(File file, String image)
1346 alignPanel.makePNGImageMap(file, image);
1356 public void createPNG(File f)
1358 alignPanel.makePNG(f);
1368 public void createEPS(File f)
1370 alignPanel.makeEPS(f);
1374 public void createSVG(File f)
1376 alignPanel.makeSVG(f);
1380 public void pageSetup_actionPerformed(ActionEvent e)
1382 PrinterJob printJob = PrinterJob.getPrinterJob();
1383 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1393 public void printMenuItem_actionPerformed(ActionEvent e)
1395 // Putting in a thread avoids Swing painting problems
1396 PrintThread thread = new PrintThread(alignPanel);
1401 public void exportFeatures_actionPerformed(ActionEvent e)
1403 new AnnotationExporter().exportFeatures(alignPanel);
1407 public void exportAnnotations_actionPerformed(ActionEvent e)
1409 new AnnotationExporter().exportAnnotations(alignPanel);
1413 public void associatedData_actionPerformed(ActionEvent e)
1415 // Pick the tree file
1416 JalviewFileChooser chooser = new JalviewFileChooser(
1417 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1418 chooser.setFileView(new JalviewFileView());
1419 chooser.setDialogTitle(
1420 MessageManager.getString("label.load_jalview_annotations"));
1421 chooser.setToolTipText(
1422 MessageManager.getString("label.load_jalview_annotations"));
1424 int value = chooser.showOpenDialog(null);
1426 if (value == JalviewFileChooser.APPROVE_OPTION)
1428 String choice = chooser.getSelectedFile().getPath();
1429 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1430 loadJalviewDataFile(choice, null, null, null);
1436 * Close the current view or all views in the alignment frame. If the frame
1437 * only contains one view then the alignment will be removed from memory.
1439 * @param closeAllTabs
1442 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1444 if (alignPanels != null && alignPanels.size() < 2)
1446 closeAllTabs = true;
1451 if (alignPanels != null)
1455 if (this.isClosed())
1457 // really close all the windows - otherwise wait till
1458 // setClosed(true) is called
1459 for (int i = 0; i < alignPanels.size(); i++)
1461 AlignmentPanel ap = alignPanels.get(i);
1468 closeView(alignPanel);
1475 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1476 * be called recursively, with the frame now in 'closed' state
1478 this.setClosed(true);
1480 } catch (Exception ex)
1482 ex.printStackTrace();
1487 * Close the specified panel and close up tabs appropriately.
1489 * @param panelToClose
1491 public void closeView(AlignmentPanel panelToClose)
1493 int index = tabbedPane.getSelectedIndex();
1494 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1495 alignPanels.remove(panelToClose);
1496 panelToClose.closePanel();
1497 panelToClose = null;
1499 tabbedPane.removeTabAt(closedindex);
1500 tabbedPane.validate();
1502 if (index > closedindex || index == tabbedPane.getTabCount())
1504 // modify currently selected tab index if necessary.
1508 this.tabSelectionChanged(index);
1514 void updateEditMenuBar()
1517 if (viewport.getHistoryList().size() > 0)
1519 undoMenuItem.setEnabled(true);
1520 CommandI command = viewport.getHistoryList().peek();
1521 undoMenuItem.setText(MessageManager
1522 .formatMessage("label.undo_command", new Object[]
1523 { command.getDescription() }));
1527 undoMenuItem.setEnabled(false);
1528 undoMenuItem.setText(MessageManager.getString("action.undo"));
1531 if (viewport.getRedoList().size() > 0)
1533 redoMenuItem.setEnabled(true);
1535 CommandI command = viewport.getRedoList().peek();
1536 redoMenuItem.setText(MessageManager
1537 .formatMessage("label.redo_command", new Object[]
1538 { command.getDescription() }));
1542 redoMenuItem.setEnabled(false);
1543 redoMenuItem.setText(MessageManager.getString("action.redo"));
1548 public void addHistoryItem(CommandI command)
1550 if (command.getSize() > 0)
1552 viewport.addToHistoryList(command);
1553 viewport.clearRedoList();
1554 updateEditMenuBar();
1555 viewport.updateHiddenColumns();
1556 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1557 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1558 // viewport.getColumnSelection()
1559 // .getHiddenColumns().size() > 0);
1565 * @return alignment objects for all views
1567 AlignmentI[] getViewAlignments()
1569 if (alignPanels != null)
1571 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1573 for (AlignmentPanel ap : alignPanels)
1575 als[i++] = ap.av.getAlignment();
1579 if (viewport != null)
1581 return new AlignmentI[] { viewport.getAlignment() };
1593 protected void undoMenuItem_actionPerformed(ActionEvent e)
1595 if (viewport.getHistoryList().isEmpty())
1599 CommandI command = viewport.getHistoryList().pop();
1600 viewport.addToRedoList(command);
1601 command.undoCommand(getViewAlignments());
1603 AlignmentViewport originalSource = getOriginatingSource(command);
1604 updateEditMenuBar();
1606 if (originalSource != null)
1608 if (originalSource != viewport)
1611 "Implementation worry: mismatch of viewport origin for undo");
1613 originalSource.updateHiddenColumns();
1614 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1616 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1617 // viewport.getColumnSelection()
1618 // .getHiddenColumns().size() > 0);
1619 originalSource.firePropertyChange("alignment", null,
1620 originalSource.getAlignment().getSequences());
1631 protected void redoMenuItem_actionPerformed(ActionEvent e)
1633 if (viewport.getRedoList().size() < 1)
1638 CommandI command = viewport.getRedoList().pop();
1639 viewport.addToHistoryList(command);
1640 command.doCommand(getViewAlignments());
1642 AlignmentViewport originalSource = getOriginatingSource(command);
1643 updateEditMenuBar();
1645 if (originalSource != null)
1648 if (originalSource != viewport)
1651 "Implementation worry: mismatch of viewport origin for redo");
1653 originalSource.updateHiddenColumns();
1654 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1656 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1657 // viewport.getColumnSelection()
1658 // .getHiddenColumns().size() > 0);
1659 originalSource.firePropertyChange("alignment", null,
1660 originalSource.getAlignment().getSequences());
1664 AlignmentViewport getOriginatingSource(CommandI command)
1666 AlignmentViewport originalSource = null;
1667 // For sequence removal and addition, we need to fire
1668 // the property change event FROM the viewport where the
1669 // original alignment was altered
1670 AlignmentI al = null;
1671 if (command instanceof EditCommand)
1673 EditCommand editCommand = (EditCommand) command;
1674 al = editCommand.getAlignment();
1675 List<Component> comps = PaintRefresher.components
1676 .get(viewport.getSequenceSetId());
1678 for (Component comp : comps)
1680 if (comp instanceof AlignmentPanel)
1682 if (al == ((AlignmentPanel) comp).av.getAlignment())
1684 originalSource = ((AlignmentPanel) comp).av;
1691 if (originalSource == null)
1693 // The original view is closed, we must validate
1694 // the current view against the closed view first
1697 PaintRefresher.validateSequences(al, viewport.getAlignment());
1700 originalSource = viewport;
1703 return originalSource;
1712 public void moveSelectedSequences(boolean up)
1714 SequenceGroup sg = viewport.getSelectionGroup();
1720 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1721 viewport.getHiddenRepSequences(), up);
1722 alignPanel.paintAlignment(true, false);
1725 synchronized void slideSequences(boolean right, int size)
1727 List<SequenceI> sg = new ArrayList<>();
1728 if (viewport.cursorMode)
1730 sg.add(viewport.getAlignment()
1731 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1733 else if (viewport.getSelectionGroup() != null
1734 && viewport.getSelectionGroup().getSize() != viewport
1735 .getAlignment().getHeight())
1737 sg = viewport.getSelectionGroup()
1738 .getSequences(viewport.getHiddenRepSequences());
1746 List<SequenceI> invertGroup = new ArrayList<>();
1748 for (SequenceI seq : viewport.getAlignment().getSequences())
1750 if (!sg.contains(seq))
1752 invertGroup.add(seq);
1756 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1758 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1759 for (int i = 0; i < invertGroup.size(); i++)
1761 seqs2[i] = invertGroup.get(i);
1764 SlideSequencesCommand ssc;
1767 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1768 viewport.getGapCharacter());
1772 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1773 viewport.getGapCharacter());
1776 int groupAdjustment = 0;
1777 if (ssc.getGapsInsertedBegin() && right)
1779 if (viewport.cursorMode)
1781 alignPanel.getSeqPanel().moveCursor(size, 0);
1785 groupAdjustment = size;
1788 else if (!ssc.getGapsInsertedBegin() && !right)
1790 if (viewport.cursorMode)
1792 alignPanel.getSeqPanel().moveCursor(-size, 0);
1796 groupAdjustment = -size;
1800 if (groupAdjustment != 0)
1802 viewport.getSelectionGroup().setStartRes(
1803 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1804 viewport.getSelectionGroup().setEndRes(
1805 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1809 * just extend the last slide command if compatible; but not if in
1810 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1812 boolean appendHistoryItem = false;
1813 Deque<CommandI> historyList = viewport.getHistoryList();
1814 boolean inSplitFrame = getSplitViewContainer() != null;
1815 if (!inSplitFrame && historyList != null && historyList.size() > 0
1816 && historyList.peek() instanceof SlideSequencesCommand)
1818 appendHistoryItem = ssc.appendSlideCommand(
1819 (SlideSequencesCommand) historyList.peek());
1822 if (!appendHistoryItem)
1824 addHistoryItem(ssc);
1837 protected void copy_actionPerformed(ActionEvent e)
1840 if (viewport.getSelectionGroup() == null)
1844 // TODO: preserve the ordering of displayed alignment annotation in any
1845 // internal paste (particularly sequence associated annotation)
1846 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1847 String[] omitHidden = null;
1849 if (viewport.hasHiddenColumns())
1851 omitHidden = viewport.getViewAsString(true);
1854 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1855 seqs, omitHidden, null);
1857 StringSelection ss = new StringSelection(output);
1861 jalview.gui.Desktop.internalCopy = true;
1862 // Its really worth setting the clipboard contents
1863 // to empty before setting the large StringSelection!!
1864 Toolkit.getDefaultToolkit().getSystemClipboard()
1865 .setContents(new StringSelection(""), null);
1867 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1869 } catch (OutOfMemoryError er)
1871 new OOMWarning("copying region", er);
1875 ArrayList<int[]> hiddenColumns = null;
1876 if (viewport.hasHiddenColumns())
1878 hiddenColumns = new ArrayList<>();
1879 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1880 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1881 ArrayList<int[]> hiddenRegions = viewport.getAlignment()
1882 .getHiddenColumns().getHiddenColumnsCopy();
1883 for (int[] region : hiddenRegions)
1885 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1889 { region[0] - hiddenOffset, region[1] - hiddenOffset });
1894 Desktop.jalviewClipboard = new Object[] { seqs,
1895 viewport.getAlignment().getDataset(), hiddenColumns };
1896 statusBar.setText(MessageManager.formatMessage(
1897 "label.copied_sequences_to_clipboard", new Object[]
1898 { Integer.valueOf(seqs.length).toString() }));
1908 protected void pasteNew_actionPerformed(ActionEvent e)
1920 protected void pasteThis_actionPerformed(ActionEvent e)
1926 * Paste contents of Jalview clipboard
1928 * @param newAlignment
1929 * true to paste to a new alignment, otherwise add to this.
1931 void paste(boolean newAlignment)
1933 boolean externalPaste = true;
1936 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1937 Transferable contents = c.getContents(this);
1939 if (contents == null)
1948 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1949 if (str.length() < 1)
1954 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1956 } catch (OutOfMemoryError er)
1958 new OOMWarning("Out of memory pasting sequences!!", er);
1962 SequenceI[] sequences;
1963 boolean annotationAdded = false;
1964 AlignmentI alignment = null;
1966 if (Desktop.jalviewClipboard != null)
1968 // The clipboard was filled from within Jalview, we must use the
1970 // And dataset from the copied alignment
1971 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1972 // be doubly sure that we create *new* sequence objects.
1973 sequences = new SequenceI[newseq.length];
1974 for (int i = 0; i < newseq.length; i++)
1976 sequences[i] = new Sequence(newseq[i]);
1978 alignment = new Alignment(sequences);
1979 externalPaste = false;
1983 // parse the clipboard as an alignment.
1984 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
1986 sequences = alignment.getSequencesArray();
1990 ArrayList<Integer> newGraphGroups = new ArrayList<>();
1996 if (Desktop.jalviewClipboard != null)
1998 // dataset is inherited
1999 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2003 // new dataset is constructed
2004 alignment.setDataset(null);
2006 alwidth = alignment.getWidth() + 1;
2010 AlignmentI pastedal = alignment; // preserve pasted alignment object
2011 // Add pasted sequences and dataset into existing alignment.
2012 alignment = viewport.getAlignment();
2013 alwidth = alignment.getWidth() + 1;
2014 // decide if we need to import sequences from an existing dataset
2015 boolean importDs = Desktop.jalviewClipboard != null
2016 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2017 // importDs==true instructs us to copy over new dataset sequences from
2018 // an existing alignment
2019 Vector newDs = (importDs) ? new Vector() : null; // used to create
2020 // minimum dataset set
2022 for (int i = 0; i < sequences.length; i++)
2026 newDs.addElement(null);
2028 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2030 if (importDs && ds != null)
2032 if (!newDs.contains(ds))
2034 newDs.setElementAt(ds, i);
2035 ds = new Sequence(ds);
2036 // update with new dataset sequence
2037 sequences[i].setDatasetSequence(ds);
2041 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2046 // copy and derive new dataset sequence
2047 sequences[i] = sequences[i].deriveSequence();
2048 alignment.getDataset()
2049 .addSequence(sequences[i].getDatasetSequence());
2050 // TODO: avoid creation of duplicate dataset sequences with a
2051 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2053 alignment.addSequence(sequences[i]); // merges dataset
2057 newDs.clear(); // tidy up
2059 if (alignment.getAlignmentAnnotation() != null)
2061 for (AlignmentAnnotation alan : alignment
2062 .getAlignmentAnnotation())
2064 if (alan.graphGroup > fgroup)
2066 fgroup = alan.graphGroup;
2070 if (pastedal.getAlignmentAnnotation() != null)
2072 // Add any annotation attached to alignment.
2073 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2074 for (int i = 0; i < alann.length; i++)
2076 annotationAdded = true;
2077 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2079 AlignmentAnnotation newann = new AlignmentAnnotation(
2081 if (newann.graphGroup > -1)
2083 if (newGraphGroups.size() <= newann.graphGroup
2084 || newGraphGroups.get(newann.graphGroup) == null)
2086 for (int q = newGraphGroups
2087 .size(); q <= newann.graphGroup; q++)
2089 newGraphGroups.add(q, null);
2091 newGraphGroups.set(newann.graphGroup,
2092 new Integer(++fgroup));
2094 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2098 newann.padAnnotation(alwidth);
2099 alignment.addAnnotation(newann);
2109 addHistoryItem(new EditCommand(
2110 MessageManager.getString("label.add_sequences"),
2111 Action.PASTE, sequences, 0, alignment.getWidth(),
2114 // Add any annotations attached to sequences
2115 for (int i = 0; i < sequences.length; i++)
2117 if (sequences[i].getAnnotation() != null)
2119 AlignmentAnnotation newann;
2120 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2122 annotationAdded = true;
2123 newann = sequences[i].getAnnotation()[a];
2124 newann.adjustForAlignment();
2125 newann.padAnnotation(alwidth);
2126 if (newann.graphGroup > -1)
2128 if (newann.graphGroup > -1)
2130 if (newGraphGroups.size() <= newann.graphGroup
2131 || newGraphGroups.get(newann.graphGroup) == null)
2133 for (int q = newGraphGroups
2134 .size(); q <= newann.graphGroup; q++)
2136 newGraphGroups.add(q, null);
2138 newGraphGroups.set(newann.graphGroup,
2139 new Integer(++fgroup));
2141 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2145 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2149 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2157 // propagate alignment changed.
2158 viewport.getRanges().setEndSeq(alignment.getHeight());
2159 if (annotationAdded)
2161 // Duplicate sequence annotation in all views.
2162 AlignmentI[] alview = this.getViewAlignments();
2163 for (int i = 0; i < sequences.length; i++)
2165 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2170 for (int avnum = 0; avnum < alview.length; avnum++)
2172 if (alview[avnum] != alignment)
2174 // duplicate in a view other than the one with input focus
2175 int avwidth = alview[avnum].getWidth() + 1;
2176 // this relies on sann being preserved after we
2177 // modify the sequence's annotation array for each duplication
2178 for (int a = 0; a < sann.length; a++)
2180 AlignmentAnnotation newann = new AlignmentAnnotation(
2182 sequences[i].addAlignmentAnnotation(newann);
2183 newann.padAnnotation(avwidth);
2184 alview[avnum].addAnnotation(newann); // annotation was
2185 // duplicated earlier
2186 // TODO JAL-1145 graphGroups are not updated for sequence
2187 // annotation added to several views. This may cause
2189 alview[avnum].setAnnotationIndex(newann, a);
2194 buildSortByAnnotationScoresMenu();
2196 viewport.firePropertyChange("alignment", null,
2197 alignment.getSequences());
2198 if (alignPanels != null)
2200 for (AlignmentPanel ap : alignPanels)
2202 ap.validateAnnotationDimensions(false);
2207 alignPanel.validateAnnotationDimensions(false);
2213 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2215 String newtitle = new String("Copied sequences");
2217 if (Desktop.jalviewClipboard != null
2218 && Desktop.jalviewClipboard[2] != null)
2220 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2221 for (int[] region : hc)
2223 af.viewport.hideColumns(region[0], region[1]);
2227 // >>>This is a fix for the moment, until a better solution is
2229 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2230 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2231 .getFeatureRenderer());
2233 // TODO: maintain provenance of an alignment, rather than just make the
2234 // title a concatenation of operations.
2237 if (title.startsWith("Copied sequences"))
2243 newtitle = newtitle.concat("- from " + title);
2248 newtitle = new String("Pasted sequences");
2251 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2256 } catch (Exception ex)
2258 ex.printStackTrace();
2259 System.out.println("Exception whilst pasting: " + ex);
2260 // could be anything being pasted in here
2266 protected void expand_newalign(ActionEvent e)
2270 AlignmentI alignment = AlignmentUtils
2271 .expandContext(getViewport().getAlignment(), -1);
2272 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2274 String newtitle = new String("Flanking alignment");
2276 if (Desktop.jalviewClipboard != null
2277 && Desktop.jalviewClipboard[2] != null)
2279 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2280 for (int region[] : hc)
2282 af.viewport.hideColumns(region[0], region[1]);
2286 // >>>This is a fix for the moment, until a better solution is
2288 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2289 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2290 .getFeatureRenderer());
2292 // TODO: maintain provenance of an alignment, rather than just make the
2293 // title a concatenation of operations.
2295 if (title.startsWith("Copied sequences"))
2301 newtitle = newtitle.concat("- from " + title);
2305 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2307 } catch (Exception ex)
2309 ex.printStackTrace();
2310 System.out.println("Exception whilst pasting: " + ex);
2311 // could be anything being pasted in here
2312 } catch (OutOfMemoryError oom)
2314 new OOMWarning("Viewing flanking region of alignment", oom);
2325 protected void cut_actionPerformed(ActionEvent e)
2327 copy_actionPerformed(null);
2328 delete_actionPerformed(null);
2338 protected void delete_actionPerformed(ActionEvent evt)
2341 SequenceGroup sg = viewport.getSelectionGroup();
2348 * If the cut affects all sequences, warn, remove highlighted columns
2350 if (sg.getSize() == viewport.getAlignment().getHeight())
2352 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2353 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2354 if (isEntireAlignWidth)
2356 int confirm = JvOptionPane.showConfirmDialog(this,
2357 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2358 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2359 JvOptionPane.OK_CANCEL_OPTION);
2361 if (confirm == JvOptionPane.CANCEL_OPTION
2362 || confirm == JvOptionPane.CLOSED_OPTION)
2367 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2368 sg.getEndRes() + 1);
2370 SequenceI[] cut = sg.getSequences()
2371 .toArray(new SequenceI[sg.getSize()]);
2373 addHistoryItem(new EditCommand(
2374 MessageManager.getString("label.cut_sequences"), Action.CUT,
2375 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2376 viewport.getAlignment()));
2378 viewport.setSelectionGroup(null);
2379 viewport.sendSelection();
2380 viewport.getAlignment().deleteGroup(sg);
2382 viewport.firePropertyChange("alignment", null,
2383 viewport.getAlignment().getSequences());
2384 if (viewport.getAlignment().getHeight() < 1)
2388 this.setClosed(true);
2389 } catch (Exception ex)
2402 protected void deleteGroups_actionPerformed(ActionEvent e)
2404 if (avc.deleteGroups())
2406 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2407 alignPanel.updateAnnotation();
2408 alignPanel.paintAlignment(true, true);
2419 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2421 SequenceGroup sg = new SequenceGroup();
2423 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2425 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2428 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2429 viewport.setSelectionGroup(sg);
2430 viewport.sendSelection();
2431 // JAL-2034 - should delegate to
2432 // alignPanel to decide if overview needs
2434 alignPanel.paintAlignment(false, false);
2435 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2445 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2447 if (viewport.cursorMode)
2449 alignPanel.getSeqPanel().keyboardNo1 = null;
2450 alignPanel.getSeqPanel().keyboardNo2 = null;
2452 viewport.setSelectionGroup(null);
2453 viewport.getColumnSelection().clear();
2454 viewport.setSelectionGroup(null);
2455 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2456 // JAL-2034 - should delegate to
2457 // alignPanel to decide if overview needs
2459 alignPanel.paintAlignment(false, false);
2460 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2461 viewport.sendSelection();
2471 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2473 SequenceGroup sg = viewport.getSelectionGroup();
2477 selectAllSequenceMenuItem_actionPerformed(null);
2482 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2484 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2486 // JAL-2034 - should delegate to
2487 // alignPanel to decide if overview needs
2490 alignPanel.paintAlignment(true, false);
2491 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2492 viewport.sendSelection();
2496 public void invertColSel_actionPerformed(ActionEvent e)
2498 viewport.invertColumnSelection();
2499 alignPanel.paintAlignment(true, false);
2500 viewport.sendSelection();
2510 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2512 trimAlignment(true);
2522 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2524 trimAlignment(false);
2527 void trimAlignment(boolean trimLeft)
2529 ColumnSelection colSel = viewport.getColumnSelection();
2532 if (!colSel.isEmpty())
2536 column = colSel.getMin();
2540 column = colSel.getMax();
2544 if (viewport.getSelectionGroup() != null)
2546 seqs = viewport.getSelectionGroup()
2547 .getSequencesAsArray(viewport.getHiddenRepSequences());
2551 seqs = viewport.getAlignment().getSequencesArray();
2554 TrimRegionCommand trimRegion;
2557 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2558 column, viewport.getAlignment());
2559 viewport.getRanges().setStartRes(0);
2563 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2564 column, viewport.getAlignment());
2567 statusBar.setText(MessageManager
2568 .formatMessage("label.removed_columns", new String[]
2569 { Integer.valueOf(trimRegion.getSize()).toString() }));
2571 addHistoryItem(trimRegion);
2573 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2575 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2576 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2578 viewport.getAlignment().deleteGroup(sg);
2582 viewport.firePropertyChange("alignment", null,
2583 viewport.getAlignment().getSequences());
2594 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2596 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2599 if (viewport.getSelectionGroup() != null)
2601 seqs = viewport.getSelectionGroup()
2602 .getSequencesAsArray(viewport.getHiddenRepSequences());
2603 start = viewport.getSelectionGroup().getStartRes();
2604 end = viewport.getSelectionGroup().getEndRes();
2608 seqs = viewport.getAlignment().getSequencesArray();
2611 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2612 "Remove Gapped Columns", seqs, start, end,
2613 viewport.getAlignment());
2615 addHistoryItem(removeGapCols);
2617 statusBar.setText(MessageManager
2618 .formatMessage("label.removed_empty_columns", new Object[]
2619 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2621 // This is to maintain viewport position on first residue
2622 // of first sequence
2623 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2624 ViewportRanges ranges = viewport.getRanges();
2625 int startRes = seq.findPosition(ranges.getStartRes());
2626 // ShiftList shifts;
2627 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2628 // edit.alColumnChanges=shifts.getInverse();
2629 // if (viewport.hasHiddenColumns)
2630 // viewport.getColumnSelection().compensateForEdits(shifts);
2631 ranges.setStartRes(seq.findIndex(startRes) - 1);
2632 viewport.firePropertyChange("alignment", null,
2633 viewport.getAlignment().getSequences());
2644 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2646 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2649 if (viewport.getSelectionGroup() != null)
2651 seqs = viewport.getSelectionGroup()
2652 .getSequencesAsArray(viewport.getHiddenRepSequences());
2653 start = viewport.getSelectionGroup().getStartRes();
2654 end = viewport.getSelectionGroup().getEndRes();
2658 seqs = viewport.getAlignment().getSequencesArray();
2661 // This is to maintain viewport position on first residue
2662 // of first sequence
2663 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2664 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2666 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2667 viewport.getAlignment()));
2669 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2671 viewport.firePropertyChange("alignment", null,
2672 viewport.getAlignment().getSequences());
2683 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2685 viewport.setPadGaps(padGapsMenuitem.isSelected());
2686 viewport.firePropertyChange("alignment", null,
2687 viewport.getAlignment().getSequences());
2697 public void findMenuItem_actionPerformed(ActionEvent e)
2703 * Create a new view of the current alignment.
2706 public void newView_actionPerformed(ActionEvent e)
2708 newView(null, true);
2712 * Creates and shows a new view of the current alignment.
2715 * title of newly created view; if null, one will be generated
2716 * @param copyAnnotation
2717 * if true then duplicate all annnotation, groups and settings
2718 * @return new alignment panel, already displayed.
2720 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2723 * Create a new AlignmentPanel (with its own, new Viewport)
2725 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2726 if (!copyAnnotation)
2729 * remove all groups and annotation except for the automatic stuff
2731 newap.av.getAlignment().deleteAllGroups();
2732 newap.av.getAlignment().deleteAllAnnotations(false);
2735 newap.av.setGatherViewsHere(false);
2737 if (viewport.viewName == null)
2739 viewport.viewName = MessageManager
2740 .getString("label.view_name_original");
2744 * Views share the same edits undo and redo stacks
2746 newap.av.setHistoryList(viewport.getHistoryList());
2747 newap.av.setRedoList(viewport.getRedoList());
2750 * Views share the same mappings; need to deregister any new mappings
2751 * created by copyAlignPanel, and register the new reference to the shared
2754 newap.av.replaceMappings(viewport.getAlignment());
2757 * start up cDNA consensus (if applicable) now mappings are in place
2759 if (newap.av.initComplementConsensus())
2761 newap.refresh(true); // adjust layout of annotations
2764 newap.av.viewName = getNewViewName(viewTitle);
2766 addAlignmentPanel(newap, true);
2767 newap.alignmentChanged();
2769 if (alignPanels.size() == 2)
2771 viewport.setGatherViewsHere(true);
2773 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2778 * Make a new name for the view, ensuring it is unique within the current
2779 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2780 * these now use viewId. Unique view names are still desirable for usability.)
2785 protected String getNewViewName(String viewTitle)
2787 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2788 boolean addFirstIndex = false;
2789 if (viewTitle == null || viewTitle.trim().length() == 0)
2791 viewTitle = MessageManager.getString("action.view");
2792 addFirstIndex = true;
2796 index = 1;// we count from 1 if given a specific name
2798 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2800 List<Component> comps = PaintRefresher.components
2801 .get(viewport.getSequenceSetId());
2803 List<String> existingNames = getExistingViewNames(comps);
2805 while (existingNames.contains(newViewName))
2807 newViewName = viewTitle + " " + (++index);
2813 * Returns a list of distinct view names found in the given list of
2814 * components. View names are held on the viewport of an AlignmentPanel.
2819 protected List<String> getExistingViewNames(List<Component> comps)
2821 List<String> existingNames = new ArrayList<>();
2822 for (Component comp : comps)
2824 if (comp instanceof AlignmentPanel)
2826 AlignmentPanel ap = (AlignmentPanel) comp;
2827 if (!existingNames.contains(ap.av.viewName))
2829 existingNames.add(ap.av.viewName);
2833 return existingNames;
2837 * Explode tabbed views into separate windows.
2840 public void expandViews_actionPerformed(ActionEvent e)
2842 Desktop.explodeViews(this);
2846 * Gather views in separate windows back into a tabbed presentation.
2849 public void gatherViews_actionPerformed(ActionEvent e)
2851 Desktop.instance.gatherViews(this);
2861 public void font_actionPerformed(ActionEvent e)
2863 new FontChooser(alignPanel);
2873 protected void seqLimit_actionPerformed(ActionEvent e)
2875 viewport.setShowJVSuffix(seqLimits.isSelected());
2877 alignPanel.getIdPanel().getIdCanvas()
2878 .setPreferredSize(alignPanel.calculateIdWidth());
2879 alignPanel.paintAlignment(true, false);
2883 public void idRightAlign_actionPerformed(ActionEvent e)
2885 viewport.setRightAlignIds(idRightAlign.isSelected());
2886 alignPanel.paintAlignment(false, false);
2890 public void centreColumnLabels_actionPerformed(ActionEvent e)
2892 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2893 alignPanel.paintAlignment(false, false);
2899 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2902 protected void followHighlight_actionPerformed()
2905 * Set the 'follow' flag on the Viewport (and scroll to position if now
2908 final boolean state = this.followHighlightMenuItem.getState();
2909 viewport.setFollowHighlight(state);
2912 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2923 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2925 viewport.setColourText(colourTextMenuItem.isSelected());
2926 alignPanel.paintAlignment(false, false);
2936 public void wrapMenuItem_actionPerformed(ActionEvent e)
2938 scaleAbove.setVisible(wrapMenuItem.isSelected());
2939 scaleLeft.setVisible(wrapMenuItem.isSelected());
2940 scaleRight.setVisible(wrapMenuItem.isSelected());
2941 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2942 alignPanel.updateLayout();
2946 public void showAllSeqs_actionPerformed(ActionEvent e)
2948 viewport.showAllHiddenSeqs();
2952 public void showAllColumns_actionPerformed(ActionEvent e)
2954 viewport.showAllHiddenColumns();
2955 alignPanel.paintAlignment(true, true);
2956 viewport.sendSelection();
2960 public void hideSelSequences_actionPerformed(ActionEvent e)
2962 viewport.hideAllSelectedSeqs();
2966 * called by key handler and the hide all/show all menu items
2971 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2974 boolean hide = false;
2975 SequenceGroup sg = viewport.getSelectionGroup();
2976 if (!toggleSeqs && !toggleCols)
2978 // Hide everything by the current selection - this is a hack - we do the
2979 // invert and then hide
2980 // first check that there will be visible columns after the invert.
2981 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2982 && sg.getStartRes() <= sg.getEndRes()))
2984 // now invert the sequence set, if required - empty selection implies
2985 // that no hiding is required.
2988 invertSequenceMenuItem_actionPerformed(null);
2989 sg = viewport.getSelectionGroup();
2993 viewport.expandColSelection(sg, true);
2994 // finally invert the column selection and get the new sequence
2996 invertColSel_actionPerformed(null);
3003 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3005 hideSelSequences_actionPerformed(null);
3008 else if (!(toggleCols && viewport.hasSelectedColumns()))
3010 showAllSeqs_actionPerformed(null);
3016 if (viewport.hasSelectedColumns())
3018 hideSelColumns_actionPerformed(null);
3021 viewport.setSelectionGroup(sg);
3026 showAllColumns_actionPerformed(null);
3035 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3036 * event.ActionEvent)
3039 public void hideAllButSelection_actionPerformed(ActionEvent e)
3041 toggleHiddenRegions(false, false);
3042 viewport.sendSelection();
3049 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3053 public void hideAllSelection_actionPerformed(ActionEvent e)
3055 SequenceGroup sg = viewport.getSelectionGroup();
3056 viewport.expandColSelection(sg, false);
3057 viewport.hideAllSelectedSeqs();
3058 viewport.hideSelectedColumns();
3059 alignPanel.paintAlignment(true, true);
3060 viewport.sendSelection();
3067 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3071 public void showAllhidden_actionPerformed(ActionEvent e)
3073 viewport.showAllHiddenColumns();
3074 viewport.showAllHiddenSeqs();
3075 alignPanel.paintAlignment(true, true);
3076 viewport.sendSelection();
3080 public void hideSelColumns_actionPerformed(ActionEvent e)
3082 viewport.hideSelectedColumns();
3083 alignPanel.paintAlignment(true, true);
3084 viewport.sendSelection();
3088 public void hiddenMarkers_actionPerformed(ActionEvent e)
3090 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3101 protected void scaleAbove_actionPerformed(ActionEvent e)
3103 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3104 // TODO: do we actually need to update overview for scale above change ?
3105 alignPanel.paintAlignment(true, false);
3115 protected void scaleLeft_actionPerformed(ActionEvent e)
3117 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3118 alignPanel.paintAlignment(true, false);
3128 protected void scaleRight_actionPerformed(ActionEvent e)
3130 viewport.setScaleRightWrapped(scaleRight.isSelected());
3131 alignPanel.paintAlignment(true, false);
3141 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3143 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3144 alignPanel.paintAlignment(false, false);
3154 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3156 viewport.setShowText(viewTextMenuItem.isSelected());
3157 alignPanel.paintAlignment(false, false);
3167 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3169 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3170 alignPanel.paintAlignment(false, false);
3173 public FeatureSettings featureSettings;
3176 public FeatureSettingsControllerI getFeatureSettingsUI()
3178 return featureSettings;
3182 public void featureSettings_actionPerformed(ActionEvent e)
3184 if (featureSettings != null)
3186 featureSettings.close();
3187 featureSettings = null;
3189 if (!showSeqFeatures.isSelected())
3191 // make sure features are actually displayed
3192 showSeqFeatures.setSelected(true);
3193 showSeqFeatures_actionPerformed(null);
3195 featureSettings = new FeatureSettings(this);
3199 * Set or clear 'Show Sequence Features'
3205 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3207 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3208 alignPanel.paintAlignment(true, true);
3212 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3213 * the annotations panel as a whole.
3215 * The options to show/hide all annotations should be enabled when the panel
3216 * is shown, and disabled when the panel is hidden.
3221 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3223 final boolean setVisible = annotationPanelMenuItem.isSelected();
3224 viewport.setShowAnnotation(setVisible);
3225 this.showAllSeqAnnotations.setEnabled(setVisible);
3226 this.hideAllSeqAnnotations.setEnabled(setVisible);
3227 this.showAllAlAnnotations.setEnabled(setVisible);
3228 this.hideAllAlAnnotations.setEnabled(setVisible);
3229 alignPanel.updateLayout();
3233 public void alignmentProperties()
3235 JEditorPane editPane = new JEditorPane("text/html", "");
3236 editPane.setEditable(false);
3237 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3240 MessageManager.formatMessage("label.html_content", new Object[]
3241 { contents.toString() }));
3242 JInternalFrame frame = new JInternalFrame();
3243 frame.getContentPane().add(new JScrollPane(editPane));
3245 Desktop.addInternalFrame(frame, MessageManager
3246 .formatMessage("label.alignment_properties", new Object[]
3247 { getTitle() }), 500, 400);
3257 public void overviewMenuItem_actionPerformed(ActionEvent e)
3259 if (alignPanel.overviewPanel != null)
3264 JInternalFrame frame = new JInternalFrame();
3265 final OverviewPanel overview = new OverviewPanel(alignPanel);
3266 frame.setContentPane(overview);
3267 Desktop.addInternalFrame(frame, MessageManager
3268 .formatMessage("label.overview_params", new Object[]
3269 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3272 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3273 frame.addInternalFrameListener(
3274 new javax.swing.event.InternalFrameAdapter()
3277 public void internalFrameClosed(
3278 javax.swing.event.InternalFrameEvent evt)
3281 alignPanel.setOverviewPanel(null);
3285 alignPanel.setOverviewPanel(overview);
3289 public void textColour_actionPerformed()
3291 new TextColourChooser().chooseColour(alignPanel, null);
3295 * public void covariationColour_actionPerformed() {
3297 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3301 public void annotationColour_actionPerformed()
3303 new AnnotationColourChooser(viewport, alignPanel);
3307 public void annotationColumn_actionPerformed(ActionEvent e)
3309 new AnnotationColumnChooser(viewport, alignPanel);
3313 * Action on the user checking or unchecking the option to apply the selected
3314 * colour scheme to all groups. If unchecked, groups may have their own
3315 * independent colour schemes.
3320 public void applyToAllGroups_actionPerformed(boolean selected)
3322 viewport.setColourAppliesToAllGroups(selected);
3326 * Action on user selecting a colour from the colour menu
3329 * the name (not the menu item label!) of the colour scheme
3332 public void changeColour_actionPerformed(String name)
3335 * 'User Defined' opens a panel to configure or load a
3336 * user-defined colour scheme
3338 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3340 new UserDefinedColours(alignPanel);
3345 * otherwise set the chosen colour scheme (or null for 'None')
3347 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3348 viewport.getAlignment(), viewport.getHiddenRepSequences());
3353 * Actions on setting or changing the alignment colour scheme
3358 public void changeColour(ColourSchemeI cs)
3360 // TODO: pull up to controller method
3361 ColourMenuHelper.setColourSelected(colourMenu, cs);
3363 viewport.setGlobalColourScheme(cs);
3365 alignPanel.paintAlignment(true, true);
3369 * Show the PID threshold slider panel
3372 protected void modifyPID_actionPerformed()
3374 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3375 alignPanel.getViewName());
3376 SliderPanel.showPIDSlider();
3380 * Show the Conservation slider panel
3383 protected void modifyConservation_actionPerformed()
3385 SliderPanel.setConservationSlider(alignPanel,
3386 viewport.getResidueShading(), alignPanel.getViewName());
3387 SliderPanel.showConservationSlider();
3391 * Action on selecting or deselecting (Colour) By Conservation
3394 public void conservationMenuItem_actionPerformed(boolean selected)
3396 modifyConservation.setEnabled(selected);
3397 viewport.setConservationSelected(selected);
3398 viewport.getResidueShading().setConservationApplied(selected);
3400 changeColour(viewport.getGlobalColourScheme());
3403 modifyConservation_actionPerformed();
3407 SliderPanel.hideConservationSlider();
3412 * Action on selecting or deselecting (Colour) Above PID Threshold
3415 public void abovePIDThreshold_actionPerformed(boolean selected)
3417 modifyPID.setEnabled(selected);
3418 viewport.setAbovePIDThreshold(selected);
3421 viewport.getResidueShading().setThreshold(0,
3422 viewport.isIgnoreGapsConsensus());
3425 changeColour(viewport.getGlobalColourScheme());
3428 modifyPID_actionPerformed();
3432 SliderPanel.hidePIDSlider();
3443 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3445 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3446 AlignmentSorter.sortByPID(viewport.getAlignment(),
3447 viewport.getAlignment().getSequenceAt(0));
3448 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3449 viewport.getAlignment()));
3450 alignPanel.paintAlignment(true, false);
3460 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3462 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3463 AlignmentSorter.sortByID(viewport.getAlignment());
3465 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3466 alignPanel.paintAlignment(true, false);
3476 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3478 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3479 AlignmentSorter.sortByLength(viewport.getAlignment());
3480 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3481 viewport.getAlignment()));
3482 alignPanel.paintAlignment(true, false);
3492 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3494 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3495 AlignmentSorter.sortByGroup(viewport.getAlignment());
3496 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3497 viewport.getAlignment()));
3499 alignPanel.paintAlignment(true, false);
3509 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3511 new RedundancyPanel(alignPanel, this);
3521 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3523 if ((viewport.getSelectionGroup() == null)
3524 || (viewport.getSelectionGroup().getSize() < 2))
3526 JvOptionPane.showInternalMessageDialog(this,
3527 MessageManager.getString(
3528 "label.you_must_select_least_two_sequences"),
3529 MessageManager.getString("label.invalid_selection"),
3530 JvOptionPane.WARNING_MESSAGE);
3534 JInternalFrame frame = new JInternalFrame();
3535 frame.setContentPane(new PairwiseAlignPanel(viewport));
3536 Desktop.addInternalFrame(frame,
3537 MessageManager.getString("action.pairwise_alignment"), 600,
3543 public void autoCalculate_actionPerformed(ActionEvent e)
3545 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3546 if (viewport.autoCalculateConsensus)
3548 viewport.firePropertyChange("alignment", null,
3549 viewport.getAlignment().getSequences());
3554 public void sortByTreeOption_actionPerformed(ActionEvent e)
3556 viewport.sortByTree = sortByTree.isSelected();
3560 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3562 viewport.followSelection = listenToViewSelections.isSelected();
3566 * Constructs a tree panel and adds it to the desktop
3575 void newTreePanel(TreeModel tree, String treeAlgo,
3576 String substitutionMatrix)
3578 String frameTitle = "";
3581 boolean onSelection = false;
3582 if (viewport.getSelectionGroup() != null
3583 && viewport.getSelectionGroup().getSize() > 0)
3585 SequenceGroup sg = viewport.getSelectionGroup();
3587 /* Decide if the selection is a column region */
3588 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3590 if (_s.getLength() < sg.getEndRes())
3592 JvOptionPane.showMessageDialog(Desktop.desktop,
3593 MessageManager.getString(
3594 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3595 MessageManager.getString(
3596 "label.sequences_selection_not_aligned"),
3597 JvOptionPane.WARNING_MESSAGE);
3606 if (viewport.getAlignment().getHeight() < 2)
3612 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3613 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3615 frameTitle += " from ";
3617 if (viewport.viewName != null)
3619 frameTitle += viewport.viewName + " of ";
3622 frameTitle += this.title;
3624 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3635 public void addSortByOrderMenuItem(String title,
3636 final AlignmentOrder order)
3638 final JMenuItem item = new JMenuItem(MessageManager
3639 .formatMessage("action.by_title_param", new Object[]
3642 item.addActionListener(new java.awt.event.ActionListener()
3645 public void actionPerformed(ActionEvent e)
3647 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3649 // TODO: JBPNote - have to map order entries to curent SequenceI
3651 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3653 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3654 viewport.getAlignment()));
3656 alignPanel.paintAlignment(true, false);
3662 * Add a new sort by annotation score menu item
3665 * the menu to add the option to
3667 * the label used to retrieve scores for each sequence on the
3670 public void addSortByAnnotScoreMenuItem(JMenu sort,
3671 final String scoreLabel)
3673 final JMenuItem item = new JMenuItem(scoreLabel);
3675 item.addActionListener(new java.awt.event.ActionListener()
3678 public void actionPerformed(ActionEvent e)
3680 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3681 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3682 viewport.getAlignment());// ,viewport.getSelectionGroup());
3683 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3684 viewport.getAlignment()));
3685 alignPanel.paintAlignment(true, false);
3691 * last hash for alignment's annotation array - used to minimise cost of
3694 protected int _annotationScoreVectorHash;
3697 * search the alignment and rebuild the sort by annotation score submenu the
3698 * last alignment annotation vector hash is stored to minimize cost of
3699 * rebuilding in subsequence calls.
3703 public void buildSortByAnnotationScoresMenu()
3705 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3710 if (viewport.getAlignment().getAlignmentAnnotation()
3711 .hashCode() != _annotationScoreVectorHash)
3713 sortByAnnotScore.removeAll();
3714 // almost certainly a quicker way to do this - but we keep it simple
3715 Hashtable scoreSorts = new Hashtable();
3716 AlignmentAnnotation aann[];
3717 for (SequenceI sqa : viewport.getAlignment().getSequences())
3719 aann = sqa.getAnnotation();
3720 for (int i = 0; aann != null && i < aann.length; i++)
3722 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3724 scoreSorts.put(aann[i].label, aann[i].label);
3728 Enumeration labels = scoreSorts.keys();
3729 while (labels.hasMoreElements())
3731 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3732 (String) labels.nextElement());
3734 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3737 _annotationScoreVectorHash = viewport.getAlignment()
3738 .getAlignmentAnnotation().hashCode();
3743 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3744 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3745 * call. Listeners are added to remove the menu item when the treePanel is
3746 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3750 public void buildTreeSortMenu()
3752 sortByTreeMenu.removeAll();
3754 List<Component> comps = PaintRefresher.components
3755 .get(viewport.getSequenceSetId());
3756 List<TreePanel> treePanels = new ArrayList<>();
3757 for (Component comp : comps)
3759 if (comp instanceof TreePanel)
3761 treePanels.add((TreePanel) comp);
3765 if (treePanels.size() < 1)
3767 sortByTreeMenu.setVisible(false);
3771 sortByTreeMenu.setVisible(true);
3773 for (final TreePanel tp : treePanels)
3775 final JMenuItem item = new JMenuItem(tp.getTitle());
3776 item.addActionListener(new java.awt.event.ActionListener()
3779 public void actionPerformed(ActionEvent e)
3782 tp.sortByTree_actionPerformed();
3783 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3788 sortByTreeMenu.add(item);
3792 public boolean sortBy(AlignmentOrder alorder, String undoname)
3794 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3795 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3796 if (undoname != null)
3798 addHistoryItem(new OrderCommand(undoname, oldOrder,
3799 viewport.getAlignment()));
3801 alignPanel.paintAlignment(true, false);
3806 * Work out whether the whole set of sequences or just the selected set will
3807 * be submitted for multiple alignment.
3810 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3812 // Now, check we have enough sequences
3813 AlignmentView msa = null;
3815 if ((viewport.getSelectionGroup() != null)
3816 && (viewport.getSelectionGroup().getSize() > 1))
3818 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3819 // some common interface!
3821 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3822 * SequenceI[sz = seqs.getSize(false)];
3824 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3825 * seqs.getSequenceAt(i); }
3827 msa = viewport.getAlignmentView(true);
3829 else if (viewport.getSelectionGroup() != null
3830 && viewport.getSelectionGroup().getSize() == 1)
3832 int option = JvOptionPane.showConfirmDialog(this,
3833 MessageManager.getString("warn.oneseq_msainput_selection"),
3834 MessageManager.getString("label.invalid_selection"),
3835 JvOptionPane.OK_CANCEL_OPTION);
3836 if (option == JvOptionPane.OK_OPTION)
3838 msa = viewport.getAlignmentView(false);
3843 msa = viewport.getAlignmentView(false);
3849 * Decides what is submitted to a secondary structure prediction service: the
3850 * first sequence in the alignment, or in the current selection, or, if the
3851 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3852 * region or the whole alignment. (where the first sequence in the set is the
3853 * one that the prediction will be for).
3855 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3857 AlignmentView seqs = null;
3859 if ((viewport.getSelectionGroup() != null)
3860 && (viewport.getSelectionGroup().getSize() > 0))
3862 seqs = viewport.getAlignmentView(true);
3866 seqs = viewport.getAlignmentView(false);
3868 // limit sequences - JBPNote in future - could spawn multiple prediction
3870 // TODO: viewport.getAlignment().isAligned is a global state - the local
3871 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3872 if (!viewport.getAlignment().isAligned(false))
3874 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3875 // TODO: if seqs.getSequences().length>1 then should really have warned
3889 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3895 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
3901 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
3908 protected void loadTreeBase_actionPerformed(ActionEvent e)
3914 protected void loadTreePfam_actionPerformed(ActionEvent e)
3920 protected void loadTreeFam_actionPerformed(ActionEvent e)
3927 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
3937 public void chooseTreeFile()
3939 // Pick the tree file
3940 JalviewFileChooser chooser = new JalviewFileChooser(
3941 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3942 chooser.setFileView(new JalviewFileView());
3943 chooser.setDialogTitle(
3944 MessageManager.getString("label.select_tree_file")); // modify
3945 chooser.setToolTipText(
3946 MessageManager.getString("label.load_tree_for_sequence_set"));
3947 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
3950 chooser.setFileFilter(treeFormat.getTreeFilter());
3953 int value = chooser.showOpenDialog(null);
3955 if (value == JalviewFileChooser.APPROVE_OPTION)
3957 String filePath = chooser.getSelectedFile().getPath();
3958 Cache.setProperty("LAST_DIRECTORY", filePath);
3961 TreeParser treeParser = new TreeParser(filePath);
3962 treeParser.loadTree(viewport);
3968 * Break up and move to TreeParser?
3970 public void chooseTreeUrl()
3973 JLabel label = new JLabel(
3974 MessageManager.getString("label.tree_url_example"));
3975 // add "example" button
3976 final JComboBox<String> history = new JComboBox<>();
3978 JPanel panel = new JPanel(new GridLayout(2, 1));
3981 history.setPreferredSize(new Dimension(400, 20));
3982 history.setEditable(true);
3983 history.addItem("http://www.");
3985 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
3989 if (historyItems != null)
3991 st = new StringTokenizer(historyItems, "\t");
3993 while (st.hasMoreTokens())
3995 history.addItem(st.nextToken());
3999 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4000 MessageManager.getString("label.load_tree_url"),
4001 JvOptionPane.OK_CANCEL_OPTION);
4003 if (reply == JvOptionPane.OK_OPTION)
4006 String urlString = history.getSelectedItem().toString();
4011 FileFormatI format = null;
4013 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4014 // add actual use for the format identification (jalview .jar files)
4015 treeUrl = new URL(urlString);
4016 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4018 } catch (IOException | RuntimeException e)
4020 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4021 "exception.failed_to_read_data_from_source", new String[]
4023 MessageManager.getString("label.url_not_found"),
4024 JvOptionPane.ERROR_MESSAGE);
4025 e.printStackTrace();
4035 * Disgustingly hardcoded atm.
4037 * @param databaseIndex
4039 public void chooseTreeDb(int databaseIndex)
4041 AptxInit.createInstancesFromDb(databaseIndex, viewport);
4044 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4046 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4049 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4050 int h, int x, int y)
4052 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4056 * Add a treeviewer for the tree extracted from a Newick file object to the
4057 * current alignment view
4064 * Associated alignment input data (or null)
4073 * @return TreePanel handle
4075 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4076 AlignmentView input, int w, int h, int x, int y)
4078 TreePanel tp = null;
4084 if (nf.getTree() != null)
4086 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4092 tp.setLocation(x, y);
4095 Desktop.addInternalFrame(tp, treeTitle, w, h);
4097 } catch (Exception ex)
4099 ex.printStackTrace();
4105 private boolean buildingMenu = false;
4107 public void BuildTreeDbMenu()
4112 * Generates menu items and listener event actions for web service clients
4115 public void BuildWebServiceMenu()
4117 while (buildingMenu)
4121 System.err.println("Waiting for building menu to finish.");
4123 } catch (Exception e)
4127 final AlignFrame me = this;
4128 buildingMenu = true;
4129 new Thread(new Runnable()
4134 final List<JMenuItem> legacyItems = new ArrayList<>();
4137 // System.err.println("Building ws menu again "
4138 // + Thread.currentThread());
4139 // TODO: add support for context dependent disabling of services based
4141 // alignment and current selection
4142 // TODO: add additional serviceHandle parameter to specify abstract
4144 // class independently of AbstractName
4145 // TODO: add in rediscovery GUI function to restart discoverer
4146 // TODO: group services by location as well as function and/or
4148 // object broker mechanism.
4149 final Vector<JMenu> wsmenu = new Vector<>();
4150 final IProgressIndicator af = me;
4153 * do not i18n these strings - they are hard-coded in class
4154 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4155 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4157 final JMenu msawsmenu = new JMenu("Alignment");
4158 final JMenu secstrmenu = new JMenu(
4159 "Secondary Structure Prediction");
4160 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4161 final JMenu analymenu = new JMenu("Analysis");
4162 final JMenu dismenu = new JMenu("Protein Disorder");
4163 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4165 // JAL-940 - only show secondary structure prediction services from
4166 // the legacy server
4167 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4169 Discoverer.services != null && (Discoverer.services.size() > 0))
4171 // TODO: refactor to allow list of AbstractName/Handler bindings to
4173 // stored or retrieved from elsewhere
4174 // No MSAWS used any more:
4175 // Vector msaws = null; // (Vector)
4176 // Discoverer.services.get("MsaWS");
4177 Vector secstrpr = (Vector) Discoverer.services
4179 if (secstrpr != null)
4181 // Add any secondary structure prediction services
4182 for (int i = 0, j = secstrpr.size(); i < j; i++)
4184 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4186 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4187 .getServiceClient(sh);
4188 int p = secstrmenu.getItemCount();
4189 impl.attachWSMenuEntry(secstrmenu, me);
4190 int q = secstrmenu.getItemCount();
4191 for (int litm = p; litm < q; litm++)
4193 legacyItems.add(secstrmenu.getItem(litm));
4199 // Add all submenus in the order they should appear on the web
4201 wsmenu.add(msawsmenu);
4202 wsmenu.add(secstrmenu);
4203 wsmenu.add(dismenu);
4204 wsmenu.add(analymenu);
4205 wsmenu.add(phylogenmenu);
4206 // No search services yet
4207 // wsmenu.add(seqsrchmenu);
4209 javax.swing.SwingUtilities.invokeLater(new Runnable()
4216 webService.removeAll();
4217 // first, add discovered services onto the webservices menu
4218 if (wsmenu.size() > 0)
4220 for (int i = 0, j = wsmenu.size(); i < j; i++)
4222 webService.add(wsmenu.get(i));
4227 webService.add(me.webServiceNoServices);
4229 // TODO: move into separate menu builder class.
4230 boolean new_sspred = false;
4231 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4233 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4234 if (jws2servs != null)
4236 if (jws2servs.hasServices())
4238 jws2servs.attachWSMenuEntry(webService, me);
4239 for (Jws2Instance sv : jws2servs.getServices())
4241 if (sv.description.toLowerCase().contains("jpred"))
4243 for (JMenuItem jmi : legacyItems)
4245 jmi.setVisible(false);
4251 if (jws2servs.isRunning())
4253 JMenuItem tm = new JMenuItem(
4254 "Still discovering JABA Services");
4255 tm.setEnabled(false);
4260 build_urlServiceMenu(me.webService);
4261 build_fetchdbmenu(webService);
4262 for (JMenu item : wsmenu)
4264 if (item.getItemCount() == 0)
4266 item.setEnabled(false);
4270 item.setEnabled(true);
4273 } catch (Exception e)
4276 "Exception during web service menu building process.",
4281 } catch (Exception e)
4284 buildingMenu = false;
4286 }, "BuildWebServiceThread").start();
4291 * construct any groupURL type service menu entries.
4295 private void build_urlServiceMenu(JMenu webService)
4297 // TODO: remove this code when 2.7 is released
4298 // DEBUG - alignmentView
4300 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4301 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4303 * @Override public void actionPerformed(ActionEvent e) {
4304 * jalview.datamodel.AlignmentView
4305 * .testSelectionViews(af.viewport.getAlignment(),
4306 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4308 * }); webService.add(testAlView);
4310 // TODO: refactor to RestClient discoverer and merge menu entries for
4311 // rest-style services with other types of analysis/calculation service
4312 // SHmmr test client - still being implemented.
4313 // DEBUG - alignmentView
4315 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4318 client.attachWSMenuEntry(
4319 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4325 * Searches the alignment sequences for xRefs and builds the Show
4326 * Cross-References menu (formerly called Show Products), with database
4327 * sources for which cross-references are found (protein sources for a
4328 * nucleotide alignment and vice versa)
4330 * @return true if Show Cross-references menu should be enabled
4332 public boolean canShowProducts()
4334 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4335 AlignmentI dataset = viewport.getAlignment().getDataset();
4337 showProducts.removeAll();
4338 final boolean dna = viewport.getAlignment().isNucleotide();
4340 if (seqs == null || seqs.length == 0)
4342 // nothing to see here.
4346 boolean showp = false;
4349 List<String> ptypes = new CrossRef(seqs, dataset)
4350 .findXrefSourcesForSequences(dna);
4352 for (final String source : ptypes)
4355 final AlignFrame af = this;
4356 JMenuItem xtype = new JMenuItem(source);
4357 xtype.addActionListener(new ActionListener()
4360 public void actionPerformed(ActionEvent e)
4362 showProductsFor(af.viewport.getSequenceSelection(), dna,
4366 showProducts.add(xtype);
4368 showProducts.setVisible(showp);
4369 showProducts.setEnabled(showp);
4370 } catch (Exception e)
4373 "canShowProducts threw an exception - please report to help@jalview.org",
4381 * Finds and displays cross-references for the selected sequences (protein
4382 * products for nucleotide sequences, dna coding sequences for peptides).
4385 * the sequences to show cross-references for
4387 * true if from a nucleotide alignment (so showing proteins)
4389 * the database to show cross-references for
4391 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4392 final String source)
4394 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this),
4395 "CrossReferencesThread")
4400 * Construct and display a new frame containing the translation of this
4401 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4404 public void showTranslation_actionPerformed(ActionEvent e)
4406 AlignmentI al = null;
4409 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4411 al = dna.translateCdna();
4412 } catch (Exception ex)
4414 jalview.bin.Cache.log.error(
4415 "Exception during translation. Please report this !", ex);
4416 final String msg = MessageManager.getString(
4417 "label.error_when_translating_sequences_submit_bug_report");
4418 final String errorTitle = MessageManager
4419 .getString("label.implementation_error")
4420 + MessageManager.getString("label.translation_failed");
4421 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4422 JvOptionPane.ERROR_MESSAGE);
4425 if (al == null || al.getHeight() == 0)
4427 final String msg = MessageManager.getString(
4428 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4429 final String errorTitle = MessageManager
4430 .getString("label.translation_failed");
4431 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4432 JvOptionPane.WARNING_MESSAGE);
4436 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4437 af.setFileFormat(this.currentFileFormat);
4438 final String newTitle = MessageManager
4439 .formatMessage("label.translation_of_params", new Object[]
4440 { this.getTitle() });
4441 af.setTitle(newTitle);
4442 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4444 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4445 viewport.openSplitFrame(af, new Alignment(seqs));
4449 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4456 * Set the file format
4460 public void setFileFormat(FileFormatI format)
4462 this.currentFileFormat = format;
4466 * Try to load a features file onto the alignment.
4469 * contents or path to retrieve file
4471 * access mode of file (see jalview.io.AlignFile)
4472 * @return true if features file was parsed correctly.
4474 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4476 return avc.parseFeaturesFile(file, sourceType,
4477 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4482 public void refreshFeatureUI(boolean enableIfNecessary)
4484 // note - currently this is only still here rather than in the controller
4485 // because of the featureSettings hard reference that is yet to be
4487 if (enableIfNecessary)
4489 viewport.setShowSequenceFeatures(true);
4490 showSeqFeatures.setSelected(true);
4496 public void dragEnter(DropTargetDragEvent evt)
4501 public void dragExit(DropTargetEvent evt)
4506 public void dragOver(DropTargetDragEvent evt)
4511 public void dropActionChanged(DropTargetDragEvent evt)
4516 public void drop(DropTargetDropEvent evt)
4518 // JAL-1552 - acceptDrop required before getTransferable call for
4519 // Java's Transferable for native dnd
4520 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4521 Transferable t = evt.getTransferable();
4522 final AlignFrame thisaf = this;
4523 final List<String> files = new ArrayList<>();
4524 List<DataSourceType> protocols = new ArrayList<>();
4528 Desktop.transferFromDropTarget(files, protocols, evt, t);
4529 } catch (Exception e)
4531 e.printStackTrace();
4535 new Thread(new Runnable()
4542 // check to see if any of these files have names matching sequences
4545 SequenceIdMatcher idm = new SequenceIdMatcher(
4546 viewport.getAlignment().getSequencesArray());
4548 * Object[] { String,SequenceI}
4550 ArrayList<Object[]> filesmatched = new ArrayList<>();
4551 ArrayList<String> filesnotmatched = new ArrayList<>();
4552 for (int i = 0; i < files.size(); i++)
4554 String file = files.get(i).toString();
4556 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4557 if (protocol == DataSourceType.FILE)
4559 File fl = new File(file);
4560 pdbfn = fl.getName();
4562 else if (protocol == DataSourceType.URL)
4564 URL url = new URL(file);
4565 pdbfn = url.getFile();
4567 if (pdbfn.length() > 0)
4569 // attempt to find a match in the alignment
4570 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4571 int l = 0, c = pdbfn.indexOf(".");
4572 while (mtch == null && c != -1)
4577 } while ((c = pdbfn.indexOf(".", l)) > l);
4580 pdbfn = pdbfn.substring(0, l);
4582 mtch = idm.findAllIdMatches(pdbfn);
4586 FileFormatI type = null;
4589 type = new IdentifyFile().identify(file, protocol);
4590 } catch (Exception ex)
4594 if (type != null && type.isStructureFile())
4596 filesmatched.add(new Object[] { file, protocol, mtch });
4600 // File wasn't named like one of the sequences or wasn't a PDB
4602 filesnotmatched.add(file);
4606 if (filesmatched.size() > 0)
4608 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4609 || JvOptionPane.showConfirmDialog(thisaf,
4610 MessageManager.formatMessage(
4611 "label.automatically_associate_structure_files_with_sequences_same_name",
4613 { Integer.valueOf(filesmatched.size())
4615 MessageManager.getString(
4616 "label.automatically_associate_structure_files_by_name"),
4617 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4620 for (Object[] fm : filesmatched)
4622 // try and associate
4623 // TODO: may want to set a standard ID naming formalism for
4624 // associating PDB files which have no IDs.
4625 for (SequenceI toassoc : (SequenceI[]) fm[2])
4627 PDBEntry pe = new AssociatePdbFileWithSeq()
4628 .associatePdbWithSeq((String) fm[0],
4629 (DataSourceType) fm[1], toassoc, false,
4633 System.err.println("Associated file : "
4634 + ((String) fm[0]) + " with "
4635 + toassoc.getDisplayId(true));
4639 // TODO: do we need to update overview ? only if features are
4641 alignPanel.paintAlignment(true, false);
4645 if (filesnotmatched.size() > 0)
4647 if (assocfiles > 0 && (Cache.getDefault(
4648 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4649 || JvOptionPane.showConfirmDialog(thisaf,
4650 "<html>" + MessageManager.formatMessage(
4651 "label.ignore_unmatched_dropped_files_info",
4654 filesnotmatched.size())
4657 MessageManager.getString(
4658 "label.ignore_unmatched_dropped_files"),
4659 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4663 for (String fn : filesnotmatched)
4665 loadJalviewDataFile(fn, null, null, null);
4669 } catch (Exception ex)
4671 ex.printStackTrace();
4674 }, "DropFileThread").start();
4679 * Attempt to load a "dropped" file or URL string, by testing in turn for
4681 * <li>an Annotation file</li>
4682 * <li>a JNet file</li>
4683 * <li>a features file</li>
4684 * <li>else try to interpret as an alignment file</li>
4688 * either a filename or a URL string.
4690 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4691 FileFormatI format, SequenceI assocSeq)
4695 if (sourceType == null)
4697 sourceType = FormatAdapter.checkProtocol(file);
4699 // if the file isn't identified, or not positively identified as some
4700 // other filetype (PFAM is default unidentified alignment file type) then
4701 // try to parse as annotation.
4702 boolean isAnnotation = (format == null
4703 || FileFormat.Pfam.equals(format))
4704 ? new AnnotationFile().annotateAlignmentView(viewport,
4710 // first see if its a T-COFFEE score file
4711 TCoffeeScoreFile tcf = null;
4714 tcf = new TCoffeeScoreFile(file, sourceType);
4717 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4721 new TCoffeeColourScheme(viewport.getAlignment()));
4722 isAnnotation = true;
4723 statusBar.setText(MessageManager.getString(
4724 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4728 // some problem - if no warning its probable that the ID matching
4729 // process didn't work
4730 JvOptionPane.showMessageDialog(Desktop.desktop,
4731 tcf.getWarningMessage() == null
4732 ? MessageManager.getString(
4733 "label.check_file_matches_sequence_ids_alignment")
4734 : tcf.getWarningMessage(),
4735 MessageManager.getString(
4736 "label.problem_reading_tcoffee_score_file"),
4737 JvOptionPane.WARNING_MESSAGE);
4744 } catch (Exception x)
4747 "Exception when processing data source as T-COFFEE score file",
4753 // try to see if its a JNet 'concise' style annotation file *before*
4755 // try to parse it as a features file
4758 format = new IdentifyFile().identify(file, sourceType);
4760 if (FileFormat.ScoreMatrix == format)
4762 ScoreMatrixFile sm = new ScoreMatrixFile(
4763 new FileParse(file, sourceType));
4765 // todo: i18n this message
4766 statusBar.setText(MessageManager.formatMessage(
4767 "label.successfully_loaded_matrix",
4768 sm.getMatrixName()));
4770 else if (FileFormat.Jnet.equals(format))
4772 JPredFile predictions = new JPredFile(file, sourceType);
4773 new JnetAnnotationMaker();
4774 JnetAnnotationMaker.add_annotation(predictions,
4775 viewport.getAlignment(), 0, false);
4776 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4777 viewport.getAlignment().setSeqrep(repseq);
4778 HiddenColumns cs = new HiddenColumns();
4779 cs.hideInsertionsFor(repseq);
4780 viewport.getAlignment().setHiddenColumns(cs);
4781 isAnnotation = true;
4783 // else if (IdentifyFile.FeaturesFile.equals(format))
4784 else if (FileFormat.Features.equals(format))
4786 if (parseFeaturesFile(file, sourceType))
4788 alignPanel.paintAlignment(true, true);
4793 new FileLoader().LoadFile(viewport, file, sourceType, format);
4800 alignPanel.adjustAnnotationHeight();
4801 viewport.updateSequenceIdColours();
4802 buildSortByAnnotationScoresMenu();
4803 alignPanel.paintAlignment(true, true);
4805 } catch (Exception ex)
4807 ex.printStackTrace();
4808 } catch (OutOfMemoryError oom)
4813 } catch (Exception x)
4818 + (sourceType != null
4819 ? (sourceType == DataSourceType.PASTE
4821 : "using " + sourceType + " from "
4825 ? "(parsing as '" + format + "' file)"
4827 oom, Desktop.desktop);
4832 * Method invoked by the ChangeListener on the tabbed pane, in other words
4833 * when a different tabbed pane is selected by the user or programmatically.
4836 public void tabSelectionChanged(int index)
4840 alignPanel = alignPanels.get(index);
4841 viewport = alignPanel.av;
4842 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4843 setMenusFromViewport(viewport);
4847 * 'focus' any colour slider that is open to the selected viewport
4849 if (viewport.getConservationSelected())
4851 SliderPanel.setConservationSlider(alignPanel,
4852 viewport.getResidueShading(), alignPanel.getViewName());
4856 SliderPanel.hideConservationSlider();
4858 if (viewport.getAbovePIDThreshold())
4860 SliderPanel.setPIDSliderSource(alignPanel,
4861 viewport.getResidueShading(), alignPanel.getViewName());
4865 SliderPanel.hidePIDSlider();
4869 * If there is a frame linked to this one in a SplitPane, switch it to the
4870 * same view tab index. No infinite recursion of calls should happen, since
4871 * tabSelectionChanged() should not get invoked on setting the selected
4872 * index to an unchanged value. Guard against setting an invalid index
4873 * before the new view peer tab has been created.
4875 final AlignViewportI peer = viewport.getCodingComplement();
4878 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4879 .getAlignPanel().alignFrame;
4880 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4882 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4888 * On right mouse click on view tab, prompt for and set new view name.
4891 public void tabbedPane_mousePressed(MouseEvent e)
4893 if (e.isPopupTrigger())
4895 String msg = MessageManager.getString("label.enter_view_name");
4896 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4897 JvOptionPane.QUESTION_MESSAGE);
4901 viewport.viewName = reply;
4902 // TODO warn if reply is in getExistingViewNames()?
4903 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4908 public AlignViewport getCurrentView()
4914 * Open the dialog for regex description parsing.
4917 protected void extractScores_actionPerformed(ActionEvent e)
4919 ParseProperties pp = new jalview.analysis.ParseProperties(
4920 viewport.getAlignment());
4921 // TODO: verify regex and introduce GUI dialog for version 2.5
4922 // if (pp.getScoresFromDescription("col", "score column ",
4923 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4925 if (pp.getScoresFromDescription("description column",
4926 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4928 buildSortByAnnotationScoresMenu();
4936 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4940 protected void showDbRefs_actionPerformed(ActionEvent e)
4942 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4948 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4952 protected void showNpFeats_actionPerformed(ActionEvent e)
4954 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4958 * find the viewport amongst the tabs in this alignment frame and close that
4963 public boolean closeView(AlignViewportI av)
4967 this.closeMenuItem_actionPerformed(false);
4970 Component[] comp = tabbedPane.getComponents();
4971 for (int i = 0; comp != null && i < comp.length; i++)
4973 if (comp[i] instanceof AlignmentPanel)
4975 if (((AlignmentPanel) comp[i]).av == av)
4978 closeView((AlignmentPanel) comp[i]);
4986 protected void build_fetchdbmenu(JMenu webService)
4988 // Temporary hack - DBRef Fetcher always top level ws entry.
4989 // TODO We probably want to store a sequence database checklist in
4990 // preferences and have checkboxes.. rather than individual sources selected
4992 final JMenu rfetch = new JMenu(
4993 MessageManager.getString("action.fetch_db_references"));
4994 rfetch.setToolTipText(MessageManager.getString(
4995 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4996 webService.add(rfetch);
4998 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4999 MessageManager.getString("option.trim_retrieved_seqs"));
5000 trimrs.setToolTipText(
5001 MessageManager.getString("label.trim_retrieved_sequences"));
5002 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5003 trimrs.addActionListener(new ActionListener()
5006 public void actionPerformed(ActionEvent e)
5008 trimrs.setSelected(trimrs.isSelected());
5009 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5010 Boolean.valueOf(trimrs.isSelected()).toString());
5014 JMenuItem fetchr = new JMenuItem(
5015 MessageManager.getString("label.standard_databases"));
5016 fetchr.setToolTipText(
5017 MessageManager.getString("label.fetch_embl_uniprot"));
5018 fetchr.addActionListener(new ActionListener()
5022 public void actionPerformed(ActionEvent e)
5024 new Thread(new Runnable()
5029 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5030 .getAlignment().isNucleotide();
5031 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5032 alignPanel.av.getSequenceSelection(),
5033 alignPanel.alignFrame, null,
5034 alignPanel.alignFrame.featureSettings, isNucleotide);
5035 dbRefFetcher.addListener(new FetchFinishedListenerI()
5038 public void finished()
5040 AlignFrame.this.setMenusForViewport();
5043 dbRefFetcher.fetchDBRefs(false);
5045 }, "BuildFetchDBMenuThread").start();
5051 final AlignFrame me = this;
5052 new Thread(new Runnable()
5057 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5058 .getSequenceFetcherSingleton(me);
5059 javax.swing.SwingUtilities.invokeLater(new Runnable()
5064 String[] dbclasses = sf.getOrderedSupportedSources();
5065 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5066 // jalview.util.QuickSort.sort(otherdb, otherdb);
5067 List<DbSourceProxy> otherdb;
5068 JMenu dfetch = new JMenu();
5069 JMenu ifetch = new JMenu();
5070 JMenuItem fetchr = null;
5071 int comp = 0, icomp = 0, mcomp = 15;
5072 String mname = null;
5074 for (String dbclass : dbclasses)
5076 otherdb = sf.getSourceProxy(dbclass);
5077 // add a single entry for this class, or submenu allowing 'fetch
5079 if (otherdb == null || otherdb.size() < 1)
5083 // List<DbSourceProxy> dbs=otherdb;
5084 // otherdb=new ArrayList<DbSourceProxy>();
5085 // for (DbSourceProxy db:dbs)
5087 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5091 mname = "From " + dbclass;
5093 if (otherdb.size() == 1)
5095 final DbSourceProxy[] dassource = otherdb
5096 .toArray(new DbSourceProxy[0]);
5097 DbSourceProxy src = otherdb.get(0);
5098 fetchr = new JMenuItem(src.getDbSource());
5099 fetchr.addActionListener(new ActionListener()
5103 public void actionPerformed(ActionEvent e)
5105 new Thread(new Runnable()
5111 boolean isNucleotide = alignPanel.alignFrame
5112 .getViewport().getAlignment()
5114 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5115 alignPanel.av.getSequenceSelection(),
5116 alignPanel.alignFrame, dassource,
5117 alignPanel.alignFrame.featureSettings,
5120 .addListener(new FetchFinishedListenerI()
5123 public void finished()
5125 AlignFrame.this.setMenusForViewport();
5128 dbRefFetcher.fetchDBRefs(false);
5134 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5135 MessageManager.formatMessage(
5136 "label.fetch_retrieve_from", new Object[]
5137 { src.getDbName() })));
5143 final DbSourceProxy[] dassource = otherdb
5144 .toArray(new DbSourceProxy[0]);
5146 DbSourceProxy src = otherdb.get(0);
5147 fetchr = new JMenuItem(MessageManager
5148 .formatMessage("label.fetch_all_param", new Object[]
5149 { src.getDbSource() }));
5150 fetchr.addActionListener(new ActionListener()
5153 public void actionPerformed(ActionEvent e)
5155 new Thread(new Runnable()
5161 boolean isNucleotide = alignPanel.alignFrame
5162 .getViewport().getAlignment()
5164 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5165 alignPanel.av.getSequenceSelection(),
5166 alignPanel.alignFrame, dassource,
5167 alignPanel.alignFrame.featureSettings,
5170 .addListener(new FetchFinishedListenerI()
5173 public void finished()
5175 AlignFrame.this.setMenusForViewport();
5178 dbRefFetcher.fetchDBRefs(false);
5184 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5185 MessageManager.formatMessage(
5186 "label.fetch_retrieve_from_all_sources",
5188 { Integer.valueOf(otherdb.size())
5190 src.getDbSource(), src.getDbName() })));
5193 // and then build the rest of the individual menus
5194 ifetch = new JMenu(MessageManager.formatMessage(
5195 "label.source_from_db_source", new Object[]
5196 { src.getDbSource() }));
5198 String imname = null;
5200 for (DbSourceProxy sproxy : otherdb)
5202 String dbname = sproxy.getDbName();
5203 String sname = dbname.length() > 5
5204 ? dbname.substring(0, 5) + "..."
5206 String msname = dbname.length() > 10
5207 ? dbname.substring(0, 10) + "..."
5211 imname = MessageManager
5212 .formatMessage("label.from_msname", new Object[]
5215 fetchr = new JMenuItem(msname);
5216 final DbSourceProxy[] dassrc = { sproxy };
5217 fetchr.addActionListener(new ActionListener()
5221 public void actionPerformed(ActionEvent e)
5223 new Thread(new Runnable()
5229 boolean isNucleotide = alignPanel.alignFrame
5230 .getViewport().getAlignment()
5232 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5233 alignPanel.av.getSequenceSelection(),
5234 alignPanel.alignFrame, dassrc,
5235 alignPanel.alignFrame.featureSettings,
5238 .addListener(new FetchFinishedListenerI()
5241 public void finished()
5243 AlignFrame.this.setMenusForViewport();
5246 dbRefFetcher.fetchDBRefs(false);
5252 fetchr.setToolTipText(
5253 "<html>" + MessageManager.formatMessage(
5254 "label.fetch_retrieve_from", new Object[]
5258 if (++icomp >= mcomp || i == (otherdb.size()))
5260 ifetch.setText(MessageManager.formatMessage(
5261 "label.source_to_target", imname, sname));
5263 ifetch = new JMenu();
5271 if (comp >= mcomp || dbi >= (dbclasses.length))
5273 dfetch.setText(MessageManager.formatMessage(
5274 "label.source_to_target", mname, dbclass));
5276 dfetch = new JMenu();
5289 * Left justify the whole alignment.
5292 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5294 AlignmentI al = viewport.getAlignment();
5296 viewport.firePropertyChange("alignment", null, al);
5300 * Right justify the whole alignment.
5303 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5305 AlignmentI al = viewport.getAlignment();
5307 viewport.firePropertyChange("alignment", null, al);
5311 public void setShowSeqFeatures(boolean b)
5313 showSeqFeatures.setSelected(b);
5314 viewport.setShowSequenceFeatures(b);
5321 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5322 * awt.event.ActionEvent)
5325 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5327 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5328 alignPanel.paintAlignment(false, false);
5335 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5339 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5341 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5342 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5351 * .event.ActionEvent)
5354 protected void showGroupConservation_actionPerformed(ActionEvent e)
5356 viewport.setShowGroupConservation(showGroupConservation.getState());
5357 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5365 * .event.ActionEvent)
5368 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5370 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5371 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5379 * .event.ActionEvent)
5382 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5384 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5385 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5389 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5391 showSequenceLogo.setState(true);
5392 viewport.setShowSequenceLogo(true);
5393 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5394 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5398 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5400 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5407 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5408 * .event.ActionEvent)
5411 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5413 if (avc.makeGroupsFromSelection())
5415 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5416 alignPanel.updateAnnotation();
5417 alignPanel.paintAlignment(true, true);
5421 public void clearAlignmentSeqRep()
5423 // TODO refactor alignmentseqrep to controller
5424 if (viewport.getAlignment().hasSeqrep())
5426 viewport.getAlignment().setSeqrep(null);
5427 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5428 alignPanel.updateAnnotation();
5429 alignPanel.paintAlignment(true, true);
5434 protected void createGroup_actionPerformed(ActionEvent e)
5436 if (avc.createGroup())
5438 alignPanel.alignmentChanged();
5443 protected void unGroup_actionPerformed(ActionEvent e)
5447 alignPanel.alignmentChanged();
5452 * make the given alignmentPanel the currently selected tab
5454 * @param alignmentPanel
5456 public void setDisplayedView(AlignmentPanel alignmentPanel)
5458 if (!viewport.getSequenceSetId()
5459 .equals(alignmentPanel.av.getSequenceSetId()))
5461 throw new Error(MessageManager.getString(
5462 "error.implementation_error_cannot_show_view_alignment_frame"));
5464 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5465 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5467 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5472 * Action on selection of menu options to Show or Hide annotations.
5475 * @param forSequences
5476 * update sequence-related annotations
5477 * @param forAlignment
5478 * update non-sequence-related annotations
5481 protected void setAnnotationsVisibility(boolean visible,
5482 boolean forSequences, boolean forAlignment)
5484 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5485 .getAlignmentAnnotation();
5490 for (AlignmentAnnotation aa : anns)
5493 * don't display non-positional annotations on an alignment
5495 if (aa.annotations == null)
5499 boolean apply = (aa.sequenceRef == null && forAlignment)
5500 || (aa.sequenceRef != null && forSequences);
5503 aa.visible = visible;
5506 alignPanel.validateAnnotationDimensions(true);
5507 alignPanel.alignmentChanged();
5511 * Store selected annotation sort order for the view and repaint.
5514 protected void sortAnnotations_actionPerformed()
5516 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5518 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5519 alignPanel.paintAlignment(false, false);
5524 * @return alignment panels in this alignment frame
5526 public List<? extends AlignmentViewPanel> getAlignPanels()
5528 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5532 * Open a new alignment window, with the cDNA associated with this (protein)
5533 * alignment, aligned as is the protein.
5535 protected void viewAsCdna_actionPerformed()
5537 // TODO no longer a menu action - refactor as required
5538 final AlignmentI alignment = getViewport().getAlignment();
5539 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5540 if (mappings == null)
5544 List<SequenceI> cdnaSeqs = new ArrayList<>();
5545 for (SequenceI aaSeq : alignment.getSequences())
5547 for (AlignedCodonFrame acf : mappings)
5549 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5553 * There is a cDNA mapping for this protein sequence - add to new
5554 * alignment. It will share the same dataset sequence as other mapped
5555 * cDNA (no new mappings need to be created).
5557 final Sequence newSeq = new Sequence(dnaSeq);
5558 newSeq.setDatasetSequence(dnaSeq);
5559 cdnaSeqs.add(newSeq);
5563 if (cdnaSeqs.size() == 0)
5565 // show a warning dialog no mapped cDNA
5568 AlignmentI cdna = new Alignment(
5569 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5570 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5571 AlignFrame.DEFAULT_HEIGHT);
5572 cdna.alignAs(alignment);
5573 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5575 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5576 AlignFrame.DEFAULT_HEIGHT);
5580 * Set visibility of dna/protein complement view (available when shown in a
5586 protected void showComplement_actionPerformed(boolean show)
5588 SplitContainerI sf = getSplitViewContainer();
5591 sf.setComplementVisible(this, show);
5596 * Generate the reverse (optionally complemented) of the selected sequences,
5597 * and add them to the alignment
5600 protected void showReverse_actionPerformed(boolean complement)
5602 AlignmentI al = null;
5605 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5606 al = dna.reverseCdna(complement);
5607 viewport.addAlignment(al, "");
5608 addHistoryItem(new EditCommand(
5609 MessageManager.getString("label.add_sequences"), Action.PASTE,
5610 al.getSequencesArray(), 0, al.getWidth(),
5611 viewport.getAlignment()));
5612 } catch (Exception ex)
5614 System.err.println(ex.getMessage());
5620 * Try to run a script in the Groovy console, having first ensured that this
5621 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5622 * be targeted at this alignment.
5625 protected void runGroovy_actionPerformed()
5627 Jalview.setCurrentAlignFrame(this);
5628 groovy.ui.Console console = Desktop.getGroovyConsole();
5629 if (console != null)
5633 console.runScript();
5634 } catch (Exception ex)
5636 System.err.println((ex.toString()));
5637 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5638 MessageManager.getString("label.couldnt_run_groovy_script"),
5639 MessageManager.getString("label.groovy_support_failed"),
5640 JvOptionPane.ERROR_MESSAGE);
5645 System.err.println("Can't run Groovy script as console not found");
5650 * Hides columns containing (or not containing) a specified feature, provided
5651 * that would not leave all columns hidden
5653 * @param featureType
5654 * @param columnsContaining
5657 public boolean hideFeatureColumns(String featureType,
5658 boolean columnsContaining)
5660 boolean notForHiding = avc.markColumnsContainingFeatures(
5661 columnsContaining, false, false, featureType);
5664 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5665 false, featureType))
5667 getViewport().hideSelectedColumns();
5675 protected void selectHighlightedColumns_actionPerformed(
5676 ActionEvent actionEvent)
5678 // include key modifier check in case user selects from menu
5679 avc.markHighlightedColumns(
5680 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5681 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5682 | ActionEvent.CTRL_MASK)) != 0);
5686 * Rebuilds the Colour menu, including any user-defined colours which have
5687 * been loaded either on startup or during the session
5689 public void buildColourMenu()
5691 colourMenu.removeAll();
5693 colourMenu.add(applyToAllGroups);
5694 colourMenu.add(textColour);
5695 colourMenu.addSeparator();
5697 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5700 colourMenu.addSeparator();
5701 colourMenu.add(conservationMenuItem);
5702 colourMenu.add(modifyConservation);
5703 colourMenu.add(abovePIDThreshold);
5704 colourMenu.add(modifyPID);
5705 colourMenu.add(annotationColour);
5707 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5708 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5712 * Open a dialog (if not already open) that allows the user to select and
5713 * calculate PCA or Tree analysis
5715 protected void openTreePcaDialog()
5717 if (alignPanel.getCalculationDialog() == null)
5719 new CalculationChooser(AlignFrame.this);
5724 class PrintThread extends Thread
5728 public PrintThread(AlignmentPanel ap)
5733 static PageFormat pf;
5738 PrinterJob printJob = PrinterJob.getPrinterJob();
5742 printJob.setPrintable(ap, pf);
5746 printJob.setPrintable(ap);
5749 if (printJob.printDialog())
5754 } catch (Exception PrintException)
5756 PrintException.printStackTrace();