2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenMarkovModel;
58 import jalview.datamodel.HiddenSequences;
59 import jalview.datamodel.PDBEntry;
60 import jalview.datamodel.SeqCigar;
61 import jalview.datamodel.Sequence;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.gui.ColourMenuHelper.ColourChangeListener;
65 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
66 import jalview.io.AlignmentProperties;
67 import jalview.io.AnnotationFile;
68 import jalview.io.BioJsHTMLOutput;
69 import jalview.io.DataSourceType;
70 import jalview.io.FileFormat;
71 import jalview.io.FileFormatI;
72 import jalview.io.FileFormats;
73 import jalview.io.FileLoader;
74 import jalview.io.FileParse;
75 import jalview.io.FormatAdapter;
76 import jalview.io.HMMFile;
77 import jalview.io.HtmlSvgOutput;
78 import jalview.io.IdentifyFile;
79 import jalview.io.JPredFile;
80 import jalview.io.JalviewFileChooser;
81 import jalview.io.JalviewFileView;
82 import jalview.io.JnetAnnotationMaker;
83 import jalview.io.NewickFile;
84 import jalview.io.ScoreMatrixFile;
85 import jalview.io.TCoffeeScoreFile;
86 import jalview.jbgui.GAlignFrame;
87 import jalview.schemes.ColourSchemeI;
88 import jalview.schemes.ColourSchemes;
89 import jalview.schemes.ResidueColourScheme;
90 import jalview.schemes.TCoffeeColourScheme;
91 import jalview.util.MessageManager;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.viewmodel.ViewportRanges;
94 import jalview.ws.DBRefFetcher;
95 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
96 import jalview.ws.jws1.Discoverer;
97 import jalview.ws.jws2.Jws2Discoverer;
98 import jalview.ws.jws2.jabaws2.Jws2Instance;
99 import jalview.ws.seqfetcher.DbSourceProxy;
101 import java.awt.BorderLayout;
102 import java.awt.Component;
103 import java.awt.Rectangle;
104 import java.awt.Toolkit;
105 import java.awt.datatransfer.Clipboard;
106 import java.awt.datatransfer.DataFlavor;
107 import java.awt.datatransfer.StringSelection;
108 import java.awt.datatransfer.Transferable;
109 import java.awt.dnd.DnDConstants;
110 import java.awt.dnd.DropTargetDragEvent;
111 import java.awt.dnd.DropTargetDropEvent;
112 import java.awt.dnd.DropTargetEvent;
113 import java.awt.dnd.DropTargetListener;
114 import java.awt.event.ActionEvent;
115 import java.awt.event.ActionListener;
116 import java.awt.event.FocusAdapter;
117 import java.awt.event.FocusEvent;
118 import java.awt.event.ItemEvent;
119 import java.awt.event.ItemListener;
120 import java.awt.event.KeyAdapter;
121 import java.awt.event.KeyEvent;
122 import java.awt.event.MouseEvent;
123 import java.awt.print.PageFormat;
124 import java.awt.print.PrinterJob;
125 import java.beans.PropertyChangeEvent;
127 import java.io.FileWriter;
128 import java.io.PrintWriter;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Deque;
133 import java.util.Enumeration;
134 import java.util.HashMap;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Map;
138 import java.util.Vector;
140 import javax.swing.JCheckBoxMenuItem;
141 import javax.swing.JEditorPane;
142 import javax.swing.JInternalFrame;
143 import javax.swing.JLayeredPane;
144 import javax.swing.JMenu;
145 import javax.swing.JMenuItem;
146 import javax.swing.JScrollPane;
147 import javax.swing.SwingUtilities;
153 * @version $Revision$
155 public class AlignFrame extends GAlignFrame implements DropTargetListener,
156 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
159 Map<String, Float> distribution = new HashMap<>(); // temporary
161 public static final int DEFAULT_WIDTH = 700;
163 public static final int DEFAULT_HEIGHT = 500;
166 * The currently displayed panel (selected tabbed view if more than one)
168 public AlignmentPanel alignPanel;
170 AlignViewport viewport;
172 ViewportRanges vpRanges;
174 public AlignViewControllerI avc;
176 List<AlignmentPanel> alignPanels = new ArrayList<>();
179 * Last format used to load or save alignments in this window
181 FileFormatI currentFileFormat = null;
184 * Current filename for this alignment
186 String fileName = null;
190 * Creates a new AlignFrame object with specific width and height.
196 public AlignFrame(AlignmentI al, int width, int height)
198 this(al, null, width, height);
202 * Creates a new AlignFrame object with specific width, height and
208 * @param sequenceSetId
210 public AlignFrame(AlignmentI al, int width, int height,
211 String sequenceSetId)
213 this(al, null, width, height, sequenceSetId);
217 * Creates a new AlignFrame object with specific width, height and
223 * @param sequenceSetId
226 public AlignFrame(AlignmentI al, int width, int height,
227 String sequenceSetId, String viewId)
229 this(al, null, width, height, sequenceSetId, viewId);
233 * new alignment window with hidden columns
237 * @param hiddenColumns
238 * ColumnSelection or null
240 * Width of alignment frame
244 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
245 int width, int height)
247 this(al, hiddenColumns, width, height, null);
251 * Create alignment frame for al with hiddenColumns, a specific width and
252 * height, and specific sequenceId
255 * @param hiddenColumns
258 * @param sequenceSetId
261 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
262 int width, int height, String sequenceSetId)
264 this(al, hiddenColumns, width, height, sequenceSetId, null);
268 * Create alignment frame for al with hiddenColumns, a specific width and
269 * height, and specific sequenceId
272 * @param hiddenColumns
275 * @param sequenceSetId
280 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns,
281 int width, int height, String sequenceSetId, String viewId)
283 setSize(width, height);
285 if (al.getDataset() == null)
290 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
292 alignPanel = new AlignmentPanel(this, viewport);
294 addAlignmentPanel(alignPanel, true);
298 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
299 HiddenColumns hiddenColumns, int width, int height)
301 setSize(width, height);
303 if (al.getDataset() == null)
308 viewport = new AlignViewport(al, hiddenColumns);
310 if (hiddenSeqs != null && hiddenSeqs.length > 0)
312 viewport.hideSequence(hiddenSeqs);
314 alignPanel = new AlignmentPanel(this, viewport);
315 addAlignmentPanel(alignPanel, true);
320 * Make a new AlignFrame from existing alignmentPanels
327 public AlignFrame(AlignmentPanel ap)
331 addAlignmentPanel(ap, false);
336 * initalise the alignframe from the underlying viewport data and the
341 if (!Jalview.isHeadlessMode())
343 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
346 vpRanges = viewport.getRanges();
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 && evt.getKeyCode() <= KeyEvent.VK_9) || (evt
521 .getKeyCode() >= KeyEvent.VK_NUMPAD0 && evt
522 .getKeyCode() <= KeyEvent.VK_NUMPAD9))
523 && Character.isDigit(evt.getKeyChar()))
525 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
528 switch (evt.getKeyCode())
531 case 27: // escape key
532 deselectAllSequenceMenuItem_actionPerformed(null);
536 case KeyEvent.VK_DOWN:
537 if (evt.isAltDown() || !viewport.cursorMode)
539 moveSelectedSequences(false);
541 if (viewport.cursorMode)
543 alignPanel.getSeqPanel().moveCursor(0, 1);
548 if (evt.isAltDown() || !viewport.cursorMode)
550 moveSelectedSequences(true);
552 if (viewport.cursorMode)
554 alignPanel.getSeqPanel().moveCursor(0, -1);
559 case KeyEvent.VK_LEFT:
560 if (evt.isAltDown() || !viewport.cursorMode)
562 slideSequences(false, alignPanel.getSeqPanel().getKeyboardNo1());
566 alignPanel.getSeqPanel().moveCursor(-1, 0);
571 case KeyEvent.VK_RIGHT:
572 if (evt.isAltDown() || !viewport.cursorMode)
574 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
578 alignPanel.getSeqPanel().moveCursor(1, 0);
582 case KeyEvent.VK_SPACE:
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().insertGapAtCursor(
586 evt.isControlDown() || evt.isShiftDown()
591 // case KeyEvent.VK_A:
592 // if (viewport.cursorMode)
594 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
595 // //System.out.println("A");
599 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
600 * System.out.println("closing bracket"); } break;
602 case KeyEvent.VK_DELETE:
603 case KeyEvent.VK_BACK_SPACE:
604 if (!viewport.cursorMode)
606 cut_actionPerformed(null);
610 alignPanel.getSeqPanel().deleteGapAtCursor(
611 evt.isControlDown() || evt.isShiftDown()
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.formatMessage(
660 "label.keyboard_editing_mode",
661 new String[] { (viewport.cursorMode ? "on" : "off") }));
662 if (viewport.cursorMode)
664 alignPanel.getSeqPanel().seqCanvas.cursorX = vpRanges
666 alignPanel.getSeqPanel().seqCanvas.cursorY = vpRanges
669 alignPanel.getSeqPanel().seqCanvas.repaint();
675 Help.showHelpWindow();
676 } catch (Exception ex)
678 ex.printStackTrace();
683 boolean toggleSeqs = !evt.isControlDown();
684 boolean toggleCols = !evt.isShiftDown();
685 toggleHiddenRegions(toggleSeqs, toggleCols);
690 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
691 boolean modifyExisting = true; // always modify, don't clear
692 // evt.isShiftDown();
693 boolean invertHighlighted = evt.isAltDown();
694 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
698 case KeyEvent.VK_PAGE_UP:
699 if (viewport.getWrapAlignment())
701 vpRanges.scrollUp(true);
708 case KeyEvent.VK_PAGE_DOWN:
709 if (viewport.getWrapAlignment())
711 vpRanges.scrollUp(false);
722 public void keyReleased(KeyEvent evt)
724 switch (evt.getKeyCode())
726 case KeyEvent.VK_LEFT:
727 if (evt.isAltDown() || !viewport.cursorMode)
729 viewport.firePropertyChange("alignment", null, viewport
730 .getAlignment().getSequences());
734 case KeyEvent.VK_RIGHT:
735 if (evt.isAltDown() || !viewport.cursorMode)
737 viewport.firePropertyChange("alignment", null, viewport
738 .getAlignment().getSequences());
746 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
748 ap.alignFrame = this;
749 avc = new jalview.controller.AlignViewController(this, viewport,
754 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
756 int aSize = alignPanels.size();
758 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
760 if (aSize == 1 && ap.av.viewName == null)
762 this.getContentPane().add(ap, BorderLayout.CENTER);
768 setInitialTabVisible();
771 expandViews.setEnabled(true);
772 gatherViews.setEnabled(true);
773 tabbedPane.addTab(ap.av.viewName, ap);
775 ap.setVisible(false);
780 if (ap.av.isPadGaps())
782 ap.av.getAlignment().padGaps();
784 ap.av.updateConservation(ap);
785 ap.av.updateConsensus(ap);
786 ap.av.updateStrucConsensus(ap);
790 public void setInitialTabVisible()
792 expandViews.setEnabled(true);
793 gatherViews.setEnabled(true);
794 tabbedPane.setVisible(true);
795 AlignmentPanel first = alignPanels.get(0);
796 tabbedPane.addTab(first.av.viewName, first);
797 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
800 public AlignViewport getViewport()
805 /* Set up intrinsic listeners for dynamically generated GUI bits. */
806 private void addServiceListeners()
808 final java.beans.PropertyChangeListener thisListener;
809 Desktop.instance.addJalviewPropertyChangeListener("services",
810 thisListener = new java.beans.PropertyChangeListener()
813 public void propertyChange(PropertyChangeEvent evt)
815 // // System.out.println("Discoverer property change.");
816 // if (evt.getPropertyName().equals("services"))
818 SwingUtilities.invokeLater(new Runnable()
825 .println("Rebuild WS Menu for service change");
826 BuildWebServiceMenu();
833 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
836 public void internalFrameClosed(
837 javax.swing.event.InternalFrameEvent evt)
839 // System.out.println("deregistering discoverer listener");
840 Desktop.instance.removeJalviewPropertyChangeListener("services",
842 closeMenuItem_actionPerformed(true);
845 // Finally, build the menu once to get current service state
846 new Thread(new Runnable()
851 BuildWebServiceMenu();
857 * Configure menu items that vary according to whether the alignment is
858 * nucleotide or protein
860 public void setGUINucleotide()
862 AlignmentI al = getViewport().getAlignment();
863 boolean nucleotide = al.isNucleotide();
865 showTranslation.setVisible(nucleotide);
866 showReverse.setVisible(nucleotide);
867 showReverseComplement.setVisible(nucleotide);
868 conservationMenuItem.setEnabled(!nucleotide);
869 modifyConservation.setEnabled(!nucleotide
870 && conservationMenuItem.isSelected());
871 showGroupConservation.setEnabled(!nucleotide);
873 showComplementMenuItem.setText(nucleotide ? MessageManager
874 .getString("label.protein") : MessageManager
875 .getString("label.nucleotide"));
879 * set up menus for the current viewport. This may be called after any
880 * operation that affects the data in the current view (selection changed,
881 * etc) to update the menus to reflect the new state.
884 public void setMenusForViewport()
886 setMenusFromViewport(viewport);
890 * Need to call this method when tabs are selected for multiple views, or when
891 * loading from Jalview2XML.java
896 void setMenusFromViewport(AlignViewport av)
898 padGapsMenuitem.setSelected(av.isPadGaps());
899 colourTextMenuItem.setSelected(av.isShowColourText());
900 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
901 modifyPID.setEnabled(abovePIDThreshold.isSelected());
902 conservationMenuItem.setSelected(av.getConservationSelected());
903 modifyConservation.setEnabled(conservationMenuItem.isSelected());
904 seqLimits.setSelected(av.getShowJVSuffix());
905 idRightAlign.setSelected(av.isRightAlignIds());
906 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
907 renderGapsMenuItem.setSelected(av.isRenderGaps());
908 wrapMenuItem.setSelected(av.getWrapAlignment());
909 scaleAbove.setVisible(av.getWrapAlignment());
910 scaleLeft.setVisible(av.getWrapAlignment());
911 scaleRight.setVisible(av.getWrapAlignment());
912 annotationPanelMenuItem.setState(av.isShowAnnotation());
914 * Show/hide annotations only enabled if annotation panel is shown
916 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
917 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
918 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
919 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
920 viewBoxesMenuItem.setSelected(av.getShowBoxes());
921 viewTextMenuItem.setSelected(av.getShowText());
922 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
923 showGroupConsensus.setSelected(av.isShowGroupConsensus());
924 showGroupConservation.setSelected(av.isShowGroupConservation());
925 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
926 showSequenceLogo.setSelected(av.isShowSequenceLogo());
927 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
928 showInformationHistogram.setSelected(av.isShowInformationHistogram());
929 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
930 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
932 ColourMenuHelper.setColourSelected(colourMenu,
933 av.getGlobalColourScheme());
935 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
936 hiddenMarkers.setState(av.getShowHiddenMarkers());
937 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
938 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
939 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
940 autoCalculate.setSelected(av.autoCalculateConsensus);
941 sortByTree.setSelected(av.sortByTree);
942 listenToViewSelections.setSelected(av.followSelection);
944 showProducts.setEnabled(canShowProducts());
945 setGroovyEnabled(Desktop.getGroovyConsole() != null);
951 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
955 public void setGroovyEnabled(boolean b)
957 runGroovy.setEnabled(b);
960 private IProgressIndicator progressBar;
965 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
968 public void setProgressBar(String message, long id)
970 progressBar.setProgressBar(message, id);
974 public void registerHandler(final long id,
975 final IProgressIndicatorHandler handler)
977 progressBar.registerHandler(id, handler);
982 * @return true if any progress bars are still active
985 public boolean operationInProgress()
987 return progressBar.operationInProgress();
991 public void setStatus(String text)
993 statusBar.setText(text);
997 * Added so Castor Mapping file can obtain Jalview Version
999 public String getVersion()
1001 return jalview.bin.Cache.getProperty("VERSION");
1004 public FeatureRenderer getFeatureRenderer()
1006 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1010 public void fetchSequence_actionPerformed(ActionEvent e)
1012 new jalview.gui.SequenceFetcher(this);
1016 public void addFromFile_actionPerformed(ActionEvent e)
1018 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1022 public void reload_actionPerformed(ActionEvent e)
1024 if (fileName != null)
1026 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1027 // originating file's format
1028 // TODO: work out how to recover feature settings for correct view(s) when
1029 // file is reloaded.
1030 if (FileFormat.Jalview.equals(currentFileFormat))
1032 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1033 for (int i = 0; i < frames.length; i++)
1035 if (frames[i] instanceof AlignFrame && frames[i] != this
1036 && ((AlignFrame) frames[i]).fileName != null
1037 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1041 frames[i].setSelected(true);
1042 Desktop.instance.closeAssociatedWindows();
1043 } catch (java.beans.PropertyVetoException ex)
1049 Desktop.instance.closeAssociatedWindows();
1051 FileLoader loader = new FileLoader();
1052 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1053 : DataSourceType.FILE;
1054 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1058 Rectangle bounds = this.getBounds();
1060 FileLoader loader = new FileLoader();
1061 DataSourceType protocol = fileName.startsWith("http:") ? DataSourceType.URL
1062 : DataSourceType.FILE;
1063 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1064 protocol, currentFileFormat);
1066 newframe.setBounds(bounds);
1067 if (featureSettings != null && featureSettings.isShowing())
1069 final Rectangle fspos = featureSettings.frame.getBounds();
1070 // TODO: need a 'show feature settings' function that takes bounds -
1071 // need to refactor Desktop.addFrame
1072 newframe.featureSettings_actionPerformed(null);
1073 final FeatureSettings nfs = newframe.featureSettings;
1074 SwingUtilities.invokeLater(new Runnable()
1079 nfs.frame.setBounds(fspos);
1082 this.featureSettings.close();
1083 this.featureSettings = null;
1085 this.closeMenuItem_actionPerformed(true);
1091 public void addFromText_actionPerformed(ActionEvent e)
1093 Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport
1098 public void addFromURL_actionPerformed(ActionEvent e)
1100 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1104 public void save_actionPerformed(ActionEvent e)
1106 if (fileName == null || (currentFileFormat == null)
1107 || fileName.startsWith("http"))
1109 saveAs_actionPerformed(null);
1113 saveAlignment(fileName, currentFileFormat);
1124 public void saveAs_actionPerformed(ActionEvent e)
1126 String format = currentFileFormat == null ? null : currentFileFormat
1128 JalviewFileChooser chooser = JalviewFileChooser.forWrite(
1129 Cache.getProperty("LAST_DIRECTORY"), format);
1131 chooser.setFileView(new JalviewFileView());
1132 chooser.setDialogTitle(MessageManager
1133 .getString("label.save_alignment_to_file"));
1134 chooser.setToolTipText(MessageManager.getString("action.save"));
1136 int value = chooser.showSaveDialog(this);
1138 if (value == JalviewFileChooser.APPROVE_OPTION)
1140 currentFileFormat = chooser.getSelectedFormat();
1141 while (currentFileFormat == null)
1144 .showInternalMessageDialog(
1147 .getString("label.select_file_format_before_saving"),
1149 .getString("label.file_format_not_specified"),
1150 JvOptionPane.WARNING_MESSAGE);
1151 currentFileFormat = chooser.getSelectedFormat();
1152 value = chooser.showSaveDialog(this);
1153 if (value != JalviewFileChooser.APPROVE_OPTION)
1159 fileName = chooser.getSelectedFile().getPath();
1161 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1163 Cache.setProperty("LAST_DIRECTORY", fileName);
1164 saveAlignment(fileName, currentFileFormat);
1168 public boolean saveAlignment(String file, FileFormatI format)
1170 boolean success = true;
1172 if (FileFormat.Jalview.equals(format))
1174 String shortName = title;
1176 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1178 shortName = shortName.substring(shortName
1179 .lastIndexOf(java.io.File.separatorChar) + 1);
1182 success = new Jalview2XML().saveAlignment(this, file, shortName);
1184 statusBar.setText(MessageManager.formatMessage(
1185 "label.successfully_saved_to_file_in_format", new Object[] {
1186 fileName, format }));
1191 AlignmentExportData exportData = getAlignmentForExport(format,
1193 if (exportData.getSettings().isCancelled())
1197 FormatAdapter f = new FormatAdapter(alignPanel,
1198 exportData.getSettings());
1199 String output = f.formatSequences(
1201 exportData.getAlignment(), // class cast exceptions will
1202 // occur in the distant future
1203 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1204 f.getCacheSuffixDefault(format), viewport.getAlignment()
1205 .getHiddenColumns());
1215 PrintWriter out = new PrintWriter(new FileWriter(file));
1219 this.setTitle(file);
1220 statusBar.setText(MessageManager.formatMessage(
1221 "label.successfully_saved_to_file_in_format",
1222 new Object[] { fileName, format.getName() }));
1223 } catch (Exception ex)
1226 ex.printStackTrace();
1233 JvOptionPane.showInternalMessageDialog(this, MessageManager
1234 .formatMessage("label.couldnt_save_file",
1235 new Object[] { fileName }), MessageManager
1236 .getString("label.error_saving_file"),
1237 JvOptionPane.WARNING_MESSAGE);
1243 private void warningMessage(String warning, String title)
1245 if (new jalview.util.Platform().isHeadless())
1247 System.err.println("Warning: " + title + "\nWarning: " + warning);
1252 JvOptionPane.showInternalMessageDialog(this, warning, title,
1253 JvOptionPane.WARNING_MESSAGE);
1265 protected void outputText_actionPerformed(ActionEvent e)
1267 FileFormatI fileFormat = FileFormats.getInstance().forName(
1268 e.getActionCommand());
1269 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1271 if (exportData.getSettings().isCancelled())
1275 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1276 cap.setForInput(null);
1279 FileFormatI format = fileFormat;
1280 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1281 .formatSequences(format, exportData.getAlignment(),
1282 exportData.getOmitHidden(),
1284 .getStartEndPostions(), viewport
1285 .getAlignment().getHiddenColumns()));
1286 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1287 "label.alignment_output_command",
1288 new Object[] { e.getActionCommand() }), 600, 500);
1289 } catch (OutOfMemoryError oom)
1291 new OOMWarning("Outputting alignment as " + e.getActionCommand(), oom);
1297 public static AlignmentExportData getAlignmentForExport(
1298 FileFormatI format, AlignViewportI viewport,
1299 AlignExportSettingI exportSettings)
1301 AlignmentI alignmentToExport = null;
1302 AlignExportSettingI settings = exportSettings;
1303 String[] omitHidden = null;
1305 HiddenSequences hiddenSeqs = viewport.getAlignment()
1306 .getHiddenSequences();
1308 alignmentToExport = viewport.getAlignment();
1310 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1311 if (settings == null)
1313 settings = new AlignExportSettings(hasHiddenSeqs,
1314 viewport.hasHiddenColumns(), format);
1316 // settings.isExportAnnotations();
1318 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1320 omitHidden = viewport.getViewAsString(false,
1321 settings.isExportHiddenSequences());
1324 int[] alignmentStartEnd = new int[2];
1325 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1327 alignmentToExport = hiddenSeqs.getFullAlignment();
1331 alignmentToExport = viewport.getAlignment();
1333 alignmentStartEnd = alignmentToExport
1334 .getVisibleStartAndEndIndex(viewport.getAlignment()
1336 .getHiddenRegions());
1337 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1338 omitHidden, alignmentStartEnd, settings);
1349 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1351 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1352 htmlSVG.exportHTML(null);
1356 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1358 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1359 bjs.exportHTML(null);
1362 public void createImageMap(File file, String image)
1364 alignPanel.makePNGImageMap(file, image);
1374 public void createPNG(File f)
1376 alignPanel.makePNG(f);
1386 public void createEPS(File f)
1388 alignPanel.makeEPS(f);
1392 public void createSVG(File f)
1394 alignPanel.makeSVG(f);
1398 public void pageSetup_actionPerformed(ActionEvent e)
1400 PrinterJob printJob = PrinterJob.getPrinterJob();
1401 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1411 public void printMenuItem_actionPerformed(ActionEvent e)
1413 // Putting in a thread avoids Swing painting problems
1414 PrintThread thread = new PrintThread(alignPanel);
1419 public void exportFeatures_actionPerformed(ActionEvent e)
1421 new AnnotationExporter().exportFeatures(alignPanel);
1425 public void exportAnnotations_actionPerformed(ActionEvent e)
1427 new AnnotationExporter().exportAnnotations(alignPanel);
1431 public void associatedData_actionPerformed(ActionEvent e)
1433 // Pick the tree file
1434 JalviewFileChooser chooser = new JalviewFileChooser(
1435 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1436 chooser.setFileView(new JalviewFileView());
1437 chooser.setDialogTitle(MessageManager
1438 .getString("label.load_jalview_annotations"));
1439 chooser.setToolTipText(MessageManager
1440 .getString("label.load_jalview_annotations"));
1442 int value = chooser.showOpenDialog(null);
1444 if (value == JalviewFileChooser.APPROVE_OPTION)
1446 String choice = chooser.getSelectedFile().getPath();
1447 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1448 loadJalviewDataFile(choice, null, null, null);
1454 * Close the current view or all views in the alignment frame. If the frame
1455 * only contains one view then the alignment will be removed from memory.
1457 * @param closeAllTabs
1460 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1462 if (alignPanels != null && alignPanels.size() < 2)
1464 closeAllTabs = true;
1469 if (alignPanels != null)
1473 if (this.isClosed())
1475 // really close all the windows - otherwise wait till
1476 // setClosed(true) is called
1477 for (int i = 0; i < alignPanels.size(); i++)
1479 AlignmentPanel ap = alignPanels.get(i);
1486 closeView(alignPanel);
1493 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1494 * be called recursively, with the frame now in 'closed' state
1496 this.setClosed(true);
1498 } catch (Exception ex)
1500 ex.printStackTrace();
1505 * Close the specified panel and close up tabs appropriately.
1507 * @param panelToClose
1509 public void closeView(AlignmentPanel panelToClose)
1511 int index = tabbedPane.getSelectedIndex();
1512 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1513 alignPanels.remove(panelToClose);
1514 panelToClose.closePanel();
1515 panelToClose = null;
1517 tabbedPane.removeTabAt(closedindex);
1518 tabbedPane.validate();
1520 if (index > closedindex || index == tabbedPane.getTabCount())
1522 // modify currently selected tab index if necessary.
1526 this.tabSelectionChanged(index);
1532 void updateEditMenuBar()
1535 if (viewport.getHistoryList().size() > 0)
1537 undoMenuItem.setEnabled(true);
1538 CommandI command = viewport.getHistoryList().peek();
1539 undoMenuItem.setText(MessageManager.formatMessage(
1540 "label.undo_command",
1541 new Object[] { command.getDescription() }));
1545 undoMenuItem.setEnabled(false);
1546 undoMenuItem.setText(MessageManager.getString("action.undo"));
1549 if (viewport.getRedoList().size() > 0)
1551 redoMenuItem.setEnabled(true);
1553 CommandI command = viewport.getRedoList().peek();
1554 redoMenuItem.setText(MessageManager.formatMessage(
1555 "label.redo_command",
1556 new Object[] { command.getDescription() }));
1560 redoMenuItem.setEnabled(false);
1561 redoMenuItem.setText(MessageManager.getString("action.redo"));
1566 public void addHistoryItem(CommandI command)
1568 if (command.getSize() > 0)
1570 viewport.addToHistoryList(command);
1571 viewport.clearRedoList();
1572 updateEditMenuBar();
1573 viewport.updateHiddenColumns();
1574 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1575 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1576 // viewport.getColumnSelection()
1577 // .getHiddenColumns().size() > 0);
1583 * @return alignment objects for all views
1585 AlignmentI[] getViewAlignments()
1587 if (alignPanels != null)
1589 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1591 for (AlignmentPanel ap : alignPanels)
1593 als[i++] = ap.av.getAlignment();
1597 if (viewport != null)
1599 return new AlignmentI[] { viewport.getAlignment() };
1611 protected void undoMenuItem_actionPerformed(ActionEvent e)
1613 if (viewport.getHistoryList().isEmpty())
1617 CommandI command = viewport.getHistoryList().pop();
1618 viewport.addToRedoList(command);
1619 command.undoCommand(getViewAlignments());
1621 AlignmentViewport originalSource = getOriginatingSource(command);
1622 updateEditMenuBar();
1624 if (originalSource != null)
1626 if (originalSource != viewport)
1629 .warn("Implementation worry: mismatch of viewport origin for undo");
1631 originalSource.updateHiddenColumns();
1632 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1634 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1635 // viewport.getColumnSelection()
1636 // .getHiddenColumns().size() > 0);
1637 originalSource.firePropertyChange("alignment", null, originalSource
1638 .getAlignment().getSequences());
1649 protected void redoMenuItem_actionPerformed(ActionEvent e)
1651 if (viewport.getRedoList().size() < 1)
1656 CommandI command = viewport.getRedoList().pop();
1657 viewport.addToHistoryList(command);
1658 command.doCommand(getViewAlignments());
1660 AlignmentViewport originalSource = getOriginatingSource(command);
1661 updateEditMenuBar();
1663 if (originalSource != null)
1666 if (originalSource != viewport)
1669 .warn("Implementation worry: mismatch of viewport origin for redo");
1671 originalSource.updateHiddenColumns();
1672 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1674 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1675 // viewport.getColumnSelection()
1676 // .getHiddenColumns().size() > 0);
1677 originalSource.firePropertyChange("alignment", null, originalSource
1678 .getAlignment().getSequences());
1682 AlignmentViewport getOriginatingSource(CommandI command)
1684 AlignmentViewport originalSource = null;
1685 // For sequence removal and addition, we need to fire
1686 // the property change event FROM the viewport where the
1687 // original alignment was altered
1688 AlignmentI al = null;
1689 if (command instanceof EditCommand)
1691 EditCommand editCommand = (EditCommand) command;
1692 al = editCommand.getAlignment();
1693 List<Component> comps = PaintRefresher.components.get(viewport
1694 .getSequenceSetId());
1696 for (Component comp : comps)
1698 if (comp instanceof AlignmentPanel)
1700 if (al == ((AlignmentPanel) comp).av.getAlignment())
1702 originalSource = ((AlignmentPanel) comp).av;
1709 if (originalSource == null)
1711 // The original view is closed, we must validate
1712 // the current view against the closed view first
1715 PaintRefresher.validateSequences(al, viewport.getAlignment());
1718 originalSource = viewport;
1721 return originalSource;
1730 public void moveSelectedSequences(boolean up)
1732 SequenceGroup sg = viewport.getSelectionGroup();
1738 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1739 viewport.getHiddenRepSequences(), up);
1740 alignPanel.paintAlignment(true);
1743 synchronized void slideSequences(boolean right, int size)
1745 List<SequenceI> sg = new ArrayList<>();
1746 if (viewport.cursorMode)
1748 sg.add(viewport.getAlignment().getSequenceAt(
1749 alignPanel.getSeqPanel().seqCanvas.cursorY));
1751 else if (viewport.getSelectionGroup() != null
1752 && viewport.getSelectionGroup().getSize() != viewport
1753 .getAlignment().getHeight())
1755 sg = viewport.getSelectionGroup().getSequences(
1756 viewport.getHiddenRepSequences());
1764 List<SequenceI> invertGroup = new ArrayList<>();
1766 for (SequenceI seq : viewport.getAlignment().getSequences())
1768 if (!sg.contains(seq))
1770 invertGroup.add(seq);
1774 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1776 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1777 for (int i = 0; i < invertGroup.size(); i++)
1779 seqs2[i] = invertGroup.get(i);
1782 SlideSequencesCommand ssc;
1785 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1786 size, viewport.getGapCharacter());
1790 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1791 size, viewport.getGapCharacter());
1794 int groupAdjustment = 0;
1795 if (ssc.getGapsInsertedBegin() && right)
1797 if (viewport.cursorMode)
1799 alignPanel.getSeqPanel().moveCursor(size, 0);
1803 groupAdjustment = size;
1806 else if (!ssc.getGapsInsertedBegin() && !right)
1808 if (viewport.cursorMode)
1810 alignPanel.getSeqPanel().moveCursor(-size, 0);
1814 groupAdjustment = -size;
1818 if (groupAdjustment != 0)
1820 viewport.getSelectionGroup().setStartRes(
1821 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1822 viewport.getSelectionGroup().setEndRes(
1823 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1827 * just extend the last slide command if compatible; but not if in
1828 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1830 boolean appendHistoryItem = false;
1831 Deque<CommandI> historyList = viewport.getHistoryList();
1832 boolean inSplitFrame = getSplitViewContainer() != null;
1833 if (!inSplitFrame && historyList != null && historyList.size() > 0
1834 && historyList.peek() instanceof SlideSequencesCommand)
1836 appendHistoryItem = ssc
1837 .appendSlideCommand((SlideSequencesCommand) historyList
1841 if (!appendHistoryItem)
1843 addHistoryItem(ssc);
1856 protected void copy_actionPerformed(ActionEvent e)
1859 if (viewport.getSelectionGroup() == null)
1863 // TODO: preserve the ordering of displayed alignment annotation in any
1864 // internal paste (particularly sequence associated annotation)
1865 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1866 String[] omitHidden = null;
1868 if (viewport.hasHiddenColumns())
1870 omitHidden = viewport.getViewAsString(true);
1873 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1874 seqs, omitHidden, null);
1876 StringSelection ss = new StringSelection(output);
1880 jalview.gui.Desktop.internalCopy = true;
1881 // Its really worth setting the clipboard contents
1882 // to empty before setting the large StringSelection!!
1883 Toolkit.getDefaultToolkit().getSystemClipboard()
1884 .setContents(new StringSelection(""), null);
1886 Toolkit.getDefaultToolkit().getSystemClipboard()
1887 .setContents(ss, Desktop.instance);
1888 } catch (OutOfMemoryError er)
1890 new OOMWarning("copying region", er);
1894 ArrayList<int[]> hiddenColumns = null;
1895 if (viewport.hasHiddenColumns())
1897 hiddenColumns = new ArrayList<>();
1898 int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1899 .getSelectionGroup().getEndRes();
1900 for (int[] region : viewport.getAlignment().getHiddenColumns()
1901 .getHiddenRegions())
1903 if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1905 hiddenColumns.add(new int[] { region[0] - hiddenOffset,
1906 region[1] - hiddenOffset });
1911 Desktop.jalviewClipboard = new Object[] { seqs,
1912 viewport.getAlignment().getDataset(), hiddenColumns };
1913 statusBar.setText(MessageManager.formatMessage(
1914 "label.copied_sequences_to_clipboard", new Object[] { Integer
1915 .valueOf(seqs.length).toString() }));
1925 protected void pasteNew_actionPerformed(ActionEvent e)
1937 protected void pasteThis_actionPerformed(ActionEvent e)
1943 * Paste contents of Jalview clipboard
1945 * @param newAlignment
1946 * true to paste to a new alignment, otherwise add to this.
1948 void paste(boolean newAlignment)
1950 boolean externalPaste = true;
1953 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1954 Transferable contents = c.getContents(this);
1956 if (contents == null)
1965 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1966 if (str.length() < 1)
1971 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1973 } catch (OutOfMemoryError er)
1975 new OOMWarning("Out of memory pasting sequences!!", er);
1979 SequenceI[] sequences;
1980 boolean annotationAdded = false;
1981 AlignmentI alignment = null;
1983 if (Desktop.jalviewClipboard != null)
1985 // The clipboard was filled from within Jalview, we must use the
1987 // And dataset from the copied alignment
1988 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1989 // be doubly sure that we create *new* sequence objects.
1990 sequences = new SequenceI[newseq.length];
1991 for (int i = 0; i < newseq.length; i++)
1993 sequences[i] = new Sequence(newseq[i]);
1995 alignment = new Alignment(sequences);
1996 externalPaste = false;
2000 // parse the clipboard as an alignment.
2001 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2003 sequences = alignment.getSequencesArray();
2007 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2013 if (Desktop.jalviewClipboard != null)
2015 // dataset is inherited
2016 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2020 // new dataset is constructed
2021 alignment.setDataset(null);
2023 alwidth = alignment.getWidth() + 1;
2027 AlignmentI pastedal = alignment; // preserve pasted alignment object
2028 // Add pasted sequences and dataset into existing alignment.
2029 alignment = viewport.getAlignment();
2030 alwidth = alignment.getWidth() + 1;
2031 // decide if we need to import sequences from an existing dataset
2032 boolean importDs = Desktop.jalviewClipboard != null
2033 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2034 // importDs==true instructs us to copy over new dataset sequences from
2035 // an existing alignment
2036 Vector newDs = (importDs) ? new Vector() : null; // used to create
2037 // minimum dataset set
2039 for (int i = 0; i < sequences.length; i++)
2043 newDs.addElement(null);
2045 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2047 if (importDs && ds != null)
2049 if (!newDs.contains(ds))
2051 newDs.setElementAt(ds, i);
2052 ds = new Sequence(ds);
2053 // update with new dataset sequence
2054 sequences[i].setDatasetSequence(ds);
2058 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2063 // copy and derive new dataset sequence
2064 sequences[i] = sequences[i].deriveSequence();
2065 alignment.getDataset().addSequence(
2066 sequences[i].getDatasetSequence());
2067 // TODO: avoid creation of duplicate dataset sequences with a
2068 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2070 alignment.addSequence(sequences[i]); // merges dataset
2074 newDs.clear(); // tidy up
2076 if (alignment.getAlignmentAnnotation() != null)
2078 for (AlignmentAnnotation alan : alignment
2079 .getAlignmentAnnotation())
2081 if (alan.graphGroup > fgroup)
2083 fgroup = alan.graphGroup;
2087 if (pastedal.getAlignmentAnnotation() != null)
2089 // Add any annotation attached to alignment.
2090 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2091 for (int i = 0; i < alann.length; i++)
2093 annotationAdded = true;
2094 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2096 AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2097 if (newann.graphGroup > -1)
2099 if (newGraphGroups.size() <= newann.graphGroup
2100 || newGraphGroups.get(newann.graphGroup) == null)
2102 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2104 newGraphGroups.add(q, null);
2106 newGraphGroups.set(newann.graphGroup, new Integer(
2109 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2113 newann.padAnnotation(alwidth);
2114 alignment.addAnnotation(newann);
2124 addHistoryItem(new EditCommand(
2125 MessageManager.getString("label.add_sequences"),
2126 Action.PASTE, sequences, 0, alignment.getWidth(), alignment));
2128 // Add any annotations attached to sequences
2129 for (int i = 0; i < sequences.length; i++)
2131 if (sequences[i].getAnnotation() != null)
2133 AlignmentAnnotation newann;
2134 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2136 annotationAdded = true;
2137 newann = sequences[i].getAnnotation()[a];
2138 newann.adjustForAlignment();
2139 newann.padAnnotation(alwidth);
2140 if (newann.graphGroup > -1)
2142 if (newann.graphGroup > -1)
2144 if (newGraphGroups.size() <= newann.graphGroup
2145 || newGraphGroups.get(newann.graphGroup) == null)
2147 for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2149 newGraphGroups.add(q, null);
2151 newGraphGroups.set(newann.graphGroup, new Integer(
2154 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2158 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2163 .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2170 // propagate alignment changed.
2171 vpRanges.setEndSeq(alignment.getHeight());
2172 if (annotationAdded)
2174 // Duplicate sequence annotation in all views.
2175 AlignmentI[] alview = this.getViewAlignments();
2176 for (int i = 0; i < sequences.length; i++)
2178 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2183 for (int avnum = 0; avnum < alview.length; avnum++)
2185 if (alview[avnum] != alignment)
2187 // duplicate in a view other than the one with input focus
2188 int avwidth = alview[avnum].getWidth() + 1;
2189 // this relies on sann being preserved after we
2190 // modify the sequence's annotation array for each duplication
2191 for (int a = 0; a < sann.length; a++)
2193 AlignmentAnnotation newann = new AlignmentAnnotation(
2195 sequences[i].addAlignmentAnnotation(newann);
2196 newann.padAnnotation(avwidth);
2197 alview[avnum].addAnnotation(newann); // annotation was
2198 // duplicated earlier
2199 // TODO JAL-1145 graphGroups are not updated for sequence
2200 // annotation added to several views. This may cause
2202 alview[avnum].setAnnotationIndex(newann, a);
2207 buildSortByAnnotationScoresMenu();
2209 viewport.firePropertyChange("alignment", null,
2210 alignment.getSequences());
2211 if (alignPanels != null)
2213 for (AlignmentPanel ap : alignPanels)
2215 ap.validateAnnotationDimensions(false);
2220 alignPanel.validateAnnotationDimensions(false);
2226 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2228 String newtitle = new String("Copied sequences");
2230 if (Desktop.jalviewClipboard != null
2231 && Desktop.jalviewClipboard[2] != null)
2233 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2234 for (int[] region : hc)
2236 af.viewport.hideColumns(region[0], region[1]);
2240 // >>>This is a fix for the moment, until a better solution is
2242 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2244 alignPanel.getSeqPanel().seqCanvas
2245 .getFeatureRenderer());
2247 // TODO: maintain provenance of an alignment, rather than just make the
2248 // title a concatenation of operations.
2251 if (title.startsWith("Copied sequences"))
2257 newtitle = newtitle.concat("- from " + title);
2262 newtitle = new String("Pasted sequences");
2265 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2270 } catch (Exception ex)
2272 ex.printStackTrace();
2273 System.out.println("Exception whilst pasting: " + ex);
2274 // could be anything being pasted in here
2280 protected void expand_newalign(ActionEvent e)
2284 AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2285 .getAlignment(), -1);
2286 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2288 String newtitle = new String("Flanking alignment");
2290 if (Desktop.jalviewClipboard != null
2291 && Desktop.jalviewClipboard[2] != null)
2293 List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2294 for (int region[] : hc)
2296 af.viewport.hideColumns(region[0], region[1]);
2300 // >>>This is a fix for the moment, until a better solution is
2302 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2304 alignPanel.getSeqPanel().seqCanvas
2305 .getFeatureRenderer());
2307 // TODO: maintain provenance of an alignment, rather than just make the
2308 // title a concatenation of operations.
2310 if (title.startsWith("Copied sequences"))
2316 newtitle = newtitle.concat("- from " + title);
2320 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2322 } catch (Exception ex)
2324 ex.printStackTrace();
2325 System.out.println("Exception whilst pasting: " + ex);
2326 // could be anything being pasted in here
2327 } catch (OutOfMemoryError oom)
2329 new OOMWarning("Viewing flanking region of alignment", oom);
2340 protected void cut_actionPerformed(ActionEvent e)
2342 copy_actionPerformed(null);
2343 delete_actionPerformed(null);
2353 protected void delete_actionPerformed(ActionEvent evt)
2356 SequenceGroup sg = viewport.getSelectionGroup();
2363 * If the cut affects all sequences, warn, remove highlighted columns
2365 if (sg.getSize() == viewport.getAlignment().getHeight())
2367 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes()) + 1) == viewport
2368 .getAlignment().getWidth()) ? true : false;
2369 if (isEntireAlignWidth)
2371 int confirm = JvOptionPane.showConfirmDialog(this,
2372 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2373 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2374 JvOptionPane.OK_CANCEL_OPTION);
2376 if (confirm == JvOptionPane.CANCEL_OPTION
2377 || confirm == JvOptionPane.CLOSED_OPTION)
2382 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2383 sg.getEndRes() + 1);
2385 SequenceI[] cut = sg.getSequences()
2386 .toArray(new SequenceI[sg.getSize()]);
2388 addHistoryItem(new EditCommand(
2389 MessageManager.getString("label.cut_sequences"), Action.CUT,
2390 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2391 viewport.getAlignment()));
2393 viewport.setSelectionGroup(null);
2394 viewport.sendSelection();
2395 viewport.getAlignment().deleteGroup(sg);
2397 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2399 if (viewport.getAlignment().getHeight() < 1)
2403 this.setClosed(true);
2404 } catch (Exception ex)
2417 protected void deleteGroups_actionPerformed(ActionEvent e)
2419 if (avc.deleteGroups())
2421 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2422 alignPanel.updateAnnotation();
2423 alignPanel.paintAlignment(true);
2434 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2436 SequenceGroup sg = new SequenceGroup();
2438 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2440 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2443 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2444 viewport.setSelectionGroup(sg);
2445 viewport.sendSelection();
2446 // JAL-2034 - should delegate to
2447 // alignPanel to decide if overview needs
2449 alignPanel.paintAlignment(false);
2450 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2460 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2462 if (viewport.cursorMode)
2464 alignPanel.getSeqPanel().keyboardNo1 = null;
2465 alignPanel.getSeqPanel().keyboardNo2 = null;
2467 viewport.setSelectionGroup(null);
2468 viewport.getColumnSelection().clear();
2469 viewport.setSelectionGroup(null);
2470 alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2471 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2472 // JAL-2034 - should delegate to
2473 // alignPanel to decide if overview needs
2475 alignPanel.paintAlignment(false);
2476 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477 viewport.sendSelection();
2487 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2489 SequenceGroup sg = viewport.getSelectionGroup();
2493 selectAllSequenceMenuItem_actionPerformed(null);
2498 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2500 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2502 // JAL-2034 - should delegate to
2503 // alignPanel to decide if overview needs
2506 alignPanel.paintAlignment(true);
2507 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2508 viewport.sendSelection();
2512 public void invertColSel_actionPerformed(ActionEvent e)
2514 viewport.invertColumnSelection();
2515 alignPanel.paintAlignment(true);
2516 viewport.sendSelection();
2526 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2528 trimAlignment(true);
2538 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2540 trimAlignment(false);
2543 void trimAlignment(boolean trimLeft)
2545 ColumnSelection colSel = viewport.getColumnSelection();
2548 if (!colSel.isEmpty())
2552 column = colSel.getMin();
2556 column = colSel.getMax();
2560 if (viewport.getSelectionGroup() != null)
2562 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2563 viewport.getHiddenRepSequences());
2567 seqs = viewport.getAlignment().getSequencesArray();
2570 TrimRegionCommand trimRegion;
2573 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2574 column, viewport.getAlignment());
2575 vpRanges.setStartRes(0);
2579 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2580 column, viewport.getAlignment());
2583 statusBar.setText(MessageManager.formatMessage(
2584 "label.removed_columns",
2585 new String[] { Integer.valueOf(trimRegion.getSize())
2588 addHistoryItem(trimRegion);
2590 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2592 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2593 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2595 viewport.getAlignment().deleteGroup(sg);
2599 viewport.firePropertyChange("alignment", null, viewport
2600 .getAlignment().getSequences());
2611 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2613 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2616 if (viewport.getSelectionGroup() != null)
2618 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2619 viewport.getHiddenRepSequences());
2620 start = viewport.getSelectionGroup().getStartRes();
2621 end = viewport.getSelectionGroup().getEndRes();
2625 seqs = viewport.getAlignment().getSequencesArray();
2628 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2629 "Remove Gapped Columns", seqs, start, end,
2630 viewport.getAlignment());
2632 addHistoryItem(removeGapCols);
2634 statusBar.setText(MessageManager.formatMessage(
2635 "label.removed_empty_columns",
2636 new Object[] { Integer.valueOf(removeGapCols.getSize())
2639 // This is to maintain viewport position on first residue
2640 // of first sequence
2641 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2642 int startRes = seq.findPosition(vpRanges.getStartRes());
2643 // ShiftList shifts;
2644 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2645 // edit.alColumnChanges=shifts.getInverse();
2646 // if (viewport.hasHiddenColumns)
2647 // viewport.getColumnSelection().compensateForEdits(shifts);
2648 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2649 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2661 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2663 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2666 if (viewport.getSelectionGroup() != null)
2668 seqs = viewport.getSelectionGroup().getSequencesAsArray(
2669 viewport.getHiddenRepSequences());
2670 start = viewport.getSelectionGroup().getStartRes();
2671 end = viewport.getSelectionGroup().getEndRes();
2675 seqs = viewport.getAlignment().getSequencesArray();
2678 // This is to maintain viewport position on first residue
2679 // of first sequence
2680 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2681 int startRes = seq.findPosition(vpRanges.getStartRes());
2683 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2684 viewport.getAlignment()));
2686 vpRanges.setStartRes(seq.findIndex(startRes) - 1);
2688 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2700 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2702 viewport.setPadGaps(padGapsMenuitem.isSelected());
2703 viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2714 public void findMenuItem_actionPerformed(ActionEvent e)
2720 * Create a new view of the current alignment.
2723 public void newView_actionPerformed(ActionEvent e)
2725 newView(null, true);
2729 * Creates and shows a new view of the current alignment.
2732 * title of newly created view; if null, one will be generated
2733 * @param copyAnnotation
2734 * if true then duplicate all annnotation, groups and settings
2735 * @return new alignment panel, already displayed.
2737 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2740 * Create a new AlignmentPanel (with its own, new Viewport)
2742 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2744 if (!copyAnnotation)
2747 * remove all groups and annotation except for the automatic stuff
2749 newap.av.getAlignment().deleteAllGroups();
2750 newap.av.getAlignment().deleteAllAnnotations(false);
2753 newap.av.setGatherViewsHere(false);
2755 if (viewport.viewName == null)
2757 viewport.viewName = MessageManager
2758 .getString("label.view_name_original");
2762 * Views share the same edits undo and redo stacks
2764 newap.av.setHistoryList(viewport.getHistoryList());
2765 newap.av.setRedoList(viewport.getRedoList());
2768 * Views share the same mappings; need to deregister any new mappings
2769 * created by copyAlignPanel, and register the new reference to the shared
2772 newap.av.replaceMappings(viewport.getAlignment());
2775 * start up cDNA consensus (if applicable) now mappings are in place
2777 if (newap.av.initComplementConsensus())
2779 newap.refresh(true); // adjust layout of annotations
2782 newap.av.viewName = getNewViewName(viewTitle);
2784 addAlignmentPanel(newap, true);
2785 newap.alignmentChanged();
2787 if (alignPanels.size() == 2)
2789 viewport.setGatherViewsHere(true);
2791 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2796 * Make a new name for the view, ensuring it is unique within the current
2797 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2798 * these now use viewId. Unique view names are still desirable for usability.)
2803 protected String getNewViewName(String viewTitle)
2805 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2806 boolean addFirstIndex = false;
2807 if (viewTitle == null || viewTitle.trim().length() == 0)
2809 viewTitle = MessageManager.getString("action.view");
2810 addFirstIndex = true;
2814 index = 1;// we count from 1 if given a specific name
2816 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2818 List<Component> comps = PaintRefresher.components.get(viewport
2819 .getSequenceSetId());
2821 List<String> existingNames = getExistingViewNames(comps);
2823 while (existingNames.contains(newViewName))
2825 newViewName = viewTitle + " " + (++index);
2831 * Returns a list of distinct view names found in the given list of
2832 * components. View names are held on the viewport of an AlignmentPanel.
2837 protected List<String> getExistingViewNames(List<Component> comps)
2839 List<String> existingNames = new ArrayList<>();
2840 for (Component comp : comps)
2842 if (comp instanceof AlignmentPanel)
2844 AlignmentPanel ap = (AlignmentPanel) comp;
2845 if (!existingNames.contains(ap.av.viewName))
2847 existingNames.add(ap.av.viewName);
2851 return existingNames;
2855 * Explode tabbed views into separate windows.
2858 public void expandViews_actionPerformed(ActionEvent e)
2860 Desktop.explodeViews(this);
2864 * Gather views in separate windows back into a tabbed presentation.
2867 public void gatherViews_actionPerformed(ActionEvent e)
2869 Desktop.instance.gatherViews(this);
2879 public void font_actionPerformed(ActionEvent e)
2881 new FontChooser(alignPanel);
2891 protected void seqLimit_actionPerformed(ActionEvent e)
2893 viewport.setShowJVSuffix(seqLimits.isSelected());
2895 alignPanel.getIdPanel().getIdCanvas()
2896 .setPreferredSize(alignPanel.calculateIdWidth());
2897 alignPanel.paintAlignment(true);
2901 public void idRightAlign_actionPerformed(ActionEvent e)
2903 viewport.setRightAlignIds(idRightAlign.isSelected());
2904 alignPanel.paintAlignment(true);
2908 public void centreColumnLabels_actionPerformed(ActionEvent e)
2910 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2911 alignPanel.paintAlignment(true);
2917 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2920 protected void followHighlight_actionPerformed()
2923 * Set the 'follow' flag on the Viewport (and scroll to position if now
2926 final boolean state = this.followHighlightMenuItem.getState();
2927 viewport.setFollowHighlight(state);
2930 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2941 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2943 viewport.setColourText(colourTextMenuItem.isSelected());
2944 alignPanel.paintAlignment(true);
2954 public void wrapMenuItem_actionPerformed(ActionEvent e)
2956 scaleAbove.setVisible(wrapMenuItem.isSelected());
2957 scaleLeft.setVisible(wrapMenuItem.isSelected());
2958 scaleRight.setVisible(wrapMenuItem.isSelected());
2959 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2960 alignPanel.updateLayout();
2964 public void showAllSeqs_actionPerformed(ActionEvent e)
2966 viewport.showAllHiddenSeqs();
2970 public void showAllColumns_actionPerformed(ActionEvent e)
2972 viewport.showAllHiddenColumns();
2974 viewport.sendSelection();
2978 public void hideSelSequences_actionPerformed(ActionEvent e)
2980 viewport.hideAllSelectedSeqs();
2981 // alignPanel.paintAlignment(true);
2985 * called by key handler and the hide all/show all menu items
2990 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2993 boolean hide = false;
2994 SequenceGroup sg = viewport.getSelectionGroup();
2995 if (!toggleSeqs && !toggleCols)
2997 // Hide everything by the current selection - this is a hack - we do the
2998 // invert and then hide
2999 // first check that there will be visible columns after the invert.
3000 if (viewport.hasSelectedColumns()
3001 || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
3004 // now invert the sequence set, if required - empty selection implies
3005 // that no hiding is required.
3008 invertSequenceMenuItem_actionPerformed(null);
3009 sg = viewport.getSelectionGroup();
3013 viewport.expandColSelection(sg, true);
3014 // finally invert the column selection and get the new sequence
3016 invertColSel_actionPerformed(null);
3023 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3025 hideSelSequences_actionPerformed(null);
3028 else if (!(toggleCols && viewport.hasSelectedColumns()))
3030 showAllSeqs_actionPerformed(null);
3036 if (viewport.hasSelectedColumns())
3038 hideSelColumns_actionPerformed(null);
3041 viewport.setSelectionGroup(sg);
3046 showAllColumns_actionPerformed(null);
3055 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3056 * event.ActionEvent)
3059 public void hideAllButSelection_actionPerformed(ActionEvent e)
3061 toggleHiddenRegions(false, false);
3062 viewport.sendSelection();
3069 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3073 public void hideAllSelection_actionPerformed(ActionEvent e)
3075 SequenceGroup sg = viewport.getSelectionGroup();
3076 viewport.expandColSelection(sg, false);
3077 viewport.hideAllSelectedSeqs();
3078 viewport.hideSelectedColumns();
3079 alignPanel.paintAlignment(true);
3080 viewport.sendSelection();
3087 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3091 public void showAllhidden_actionPerformed(ActionEvent e)
3093 viewport.showAllHiddenColumns();
3094 viewport.showAllHiddenSeqs();
3095 alignPanel.paintAlignment(true);
3096 viewport.sendSelection();
3100 public void hideSelColumns_actionPerformed(ActionEvent e)
3102 viewport.hideSelectedColumns();
3103 alignPanel.paintAlignment(true);
3104 viewport.sendSelection();
3108 public void hiddenMarkers_actionPerformed(ActionEvent e)
3110 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3121 protected void scaleAbove_actionPerformed(ActionEvent e)
3123 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3124 alignPanel.paintAlignment(true);
3134 protected void scaleLeft_actionPerformed(ActionEvent e)
3136 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3137 alignPanel.paintAlignment(true);
3147 protected void scaleRight_actionPerformed(ActionEvent e)
3149 viewport.setScaleRightWrapped(scaleRight.isSelected());
3150 alignPanel.paintAlignment(true);
3160 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3163 alignPanel.paintAlignment(true);
3173 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3175 viewport.setShowText(viewTextMenuItem.isSelected());
3176 alignPanel.paintAlignment(true);
3186 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3188 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3189 alignPanel.paintAlignment(true);
3192 public FeatureSettings featureSettings;
3195 public FeatureSettingsControllerI getFeatureSettingsUI()
3197 return featureSettings;
3201 public void featureSettings_actionPerformed(ActionEvent e)
3203 if (featureSettings != null)
3205 featureSettings.close();
3206 featureSettings = null;
3208 if (!showSeqFeatures.isSelected())
3210 // make sure features are actually displayed
3211 showSeqFeatures.setSelected(true);
3212 showSeqFeatures_actionPerformed(null);
3214 featureSettings = new FeatureSettings(this);
3218 * Set or clear 'Show Sequence Features'
3224 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3226 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3227 alignPanel.paintAlignment(true);
3228 if (alignPanel.getOverviewPanel() != null)
3230 alignPanel.getOverviewPanel().updateOverviewImage();
3235 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3236 * the annotations panel as a whole.
3238 * The options to show/hide all annotations should be enabled when the panel
3239 * is shown, and disabled when the panel is hidden.
3244 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3246 final boolean setVisible = annotationPanelMenuItem.isSelected();
3247 viewport.setShowAnnotation(setVisible);
3248 this.showAllSeqAnnotations.setEnabled(setVisible);
3249 this.hideAllSeqAnnotations.setEnabled(setVisible);
3250 this.showAllAlAnnotations.setEnabled(setVisible);
3251 this.hideAllAlAnnotations.setEnabled(setVisible);
3252 alignPanel.updateLayout();
3256 public void alignmentProperties()
3258 JEditorPane editPane = new JEditorPane("text/html", "");
3259 editPane.setEditable(false);
3260 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3262 editPane.setText(MessageManager.formatMessage("label.html_content",
3263 new Object[] { contents.toString() }));
3264 JInternalFrame frame = new JInternalFrame();
3265 frame.getContentPane().add(new JScrollPane(editPane));
3267 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3268 "label.alignment_properties", new Object[] { getTitle() }),
3279 public void overviewMenuItem_actionPerformed(ActionEvent e)
3281 if (alignPanel.overviewPanel != null)
3286 JInternalFrame frame = new JInternalFrame();
3287 OverviewPanel overview = new OverviewPanel(alignPanel);
3288 frame.setContentPane(overview);
3289 Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3290 "label.overview_params", new Object[] { this.getTitle() }),
3291 true, frame.getWidth(), frame.getHeight(), true, true);
3293 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3294 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3297 public void internalFrameClosed(
3298 javax.swing.event.InternalFrameEvent evt)
3300 alignPanel.setOverviewPanel(null);
3304 alignPanel.setOverviewPanel(overview);
3308 public void textColour_actionPerformed()
3310 new TextColourChooser().chooseColour(alignPanel, null);
3314 * public void covariationColour_actionPerformed() {
3316 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3320 public void annotationColour_actionPerformed()
3322 new AnnotationColourChooser(viewport, alignPanel);
3326 public void annotationColumn_actionPerformed(ActionEvent e)
3328 new AnnotationColumnChooser(viewport, alignPanel);
3332 * Action on the user checking or unchecking the option to apply the selected
3333 * colour scheme to all groups. If unchecked, groups may have their own
3334 * independent colour schemes.
3339 public void applyToAllGroups_actionPerformed(boolean selected)
3341 viewport.setColourAppliesToAllGroups(selected);
3345 * Action on user selecting a colour from the colour menu
3348 * the name (not the menu item label!) of the colour scheme
3351 public void changeColour_actionPerformed(String name)
3354 * 'User Defined' opens a panel to configure or load a
3355 * user-defined colour scheme
3357 if (ResidueColourScheme.USER_DEFINED.equals(name))
3359 new UserDefinedColours(alignPanel);
3364 * otherwise set the chosen colour scheme (or null for 'None')
3366 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3367 viewport.getAlignment(), viewport.getHiddenRepSequences());
3372 * Actions on setting or changing the alignment colour scheme
3377 public void changeColour(ColourSchemeI cs)
3379 // TODO: pull up to controller method
3380 ColourMenuHelper.setColourSelected(colourMenu, cs);
3382 viewport.setGlobalColourScheme(cs);
3384 alignPanel.paintAlignment(true);
3388 * Show the PID threshold slider panel
3391 protected void modifyPID_actionPerformed()
3393 SliderPanel.setPIDSliderSource(alignPanel,
3394 viewport.getResidueShading(), alignPanel.getViewName());
3395 SliderPanel.showPIDSlider();
3399 * Show the Conservation slider panel
3402 protected void modifyConservation_actionPerformed()
3404 SliderPanel.setConservationSlider(alignPanel,
3405 viewport.getResidueShading(), alignPanel.getViewName());
3406 SliderPanel.showConservationSlider();
3410 * Action on selecting or deselecting (Colour) By Conservation
3413 public void conservationMenuItem_actionPerformed(boolean selected)
3415 modifyConservation.setEnabled(selected);
3416 viewport.setConservationSelected(selected);
3417 viewport.getResidueShading().setConservationApplied(selected);
3419 changeColour(viewport.getGlobalColourScheme());
3422 modifyConservation_actionPerformed();
3426 SliderPanel.hideConservationSlider();
3431 * Action on selecting or deselecting (Colour) Above PID Threshold
3434 public void abovePIDThreshold_actionPerformed(boolean selected)
3436 modifyPID.setEnabled(selected);
3437 viewport.setAbovePIDThreshold(selected);
3440 viewport.getResidueShading().setThreshold(0,
3441 viewport.isIgnoreGapsConsensus());
3444 changeColour(viewport.getGlobalColourScheme());
3447 modifyPID_actionPerformed();
3451 SliderPanel.hidePIDSlider();
3462 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3464 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3465 AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3466 .getAlignment().getSequenceAt(0));
3467 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3468 viewport.getAlignment()));
3469 alignPanel.paintAlignment(true);
3479 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3481 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3482 AlignmentSorter.sortByID(viewport.getAlignment());
3483 addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3484 viewport.getAlignment()));
3485 alignPanel.paintAlignment(true);
3495 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3497 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3498 AlignmentSorter.sortByLength(viewport.getAlignment());
3499 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3500 viewport.getAlignment()));
3501 alignPanel.paintAlignment(true);
3511 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3513 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3514 AlignmentSorter.sortByGroup(viewport.getAlignment());
3515 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3516 viewport.getAlignment()));
3518 alignPanel.paintAlignment(true);
3528 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3530 new RedundancyPanel(alignPanel, this);
3540 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3542 if ((viewport.getSelectionGroup() == null)
3543 || (viewport.getSelectionGroup().getSize() < 2))
3545 JvOptionPane.showInternalMessageDialog(this, MessageManager
3546 .getString("label.you_must_select_least_two_sequences"),
3547 MessageManager.getString("label.invalid_selection"),
3548 JvOptionPane.WARNING_MESSAGE);
3552 JInternalFrame frame = new JInternalFrame();
3553 frame.setContentPane(new PairwiseAlignPanel(viewport));
3554 Desktop.addInternalFrame(frame,
3555 MessageManager.getString("action.pairwise_alignment"), 600,
3561 public void autoCalculate_actionPerformed(ActionEvent e)
3563 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3564 if (viewport.autoCalculateConsensus)
3566 viewport.firePropertyChange("alignment", null, viewport
3567 .getAlignment().getSequences());
3572 public void sortByTreeOption_actionPerformed(ActionEvent e)
3574 viewport.sortByTree = sortByTree.isSelected();
3578 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3580 viewport.followSelection = listenToViewSelections.isSelected();
3584 * Constructs a tree panel and adds it to the desktop
3587 * tree type (NJ or AV)
3589 * name of score model used to compute the tree
3591 * parameters for the distance or similarity calculation
3593 void newTreePanel(String type, String modelName, SimilarityParamsI options)
3595 String frameTitle = "";
3598 boolean onSelection = false;
3599 if (viewport.getSelectionGroup() != null
3600 && viewport.getSelectionGroup().getSize() > 0)
3602 SequenceGroup sg = viewport.getSelectionGroup();
3604 /* Decide if the selection is a column region */
3605 for (SequenceI _s : sg.getSequences())
3607 if (_s.getLength() < sg.getEndRes())
3613 .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3615 .getString("label.sequences_selection_not_aligned"),
3616 JvOptionPane.WARNING_MESSAGE);
3625 if (viewport.getAlignment().getHeight() < 2)
3631 tp = new TreePanel(alignPanel, type, modelName, options);
3632 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3634 frameTitle += " from ";
3636 if (viewport.viewName != null)
3638 frameTitle += viewport.viewName + " of ";
3641 frameTitle += this.title;
3643 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3654 public void addSortByOrderMenuItem(String title,
3655 final AlignmentOrder order)
3657 final JMenuItem item = new JMenuItem(MessageManager.formatMessage(
3658 "action.by_title_param", new Object[] { title }));
3660 item.addActionListener(new java.awt.event.ActionListener()
3663 public void actionPerformed(ActionEvent e)
3665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3667 // TODO: JBPNote - have to map order entries to curent SequenceI
3669 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3671 addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
3674 alignPanel.paintAlignment(true);
3680 * Add a new sort by annotation score menu item
3683 * the menu to add the option to
3685 * the label used to retrieve scores for each sequence on the
3688 public void addSortByAnnotScoreMenuItem(JMenu sort,
3689 final String scoreLabel)
3691 final JMenuItem item = new JMenuItem(scoreLabel);
3693 item.addActionListener(new java.awt.event.ActionListener()
3696 public void actionPerformed(ActionEvent e)
3698 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3699 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3700 viewport.getAlignment());// ,viewport.getSelectionGroup());
3701 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3702 viewport.getAlignment()));
3703 alignPanel.paintAlignment(true);
3709 * last hash for alignment's annotation array - used to minimise cost of
3712 protected int _annotationScoreVectorHash;
3715 * search the alignment and rebuild the sort by annotation score submenu the
3716 * last alignment annotation vector hash is stored to minimize cost of
3717 * rebuilding in subsequence calls.
3721 public void buildSortByAnnotationScoresMenu()
3723 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3728 if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
3730 sortByAnnotScore.removeAll();
3731 // almost certainly a quicker way to do this - but we keep it simple
3732 Hashtable scoreSorts = new Hashtable();
3733 AlignmentAnnotation aann[];
3734 for (SequenceI sqa : viewport.getAlignment().getSequences())
3736 aann = sqa.getAnnotation();
3737 for (int i = 0; aann != null && i < aann.length; i++)
3739 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3741 scoreSorts.put(aann[i].label, aann[i].label);
3745 Enumeration labels = scoreSorts.keys();
3746 while (labels.hasMoreElements())
3748 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3749 (String) labels.nextElement());
3751 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3754 _annotationScoreVectorHash = viewport.getAlignment()
3755 .getAlignmentAnnotation().hashCode();
3760 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3761 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3762 * call. Listeners are added to remove the menu item when the treePanel is
3763 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3767 public void buildTreeSortMenu()
3769 sortByTreeMenu.removeAll();
3771 List<Component> comps = PaintRefresher.components.get(viewport
3772 .getSequenceSetId());
3773 List<TreePanel> treePanels = new ArrayList<>();
3774 for (Component comp : comps)
3776 if (comp instanceof TreePanel)
3778 treePanels.add((TreePanel) comp);
3782 if (treePanels.size() < 1)
3784 sortByTreeMenu.setVisible(false);
3788 sortByTreeMenu.setVisible(true);
3790 for (final TreePanel tp : treePanels)
3792 final JMenuItem item = new JMenuItem(tp.getTitle());
3793 item.addActionListener(new java.awt.event.ActionListener()
3796 public void actionPerformed(ActionEvent e)
3798 tp.sortByTree_actionPerformed();
3799 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3804 sortByTreeMenu.add(item);
3808 public boolean sortBy(AlignmentOrder alorder, String undoname)
3810 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3811 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3812 if (undoname != null)
3814 addHistoryItem(new OrderCommand(undoname, oldOrder,
3815 viewport.getAlignment()));
3817 alignPanel.paintAlignment(true);
3822 * Work out whether the whole set of sequences or just the selected set will
3823 * be submitted for multiple alignment.
3826 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3828 // Now, check we have enough sequences
3829 AlignmentView msa = null;
3831 if ((viewport.getSelectionGroup() != null)
3832 && (viewport.getSelectionGroup().getSize() > 1))
3834 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3835 // some common interface!
3837 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3838 * SequenceI[sz = seqs.getSize(false)];
3840 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3841 * seqs.getSequenceAt(i); }
3843 msa = viewport.getAlignmentView(true);
3845 else if (viewport.getSelectionGroup() != null
3846 && viewport.getSelectionGroup().getSize() == 1)
3848 int option = JvOptionPane.showConfirmDialog(this,
3849 MessageManager.getString("warn.oneseq_msainput_selection"),
3850 MessageManager.getString("label.invalid_selection"),
3851 JvOptionPane.OK_CANCEL_OPTION);
3852 if (option == JvOptionPane.OK_OPTION)
3854 msa = viewport.getAlignmentView(false);
3859 msa = viewport.getAlignmentView(false);
3865 * Decides what is submitted to a secondary structure prediction service: the
3866 * first sequence in the alignment, or in the current selection, or, if the
3867 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3868 * region or the whole alignment. (where the first sequence in the set is the
3869 * one that the prediction will be for).
3871 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3873 AlignmentView seqs = null;
3875 if ((viewport.getSelectionGroup() != null)
3876 && (viewport.getSelectionGroup().getSize() > 0))
3878 seqs = viewport.getAlignmentView(true);
3882 seqs = viewport.getAlignmentView(false);
3884 // limit sequences - JBPNote in future - could spawn multiple prediction
3886 // TODO: viewport.getAlignment().isAligned is a global state - the local
3887 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3888 if (!viewport.getAlignment().isAligned(false))
3890 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3891 // TODO: if seqs.getSequences().length>1 then should really have warned
3905 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3907 // Pick the tree file
3908 JalviewFileChooser chooser = new JalviewFileChooser(
3909 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3910 chooser.setFileView(new JalviewFileView());
3911 chooser.setDialogTitle(MessageManager
3912 .getString("label.select_newick_like_tree_file"));
3913 chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
3915 int value = chooser.showOpenDialog(null);
3917 if (value == JalviewFileChooser.APPROVE_OPTION)
3919 String filePath = chooser.getSelectedFile().getPath();
3920 Cache.setProperty("LAST_DIRECTORY", filePath);
3921 NewickFile fin = null;
3924 fin = new NewickFile(filePath, DataSourceType.FILE);
3925 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3926 } catch (Exception ex)
3933 .getString("label.problem_reading_tree_file"),
3934 JvOptionPane.WARNING_MESSAGE);
3935 ex.printStackTrace();
3937 if (fin != null && fin.hasWarningMessage())
3939 JvOptionPane.showMessageDialog(Desktop.desktop, fin
3940 .getWarningMessage(), MessageManager
3941 .getString("label.possible_problem_with_tree_file"),
3942 JvOptionPane.WARNING_MESSAGE);
3947 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3949 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3952 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3953 int h, int x, int y)
3955 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3959 * Add a treeviewer for the tree extracted from a Newick file object to the
3960 * current alignment view
3967 * Associated alignment input data (or null)
3976 * @return TreePanel handle
3978 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3979 AlignmentView input, int w, int h, int x, int y)
3981 TreePanel tp = null;
3987 if (nf.getTree() != null)
3989 tp = new TreePanel(alignPanel, nf, treeTitle, input);
3995 tp.setLocation(x, y);
3998 Desktop.addInternalFrame(tp, treeTitle, w, h);
4000 } catch (Exception ex)
4002 ex.printStackTrace();
4008 private boolean buildingMenu = false;
4011 * Generates menu items and listener event actions for web service clients
4014 public void BuildWebServiceMenu()
4016 while (buildingMenu)
4020 System.err.println("Waiting for building menu to finish.");
4022 } catch (Exception e)
4026 final AlignFrame me = this;
4027 buildingMenu = true;
4028 new Thread(new Runnable()
4033 final List<JMenuItem> legacyItems = new ArrayList<>();
4036 // System.err.println("Building ws menu again "
4037 // + Thread.currentThread());
4038 // TODO: add support for context dependent disabling of services based
4040 // alignment and current selection
4041 // TODO: add additional serviceHandle parameter to specify abstract
4043 // class independently of AbstractName
4044 // TODO: add in rediscovery GUI function to restart discoverer
4045 // TODO: group services by location as well as function and/or
4047 // object broker mechanism.
4048 final Vector<JMenu> wsmenu = new Vector<>();
4049 final IProgressIndicator af = me;
4052 * do not i18n these strings - they are hard-coded in class
4053 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4054 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4056 final JMenu msawsmenu = new JMenu("Alignment");
4057 final JMenu secstrmenu = new JMenu(
4058 "Secondary Structure Prediction");
4059 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4060 final JMenu analymenu = new JMenu("Analysis");
4061 final JMenu dismenu = new JMenu("Protein Disorder");
4062 // JAL-940 - only show secondary structure prediction services from
4063 // the legacy server
4064 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4066 Discoverer.services != null && (Discoverer.services.size() > 0))
4068 // TODO: refactor to allow list of AbstractName/Handler bindings to
4070 // stored or retrieved from elsewhere
4071 // No MSAWS used any more:
4072 // Vector msaws = null; // (Vector)
4073 // Discoverer.services.get("MsaWS");
4074 Vector secstrpr = (Vector) Discoverer.services
4076 if (secstrpr != null)
4078 // Add any secondary structure prediction services
4079 for (int i = 0, j = secstrpr.size(); i < j; i++)
4081 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4083 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4084 .getServiceClient(sh);
4085 int p = secstrmenu.getItemCount();
4086 impl.attachWSMenuEntry(secstrmenu, me);
4087 int q = secstrmenu.getItemCount();
4088 for (int litm = p; litm < q; litm++)
4090 legacyItems.add(secstrmenu.getItem(litm));
4096 // Add all submenus in the order they should appear on the web
4098 wsmenu.add(msawsmenu);
4099 wsmenu.add(secstrmenu);
4100 wsmenu.add(dismenu);
4101 wsmenu.add(analymenu);
4102 // No search services yet
4103 // wsmenu.add(seqsrchmenu);
4105 javax.swing.SwingUtilities.invokeLater(new Runnable()
4112 webService.removeAll();
4113 // first, add discovered services onto the webservices menu
4114 if (wsmenu.size() > 0)
4116 for (int i = 0, j = wsmenu.size(); i < j; i++)
4118 webService.add(wsmenu.get(i));
4123 webService.add(me.webServiceNoServices);
4125 // TODO: move into separate menu builder class.
4126 boolean new_sspred = false;
4127 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4129 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4130 if (jws2servs != null)
4132 if (jws2servs.hasServices())
4134 jws2servs.attachWSMenuEntry(webService, me);
4135 for (Jws2Instance sv : jws2servs.getServices())
4137 if (sv.description.toLowerCase().contains("jpred"))
4139 for (JMenuItem jmi : legacyItems)
4141 jmi.setVisible(false);
4147 if (jws2servs.isRunning())
4149 JMenuItem tm = new JMenuItem(
4150 "Still discovering JABA Services");
4151 tm.setEnabled(false);
4156 build_urlServiceMenu(me.webService);
4157 build_fetchdbmenu(webService);
4158 for (JMenu item : wsmenu)
4160 if (item.getItemCount() == 0)
4162 item.setEnabled(false);
4166 item.setEnabled(true);
4169 } catch (Exception e)
4172 .debug("Exception during web service menu building process.",
4177 } catch (Exception e)
4180 buildingMenu = false;
4187 * construct any groupURL type service menu entries.
4191 private void build_urlServiceMenu(JMenu webService)
4193 // TODO: remove this code when 2.7 is released
4194 // DEBUG - alignmentView
4196 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4197 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4199 * @Override public void actionPerformed(ActionEvent e) {
4200 * jalview.datamodel.AlignmentView
4201 * .testSelectionViews(af.viewport.getAlignment(),
4202 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4204 * }); webService.add(testAlView);
4206 // TODO: refactor to RestClient discoverer and merge menu entries for
4207 // rest-style services with other types of analysis/calculation service
4208 // SHmmr test client - still being implemented.
4209 // DEBUG - alignmentView
4211 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4214 client.attachWSMenuEntry(
4215 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4221 * Searches the alignment sequences for xRefs and builds the Show
4222 * Cross-References menu (formerly called Show Products), with database
4223 * sources for which cross-references are found (protein sources for a
4224 * nucleotide alignment and vice versa)
4226 * @return true if Show Cross-references menu should be enabled
4228 public boolean canShowProducts()
4230 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4231 AlignmentI dataset = viewport.getAlignment().getDataset();
4233 showProducts.removeAll();
4234 final boolean dna = viewport.getAlignment().isNucleotide();
4236 if (seqs == null || seqs.length == 0)
4238 // nothing to see here.
4242 boolean showp = false;
4245 List<String> ptypes = new CrossRef(seqs, dataset)
4246 .findXrefSourcesForSequences(dna);
4248 for (final String source : ptypes)
4251 final AlignFrame af = this;
4252 JMenuItem xtype = new JMenuItem(source);
4253 xtype.addActionListener(new ActionListener()
4256 public void actionPerformed(ActionEvent e)
4258 showProductsFor(af.viewport.getSequenceSelection(), dna, source);
4261 showProducts.add(xtype);
4263 showProducts.setVisible(showp);
4264 showProducts.setEnabled(showp);
4265 } catch (Exception e)
4268 .warn("canShowProducts threw an exception - please report to help@jalview.org",
4276 * Finds and displays cross-references for the selected sequences (protein
4277 * products for nucleotide sequences, dna coding sequences for peptides).
4280 * the sequences to show cross-references for
4282 * true if from a nucleotide alignment (so showing proteins)
4284 * the database to show cross-references for
4286 protected void showProductsFor(final SequenceI[] sel,
4287 final boolean _odna, final String source)
4289 new Thread(CrossRefAction.showProductsFor(sel, _odna, source, this))
4294 * Construct and display a new frame containing the translation of this
4295 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4298 public void showTranslation_actionPerformed(ActionEvent e)
4300 AlignmentI al = null;
4303 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4305 al = dna.translateCdna();
4306 } catch (Exception ex)
4308 jalview.bin.Cache.log.error(
4309 "Exception during translation. Please report this !", ex);
4310 final String msg = MessageManager
4311 .getString("label.error_when_translating_sequences_submit_bug_report");
4312 final String errorTitle = MessageManager
4313 .getString("label.implementation_error")
4314 + MessageManager.getString("label.translation_failed");
4315 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4316 JvOptionPane.ERROR_MESSAGE);
4319 if (al == null || al.getHeight() == 0)
4321 final String msg = MessageManager
4322 .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4323 final String errorTitle = MessageManager
4324 .getString("label.translation_failed");
4325 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4326 JvOptionPane.WARNING_MESSAGE);
4330 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4331 af.setFileFormat(this.currentFileFormat);
4332 final String newTitle = MessageManager.formatMessage(
4333 "label.translation_of_params",
4334 new Object[] { this.getTitle() });
4335 af.setTitle(newTitle);
4336 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4338 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4339 viewport.openSplitFrame(af, new Alignment(seqs));
4343 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4350 * Set the file format
4354 public void setFileFormat(FileFormatI format)
4356 this.currentFileFormat = format;
4360 * Try to load a features file onto the alignment.
4363 * contents or path to retrieve file
4365 * access mode of file (see jalview.io.AlignFile)
4366 * @return true if features file was parsed correctly.
4368 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4370 return avc.parseFeaturesFile(file, sourceType,
4371 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4376 public void refreshFeatureUI(boolean enableIfNecessary)
4378 // note - currently this is only still here rather than in the controller
4379 // because of the featureSettings hard reference that is yet to be
4381 if (enableIfNecessary)
4383 viewport.setShowSequenceFeatures(true);
4384 showSeqFeatures.setSelected(true);
4390 public void dragEnter(DropTargetDragEvent evt)
4395 public void dragExit(DropTargetEvent evt)
4400 public void dragOver(DropTargetDragEvent evt)
4405 public void dropActionChanged(DropTargetDragEvent evt)
4410 public void drop(DropTargetDropEvent evt)
4412 // JAL-1552 - acceptDrop required before getTransferable call for
4413 // Java's Transferable for native dnd
4414 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4415 Transferable t = evt.getTransferable();
4416 List<String> files = new ArrayList<>();
4417 List<DataSourceType> protocols = new ArrayList<>();
4421 Desktop.transferFromDropTarget(files, protocols, evt, t);
4422 } catch (Exception e)
4424 e.printStackTrace();
4430 // check to see if any of these files have names matching sequences in
4432 SequenceIdMatcher idm = new SequenceIdMatcher(viewport
4433 .getAlignment().getSequencesArray());
4435 * Object[] { String,SequenceI}
4437 ArrayList<Object[]> filesmatched = new ArrayList<>();
4438 ArrayList<String> filesnotmatched = new ArrayList<>();
4439 for (int i = 0; i < files.size(); i++)
4441 String file = files.get(i).toString();
4443 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4444 if (protocol == DataSourceType.FILE)
4446 File fl = new File(file);
4447 pdbfn = fl.getName();
4449 else if (protocol == DataSourceType.URL)
4451 URL url = new URL(file);
4452 pdbfn = url.getFile();
4454 if (pdbfn.length() > 0)
4456 // attempt to find a match in the alignment
4457 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4458 int l = 0, c = pdbfn.indexOf(".");
4459 while (mtch == null && c != -1)
4464 } while ((c = pdbfn.indexOf(".", l)) > l);
4467 pdbfn = pdbfn.substring(0, l);
4469 mtch = idm.findAllIdMatches(pdbfn);
4473 FileFormatI type = null;
4476 type = new IdentifyFile().identify(file, protocol);
4477 } catch (Exception ex)
4481 if (type != null && type.isStructureFile())
4483 filesmatched.add(new Object[] { file, protocol, mtch });
4487 // File wasn't named like one of the sequences or wasn't a PDB file.
4488 filesnotmatched.add(file);
4492 if (filesmatched.size() > 0)
4494 if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
4500 "label.automatically_associate_structure_files_with_sequences_same_name",
4501 new Object[] { Integer
4507 .getString("label.automatically_associate_structure_files_by_name"),
4508 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION)
4511 for (Object[] fm : filesmatched)
4513 // try and associate
4514 // TODO: may want to set a standard ID naming formalism for
4515 // associating PDB files which have no IDs.
4516 for (SequenceI toassoc : (SequenceI[]) fm[2])
4518 PDBEntry pe = new AssociatePdbFileWithSeq()
4519 .associatePdbWithSeq((String) fm[0],
4520 (DataSourceType) fm[1], toassoc, false,
4524 System.err.println("Associated file : "
4525 + ((String) fm[0]) + " with "
4526 + toassoc.getDisplayId(true));
4530 alignPanel.paintAlignment(true);
4534 if (filesnotmatched.size() > 0)
4537 && (Cache.getDefault(
4538 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JvOptionPane
4544 "label.ignore_unmatched_dropped_files_info",
4545 new Object[] { Integer
4552 .getString("label.ignore_unmatched_dropped_files"),
4553 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4557 for (String fn : filesnotmatched)
4559 loadJalviewDataFile(fn, null, null, null);
4563 } catch (Exception ex)
4565 ex.printStackTrace();
4571 * Attempt to load a "dropped" file or URL string, by testing in turn for
4573 * <li>an Annotation file</li>
4574 * <li>a JNet file</li>
4575 * <li>a features file</li>
4576 * <li>else try to interpret as an alignment file</li>
4580 * either a filename or a URL string.
4582 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4583 FileFormatI format, SequenceI assocSeq)
4587 if (sourceType == null)
4589 sourceType = FormatAdapter.checkProtocol(file);
4591 // if the file isn't identified, or not positively identified as some
4592 // other filetype (PFAM is default unidentified alignment file type) then
4593 // try to parse as annotation.
4594 boolean isAnnotation = (format == null || FileFormat.Pfam
4595 .equals(format)) ? new AnnotationFile()
4596 .annotateAlignmentView(viewport, file, sourceType) : false;
4600 // first see if its a T-COFFEE score file
4601 TCoffeeScoreFile tcf = null;
4604 tcf = new TCoffeeScoreFile(file, sourceType);
4607 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4610 changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
4611 isAnnotation = true;
4613 .setText(MessageManager
4614 .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
4618 // some problem - if no warning its probable that the ID matching
4619 // process didn't work
4623 tcf.getWarningMessage() == null ? MessageManager
4624 .getString("label.check_file_matches_sequence_ids_alignment")
4625 : tcf.getWarningMessage(),
4627 .getString("label.problem_reading_tcoffee_score_file"),
4628 JvOptionPane.WARNING_MESSAGE);
4635 } catch (Exception x)
4638 .debug("Exception when processing data source as T-COFFEE score file",
4644 // try to see if its a JNet 'concise' style annotation file *before*
4646 // try to parse it as a features file
4649 format = new IdentifyFile().identify(file, sourceType);
4651 if (FileFormat.ScoreMatrix == format)
4653 ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
4656 // todo: i18n this message
4658 .setText(MessageManager.formatMessage(
4659 "label.successfully_loaded_matrix",
4660 sm.getMatrixName()));
4662 else if (FileFormat.HMMER3.equals(format))
4664 HMMFile hmmFile = new HMMFile(new FileParse(file, sourceType)); // TODO
4671 HiddenMarkovModel hmm = hmmFile.getHMM();
4672 AlignmentAnnotation annotation = hmm.createAnnotation(
4673 getViewport().getAlignment().getWidth());
4674 getViewport().getAlignment().addAnnotation(annotation);
4675 annotation.setHMM(hmm);
4676 isAnnotation = true;
4679 else if (FileFormat.Jnet.equals(format))
4681 JPredFile predictions = new JPredFile(file, sourceType);
4682 new JnetAnnotationMaker();
4683 JnetAnnotationMaker.add_annotation(predictions,
4684 viewport.getAlignment(), 0, false);
4685 SequenceI repseq = viewport.getAlignment().getSequenceAt(0);
4686 viewport.getAlignment().setSeqrep(repseq);
4687 HiddenColumns cs = new HiddenColumns();
4688 cs.hideInsertionsFor(repseq);
4689 viewport.getAlignment().setHiddenColumns(cs);
4690 isAnnotation = true;
4692 // else if (IdentifyFile.FeaturesFile.equals(format))
4693 else if (FileFormat.Features.equals(format))
4695 if (parseFeaturesFile(file, sourceType))
4697 alignPanel.paintAlignment(true);
4702 new FileLoader().LoadFile(viewport, file, sourceType, format);
4709 alignPanel.adjustAnnotationHeight();
4710 viewport.updateSequenceIdColours();
4711 buildSortByAnnotationScoresMenu();
4712 alignPanel.paintAlignment(true);
4714 } catch (Exception ex)
4716 ex.printStackTrace();
4717 } catch (OutOfMemoryError oom)
4722 } catch (Exception x)
4727 + (sourceType != null ? (sourceType == DataSourceType.PASTE ? "from clipboard."
4728 : "using " + sourceType + " from " + file)
4730 + (format != null ? "(parsing as '" + format
4731 + "' file)" : ""), oom, Desktop.desktop);
4736 * Method invoked by the ChangeListener on the tabbed pane, in other words
4737 * when a different tabbed pane is selected by the user or programmatically.
4740 public void tabSelectionChanged(int index)
4744 alignPanel = alignPanels.get(index);
4745 viewport = alignPanel.av;
4746 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4747 setMenusFromViewport(viewport);
4751 * 'focus' any colour slider that is open to the selected viewport
4753 if (viewport.getConservationSelected())
4755 SliderPanel.setConservationSlider(alignPanel,
4756 viewport.getResidueShading(), alignPanel.getViewName());
4760 SliderPanel.hideConservationSlider();
4762 if (viewport.getAbovePIDThreshold())
4764 SliderPanel.setPIDSliderSource(alignPanel,
4765 viewport.getResidueShading(), alignPanel.getViewName());
4769 SliderPanel.hidePIDSlider();
4773 * If there is a frame linked to this one in a SplitPane, switch it to the
4774 * same view tab index. No infinite recursion of calls should happen, since
4775 * tabSelectionChanged() should not get invoked on setting the selected
4776 * index to an unchanged value. Guard against setting an invalid index
4777 * before the new view peer tab has been created.
4779 final AlignViewportI peer = viewport.getCodingComplement();
4782 AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
4783 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4785 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4791 * On right mouse click on view tab, prompt for and set new view name.
4794 public void tabbedPane_mousePressed(MouseEvent e)
4796 if (e.isPopupTrigger())
4798 String msg = MessageManager.getString("label.enter_view_name");
4799 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4800 JvOptionPane.QUESTION_MESSAGE);
4804 viewport.viewName = reply;
4805 // TODO warn if reply is in getExistingViewNames()?
4806 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4811 public AlignViewport getCurrentView()
4817 * Open the dialog for regex description parsing.
4820 protected void extractScores_actionPerformed(ActionEvent e)
4822 ParseProperties pp = new jalview.analysis.ParseProperties(
4823 viewport.getAlignment());
4824 // TODO: verify regex and introduce GUI dialog for version 2.5
4825 // if (pp.getScoresFromDescription("col", "score column ",
4826 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4828 if (pp.getScoresFromDescription("description column",
4829 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4831 buildSortByAnnotationScoresMenu();
4839 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4843 protected void showDbRefs_actionPerformed(ActionEvent e)
4845 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4851 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4855 protected void showNpFeats_actionPerformed(ActionEvent e)
4857 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4861 * find the viewport amongst the tabs in this alignment frame and close that
4866 public boolean closeView(AlignViewportI av)
4870 this.closeMenuItem_actionPerformed(false);
4873 Component[] comp = tabbedPane.getComponents();
4874 for (int i = 0; comp != null && i < comp.length; i++)
4876 if (comp[i] instanceof AlignmentPanel)
4878 if (((AlignmentPanel) comp[i]).av == av)
4881 closeView((AlignmentPanel) comp[i]);
4889 protected void build_fetchdbmenu(JMenu webService)
4891 // Temporary hack - DBRef Fetcher always top level ws entry.
4892 // TODO We probably want to store a sequence database checklist in
4893 // preferences and have checkboxes.. rather than individual sources selected
4895 final JMenu rfetch = new JMenu(
4896 MessageManager.getString("action.fetch_db_references"));
4897 rfetch.setToolTipText(MessageManager
4898 .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4899 webService.add(rfetch);
4901 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4902 MessageManager.getString("option.trim_retrieved_seqs"));
4903 trimrs.setToolTipText(MessageManager
4904 .getString("label.trim_retrieved_sequences"));
4905 trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
4906 trimrs.addActionListener(new ActionListener()
4909 public void actionPerformed(ActionEvent e)
4911 trimrs.setSelected(trimrs.isSelected());
4912 Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
4913 Boolean.valueOf(trimrs.isSelected()).toString());
4917 JMenuItem fetchr = new JMenuItem(
4918 MessageManager.getString("label.standard_databases"));
4919 fetchr.setToolTipText(MessageManager
4920 .getString("label.fetch_embl_uniprot"));
4921 fetchr.addActionListener(new ActionListener()
4925 public void actionPerformed(ActionEvent e)
4927 new Thread(new Runnable()
4932 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4933 .getAlignment().isNucleotide();
4934 DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
4935 .getSequenceSelection(), alignPanel.alignFrame, null,
4936 alignPanel.alignFrame.featureSettings, isNucleotide);
4937 dbRefFetcher.addListener(new FetchFinishedListenerI()
4940 public void finished()
4942 AlignFrame.this.setMenusForViewport();
4945 dbRefFetcher.fetchDBRefs(false);
4953 final AlignFrame me = this;
4954 new Thread(new Runnable()
4959 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4960 .getSequenceFetcherSingleton(me);
4961 javax.swing.SwingUtilities.invokeLater(new Runnable()
4966 String[] dbclasses = sf.getOrderedSupportedSources();
4967 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4968 // jalview.util.QuickSort.sort(otherdb, otherdb);
4969 List<DbSourceProxy> otherdb;
4970 JMenu dfetch = new JMenu();
4971 JMenu ifetch = new JMenu();
4972 JMenuItem fetchr = null;
4973 int comp = 0, icomp = 0, mcomp = 15;
4974 String mname = null;
4976 for (String dbclass : dbclasses)
4978 otherdb = sf.getSourceProxy(dbclass);
4979 // add a single entry for this class, or submenu allowing 'fetch
4981 if (otherdb == null || otherdb.size() < 1)
4985 // List<DbSourceProxy> dbs=otherdb;
4986 // otherdb=new ArrayList<DbSourceProxy>();
4987 // for (DbSourceProxy db:dbs)
4989 // if (!db.isA(DBRefSource.ALIGNMENTDB)
4993 mname = "From " + dbclass;
4995 if (otherdb.size() == 1)
4997 final DbSourceProxy[] dassource = otherdb
4998 .toArray(new DbSourceProxy[0]);
4999 DbSourceProxy src = otherdb.get(0);
5000 fetchr = new JMenuItem(src.getDbSource());
5001 fetchr.addActionListener(new ActionListener()
5005 public void actionPerformed(ActionEvent e)
5007 new Thread(new Runnable()
5013 boolean isNucleotide = alignPanel.alignFrame
5014 .getViewport().getAlignment()
5016 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5017 alignPanel.av.getSequenceSelection(),
5018 alignPanel.alignFrame, dassource,
5019 alignPanel.alignFrame.featureSettings,
5022 .addListener(new FetchFinishedListenerI()
5025 public void finished()
5027 AlignFrame.this.setMenusForViewport();
5030 dbRefFetcher.fetchDBRefs(false);
5036 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5037 MessageManager.formatMessage(
5038 "label.fetch_retrieve_from",
5039 new Object[] { src.getDbName() })));
5045 final DbSourceProxy[] dassource = otherdb
5046 .toArray(new DbSourceProxy[0]);
5048 DbSourceProxy src = otherdb.get(0);
5049 fetchr = new JMenuItem(MessageManager.formatMessage(
5050 "label.fetch_all_param",
5051 new Object[] { src.getDbSource() }));
5052 fetchr.addActionListener(new ActionListener()
5055 public void actionPerformed(ActionEvent e)
5057 new Thread(new Runnable()
5063 boolean isNucleotide = alignPanel.alignFrame
5064 .getViewport().getAlignment()
5066 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5067 alignPanel.av.getSequenceSelection(),
5068 alignPanel.alignFrame, dassource,
5069 alignPanel.alignFrame.featureSettings,
5072 .addListener(new FetchFinishedListenerI()
5075 public void finished()
5077 AlignFrame.this.setMenusForViewport();
5080 dbRefFetcher.fetchDBRefs(false);
5086 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5087 MessageManager.formatMessage(
5088 "label.fetch_retrieve_from_all_sources",
5090 Integer.valueOf(otherdb.size())
5091 .toString(), src.getDbSource(),
5092 src.getDbName() })));
5095 // and then build the rest of the individual menus
5096 ifetch = new JMenu(MessageManager.formatMessage(
5097 "label.source_from_db_source",
5098 new Object[] { src.getDbSource() }));
5100 String imname = null;
5102 for (DbSourceProxy sproxy : otherdb)
5104 String dbname = sproxy.getDbName();
5105 String sname = dbname.length() > 5 ? dbname.substring(0,
5106 5) + "..." : dbname;
5107 String msname = dbname.length() > 10 ? dbname.substring(
5108 0, 10) + "..." : dbname;
5111 imname = MessageManager.formatMessage(
5112 "label.from_msname", new Object[] { sname });
5114 fetchr = new JMenuItem(msname);
5115 final DbSourceProxy[] dassrc = { sproxy };
5116 fetchr.addActionListener(new ActionListener()
5120 public void actionPerformed(ActionEvent e)
5122 new Thread(new Runnable()
5128 boolean isNucleotide = alignPanel.alignFrame
5129 .getViewport().getAlignment()
5131 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5132 alignPanel.av.getSequenceSelection(),
5133 alignPanel.alignFrame, dassrc,
5134 alignPanel.alignFrame.featureSettings,
5137 .addListener(new FetchFinishedListenerI()
5140 public void finished()
5142 AlignFrame.this.setMenusForViewport();
5145 dbRefFetcher.fetchDBRefs(false);
5151 fetchr.setToolTipText("<html>"
5152 + MessageManager.formatMessage(
5153 "label.fetch_retrieve_from", new Object[]
5157 if (++icomp >= mcomp || i == (otherdb.size()))
5159 ifetch.setText(MessageManager.formatMessage(
5160 "label.source_to_target", imname, sname));
5162 ifetch = new JMenu();
5170 if (comp >= mcomp || dbi >= (dbclasses.length))
5172 dfetch.setText(MessageManager.formatMessage(
5173 "label.source_to_target", mname, dbclass));
5175 dfetch = new JMenu();
5188 * Left justify the whole alignment.
5191 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5193 AlignmentI al = viewport.getAlignment();
5195 viewport.firePropertyChange("alignment", null, al);
5199 * Right justify the whole alignment.
5202 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5204 AlignmentI al = viewport.getAlignment();
5206 viewport.firePropertyChange("alignment", null, al);
5210 public void setShowSeqFeatures(boolean b)
5212 showSeqFeatures.setSelected(b);
5213 viewport.setShowSequenceFeatures(b);
5220 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5221 * awt.event.ActionEvent)
5224 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5226 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5227 alignPanel.paintAlignment(true);
5234 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5238 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5240 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5241 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5249 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5250 * .event.ActionEvent)
5253 protected void showGroupConservation_actionPerformed(ActionEvent e)
5255 viewport.setShowGroupConservation(showGroupConservation.getState());
5256 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5263 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5264 * .event.ActionEvent)
5267 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5269 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5270 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5277 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5278 * .event.ActionEvent)
5281 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5283 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5284 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5288 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5290 showSequenceLogo.setState(true);
5291 viewport.setShowSequenceLogo(true);
5292 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5293 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5297 protected void showInformationHistogram_actionPerformed(ActionEvent e)
5299 viewport.setShowInformationHistogram(
5300 showInformationHistogram.getState());
5301 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5305 protected void showHMMSequenceLogo_actionPerformed(ActionEvent e)
5307 viewport.setShowHMMSequenceLogo(showHMMSequenceLogo.getState());
5308 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5312 protected void normaliseHMMSequenceLogo_actionPerformed(ActionEvent e)
5314 showHMMSequenceLogo.setState(true);
5315 viewport.setShowHMMSequenceLogo(true);
5316 viewport.setNormaliseHMMSequenceLogo(normaliseSequenceLogo.getState());
5317 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5321 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5323 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5330 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5331 * .event.ActionEvent)
5334 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5336 if (avc.makeGroupsFromSelection())
5338 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5339 alignPanel.updateAnnotation();
5340 alignPanel.paintAlignment(true);
5344 public void clearAlignmentSeqRep()
5346 // TODO refactor alignmentseqrep to controller
5347 if (viewport.getAlignment().hasSeqrep())
5349 viewport.getAlignment().setSeqrep(null);
5350 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5351 alignPanel.updateAnnotation();
5352 alignPanel.paintAlignment(true);
5357 protected void createGroup_actionPerformed(ActionEvent e)
5359 if (avc.createGroup())
5361 alignPanel.alignmentChanged();
5366 protected void unGroup_actionPerformed(ActionEvent e)
5370 alignPanel.alignmentChanged();
5375 * make the given alignmentPanel the currently selected tab
5377 * @param alignmentPanel
5379 public void setDisplayedView(AlignmentPanel alignmentPanel)
5381 if (!viewport.getSequenceSetId().equals(
5382 alignmentPanel.av.getSequenceSetId()))
5386 .getString("error.implementation_error_cannot_show_view_alignment_frame"));
5388 if (tabbedPane != null
5389 && tabbedPane.getTabCount() > 0
5390 && alignPanels.indexOf(alignmentPanel) != tabbedPane
5391 .getSelectedIndex())
5393 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5398 * Action on selection of menu options to Show or Hide annotations.
5401 * @param forSequences
5402 * update sequence-related annotations
5403 * @param forAlignment
5404 * update non-sequence-related annotations
5407 protected void setAnnotationsVisibility(boolean visible,
5408 boolean forSequences, boolean forAlignment)
5410 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5411 .getAlignmentAnnotation();
5416 for (AlignmentAnnotation aa : anns)
5419 * don't display non-positional annotations on an alignment
5421 if (aa.annotations == null)
5425 boolean apply = (aa.sequenceRef == null && forAlignment)
5426 || (aa.sequenceRef != null && forSequences);
5429 aa.visible = visible;
5432 alignPanel.validateAnnotationDimensions(true);
5433 alignPanel.alignmentChanged();
5437 * Store selected annotation sort order for the view and repaint.
5440 protected void sortAnnotations_actionPerformed()
5442 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5444 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5445 alignPanel.paintAlignment(true);
5450 * @return alignment panels in this alignment frame
5452 public List<? extends AlignmentViewPanel> getAlignPanels()
5454 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5458 * Open a new alignment window, with the cDNA associated with this (protein)
5459 * alignment, aligned as is the protein.
5461 protected void viewAsCdna_actionPerformed()
5463 // TODO no longer a menu action - refactor as required
5464 final AlignmentI alignment = getViewport().getAlignment();
5465 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5466 if (mappings == null)
5470 List<SequenceI> cdnaSeqs = new ArrayList<>();
5471 for (SequenceI aaSeq : alignment.getSequences())
5473 for (AlignedCodonFrame acf : mappings)
5475 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5479 * There is a cDNA mapping for this protein sequence - add to new
5480 * alignment. It will share the same dataset sequence as other mapped
5481 * cDNA (no new mappings need to be created).
5483 final Sequence newSeq = new Sequence(dnaSeq);
5484 newSeq.setDatasetSequence(dnaSeq);
5485 cdnaSeqs.add(newSeq);
5489 if (cdnaSeqs.size() == 0)
5491 // show a warning dialog no mapped cDNA
5494 AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5496 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5497 AlignFrame.DEFAULT_HEIGHT);
5498 cdna.alignAs(alignment);
5499 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5501 Desktop.addInternalFrame(alignFrame, newtitle,
5502 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
5506 * Set visibility of dna/protein complement view (available when shown in a
5512 protected void showComplement_actionPerformed(boolean show)
5514 SplitContainerI sf = getSplitViewContainer();
5517 sf.setComplementVisible(this, show);
5522 * Generate the reverse (optionally complemented) of the selected sequences,
5523 * and add them to the alignment
5526 protected void showReverse_actionPerformed(boolean complement)
5528 AlignmentI al = null;
5531 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5532 al = dna.reverseCdna(complement);
5533 viewport.addAlignment(al, "");
5534 addHistoryItem(new EditCommand(
5535 MessageManager.getString("label.add_sequences"),
5536 Action.PASTE, al.getSequencesArray(), 0, al.getWidth(),
5537 viewport.getAlignment()));
5538 } catch (Exception ex)
5540 System.err.println(ex.getMessage());
5546 * Try to run a script in the Groovy console, having first ensured that this
5547 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5548 * be targeted at this alignment.
5551 protected void runGroovy_actionPerformed()
5553 Jalview.setCurrentAlignFrame(this);
5554 groovy.ui.Console console = Desktop.getGroovyConsole();
5555 if (console != null)
5559 console.runScript();
5560 } catch (Exception ex)
5562 System.err.println((ex.toString()));
5564 .showInternalMessageDialog(Desktop.desktop, MessageManager
5565 .getString("label.couldnt_run_groovy_script"),
5567 .getString("label.groovy_support_failed"),
5568 JvOptionPane.ERROR_MESSAGE);
5573 System.err.println("Can't run Groovy script as console not found");
5578 * Hides columns containing (or not containing) a specified feature, provided
5579 * that would not leave all columns hidden
5581 * @param featureType
5582 * @param columnsContaining
5585 public boolean hideFeatureColumns(String featureType,
5586 boolean columnsContaining)
5588 boolean notForHiding = avc.markColumnsContainingFeatures(
5589 columnsContaining, false, false, featureType);
5592 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5593 false, featureType))
5595 getViewport().hideSelectedColumns();
5603 protected void selectHighlightedColumns_actionPerformed(
5604 ActionEvent actionEvent)
5606 // include key modifier check in case user selects from menu
5607 avc.markHighlightedColumns(
5608 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0,
5610 (actionEvent.getModifiers() & (ActionEvent.META_MASK | ActionEvent.CTRL_MASK)) != 0);
5614 * Rebuilds the Colour menu, including any user-defined colours which have
5615 * been loaded either on startup or during the session
5617 public void buildColourMenu()
5619 colourMenu.removeAll();
5621 colourMenu.add(applyToAllGroups);
5622 colourMenu.add(textColour);
5623 colourMenu.addSeparator();
5625 ColourMenuHelper.addMenuItems(colourMenu, this,
5626 viewport.getAlignment(), false);
5628 colourMenu.addSeparator();
5629 colourMenu.add(conservationMenuItem);
5630 colourMenu.add(modifyConservation);
5631 colourMenu.add(abovePIDThreshold);
5632 colourMenu.add(modifyPID);
5633 colourMenu.add(annotationColour);
5635 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5636 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5640 * Open a dialog (if not already open) that allows the user to select and
5641 * calculate PCA or Tree analysis
5643 protected void openTreePcaDialog()
5645 if (alignPanel.getCalculationDialog() == null)
5647 new CalculationChooser(AlignFrame.this);
5652 class PrintThread extends Thread
5656 public PrintThread(AlignmentPanel ap)
5661 static PageFormat pf;
5666 PrinterJob printJob = PrinterJob.getPrinterJob();
5670 printJob.setPrintable(ap, pf);
5674 printJob.setPrintable(ap);
5677 if (printJob.printDialog())
5682 } catch (Exception PrintException)
5684 PrintException.printStackTrace();