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.GeneticCodeI;
28 import jalview.analysis.ParseProperties;
29 import jalview.analysis.SequenceIdMatcher;
30 import jalview.api.AlignExportSettingI;
31 import jalview.api.AlignViewControllerGuiI;
32 import jalview.api.AlignViewControllerI;
33 import jalview.api.AlignViewportI;
34 import jalview.api.AlignmentViewPanel;
35 import jalview.api.FeatureSettingsControllerI;
36 import jalview.api.SplitContainerI;
37 import jalview.api.ViewStyleI;
38 import jalview.api.analysis.SimilarityParamsI;
39 import jalview.bin.Cache;
40 import jalview.bin.Jalview;
41 import jalview.commands.CommandI;
42 import jalview.commands.EditCommand;
43 import jalview.commands.EditCommand.Action;
44 import jalview.commands.OrderCommand;
45 import jalview.commands.RemoveGapColCommand;
46 import jalview.commands.RemoveGapsCommand;
47 import jalview.commands.SlideSequencesCommand;
48 import jalview.commands.TrimRegionCommand;
49 import jalview.datamodel.AlignedCodonFrame;
50 import jalview.datamodel.Alignment;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentExportData;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.AlignmentOrder;
55 import jalview.datamodel.AlignmentView;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
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.BackupFiles;
69 import jalview.io.BioJsHTMLOutput;
70 import jalview.io.DataSourceType;
71 import jalview.io.FileFormat;
72 import jalview.io.FileFormatI;
73 import jalview.io.FileFormats;
74 import jalview.io.FileLoader;
75 import jalview.io.FileParse;
76 import jalview.io.FormatAdapter;
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.io.vcf.VCFLoader;
87 import jalview.jbgui.GAlignFrame;
88 import jalview.schemes.ColourSchemeI;
89 import jalview.schemes.ColourSchemes;
90 import jalview.schemes.ResidueColourScheme;
91 import jalview.schemes.TCoffeeColourScheme;
92 import jalview.util.MessageManager;
93 import jalview.viewmodel.AlignmentViewport;
94 import jalview.viewmodel.ViewportRanges;
95 import jalview.ws.DBRefFetcher;
96 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
97 import jalview.ws.jws1.Discoverer;
98 import jalview.ws.jws2.Jws2Discoverer;
99 import jalview.ws.jws2.jabaws2.Jws2Instance;
100 import jalview.ws.seqfetcher.DbSourceProxy;
102 import java.awt.BorderLayout;
103 import java.awt.Component;
104 import java.awt.Rectangle;
105 import java.awt.Toolkit;
106 import java.awt.datatransfer.Clipboard;
107 import java.awt.datatransfer.DataFlavor;
108 import java.awt.datatransfer.StringSelection;
109 import java.awt.datatransfer.Transferable;
110 import java.awt.dnd.DnDConstants;
111 import java.awt.dnd.DropTargetDragEvent;
112 import java.awt.dnd.DropTargetDropEvent;
113 import java.awt.dnd.DropTargetEvent;
114 import java.awt.dnd.DropTargetListener;
115 import java.awt.event.ActionEvent;
116 import java.awt.event.ActionListener;
117 import java.awt.event.FocusAdapter;
118 import java.awt.event.FocusEvent;
119 import java.awt.event.ItemEvent;
120 import java.awt.event.ItemListener;
121 import java.awt.event.KeyAdapter;
122 import java.awt.event.KeyEvent;
123 import java.awt.event.MouseEvent;
124 import java.awt.print.PageFormat;
125 import java.awt.print.PrinterJob;
126 import java.beans.PropertyChangeEvent;
128 import java.io.FileWriter;
129 import java.io.PrintWriter;
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Deque;
134 import java.util.Enumeration;
135 import java.util.Hashtable;
136 import java.util.List;
137 import java.util.Vector;
139 import javax.swing.ButtonGroup;
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 public static final int DEFAULT_WIDTH = 700;
161 public static final int DEFAULT_HEIGHT = 500;
164 * The currently displayed panel (selected tabbed view if more than one)
166 public AlignmentPanel alignPanel;
168 AlignViewport viewport;
170 public AlignViewControllerI avc;
172 List<AlignmentPanel> alignPanels = new ArrayList<>();
175 * Last format used to load or save alignments in this window
177 FileFormatI currentFileFormat = null;
180 * Current filename for this alignment
182 String fileName = null;
185 * Creates a new AlignFrame object with specific width and height.
191 public AlignFrame(AlignmentI al, int width, int height)
193 this(al, null, width, height);
197 * Creates a new AlignFrame object with specific width, height and
203 * @param sequenceSetId
205 public AlignFrame(AlignmentI al, int width, int height,
206 String sequenceSetId)
208 this(al, null, width, height, sequenceSetId);
212 * Creates a new AlignFrame object with specific width, height and
218 * @param sequenceSetId
221 public AlignFrame(AlignmentI al, int width, int height,
222 String sequenceSetId, String viewId)
224 this(al, null, width, height, sequenceSetId, viewId);
228 * new alignment window with hidden columns
232 * @param hiddenColumns
233 * ColumnSelection or null
235 * Width of alignment frame
239 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
242 this(al, hiddenColumns, width, height, null);
246 * Create alignment frame for al with hiddenColumns, a specific width and
247 * height, and specific sequenceId
250 * @param hiddenColumns
253 * @param sequenceSetId
256 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
257 int height, String sequenceSetId)
259 this(al, hiddenColumns, width, height, sequenceSetId, null);
263 * Create alignment frame for al with hiddenColumns, a specific width and
264 * height, and specific sequenceId
267 * @param hiddenColumns
270 * @param sequenceSetId
275 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
276 int height, String sequenceSetId, String viewId)
278 setSize(width, height);
280 if (al.getDataset() == null)
285 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
287 alignPanel = new AlignmentPanel(this, viewport);
289 addAlignmentPanel(alignPanel, true);
293 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
294 HiddenColumns hiddenColumns, int width, int height)
296 setSize(width, height);
298 if (al.getDataset() == null)
303 viewport = new AlignViewport(al, hiddenColumns);
305 if (hiddenSeqs != null && hiddenSeqs.length > 0)
307 viewport.hideSequence(hiddenSeqs);
309 alignPanel = new AlignmentPanel(this, viewport);
310 addAlignmentPanel(alignPanel, true);
315 * Make a new AlignFrame from existing alignmentPanels
322 public AlignFrame(AlignmentPanel ap)
326 addAlignmentPanel(ap, false);
331 * initalise the alignframe from the underlying viewport data and the
336 if (!Jalview.isHeadlessMode())
338 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
341 avc = new jalview.controller.AlignViewController(this, viewport,
343 if (viewport.getAlignmentConservationAnnotation() == null)
345 // BLOSUM62Colour.setEnabled(false);
346 conservationMenuItem.setEnabled(false);
347 modifyConservation.setEnabled(false);
348 // PIDColour.setEnabled(false);
349 // abovePIDThreshold.setEnabled(false);
350 // modifyPID.setEnabled(false);
353 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
356 if (sortby.equals("Id"))
358 sortIDMenuItem_actionPerformed(null);
360 else if (sortby.equals("Pairwise Identity"))
362 sortPairwiseMenuItem_actionPerformed(null);
366 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
368 setMenusFromViewport(viewport);
369 buildSortByAnnotationScoresMenu();
370 calculateTree.addActionListener(new ActionListener()
374 public void actionPerformed(ActionEvent e)
381 if (Desktop.desktop != null)
383 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
384 addServiceListeners();
388 if (viewport.getWrapAlignment())
390 wrapMenuItem_actionPerformed(null);
393 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
395 this.overviewMenuItem_actionPerformed(null);
400 final List<AlignmentPanel> selviews = new ArrayList<>();
401 final List<AlignmentPanel> origview = new ArrayList<>();
402 final String menuLabel = MessageManager
403 .getString("label.copy_format_from");
404 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
405 new ViewSetProvider()
409 public AlignmentPanel[] getAllAlignmentPanels()
412 origview.add(alignPanel);
413 // make an array of all alignment panels except for this one
414 List<AlignmentPanel> aps = new ArrayList<>(
415 Arrays.asList(Desktop.getAlignmentPanels(null)));
416 aps.remove(AlignFrame.this.alignPanel);
417 return aps.toArray(new AlignmentPanel[aps.size()]);
419 }, selviews, new ItemListener()
423 public void itemStateChanged(ItemEvent e)
425 if (origview.size() > 0)
427 final AlignmentPanel ap = origview.get(0);
430 * Copy the ViewStyle of the selected panel to 'this one'.
431 * Don't change value of 'scaleProteinAsCdna' unless copying
434 ViewStyleI vs = selviews.get(0).getAlignViewport()
436 boolean fromSplitFrame = selviews.get(0)
437 .getAlignViewport().getCodingComplement() != null;
440 vs.setScaleProteinAsCdna(ap.getAlignViewport()
441 .getViewStyle().isScaleProteinAsCdna());
443 ap.getAlignViewport().setViewStyle(vs);
446 * Also rescale ViewStyle of SplitFrame complement if there is
447 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
448 * the whole ViewStyle (allow cDNA protein to have different
451 AlignViewportI complement = ap.getAlignViewport()
452 .getCodingComplement();
453 if (complement != null && vs.isScaleProteinAsCdna())
455 AlignFrame af = Desktop.getAlignFrameFor(complement);
456 ((SplitFrame) af.getSplitViewContainer())
458 af.setMenusForViewport();
462 ap.setSelected(true);
463 ap.alignFrame.setMenusForViewport();
468 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
469 .indexOf("devel") > -1
470 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
471 .indexOf("test") > -1)
473 formatMenu.add(vsel);
475 addFocusListener(new FocusAdapter()
478 public void focusGained(FocusEvent e)
480 Jalview.setCurrentAlignFrame(AlignFrame.this);
487 * Change the filename and format for the alignment, and enable the 'reload'
488 * button functionality.
495 public void setFileName(String file, FileFormatI format)
498 setFileFormat(format);
499 reload.setEnabled(true);
503 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
506 void addKeyListener()
508 addKeyListener(new KeyAdapter()
511 public void keyPressed(KeyEvent evt)
513 if (viewport.cursorMode
514 && ((evt.getKeyCode() >= KeyEvent.VK_0
515 && evt.getKeyCode() <= KeyEvent.VK_9)
516 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
517 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
518 && Character.isDigit(evt.getKeyChar()))
520 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
523 switch (evt.getKeyCode())
526 case 27: // escape key
527 deselectAllSequenceMenuItem_actionPerformed(null);
531 case KeyEvent.VK_DOWN:
532 if (evt.isAltDown() || !viewport.cursorMode)
534 moveSelectedSequences(false);
536 if (viewport.cursorMode)
538 alignPanel.getSeqPanel().moveCursor(0, 1);
543 if (evt.isAltDown() || !viewport.cursorMode)
545 moveSelectedSequences(true);
547 if (viewport.cursorMode)
549 alignPanel.getSeqPanel().moveCursor(0, -1);
554 case KeyEvent.VK_LEFT:
555 if (evt.isAltDown() || !viewport.cursorMode)
557 slideSequences(false,
558 alignPanel.getSeqPanel().getKeyboardNo1());
562 alignPanel.getSeqPanel().moveCursor(-1, 0);
567 case KeyEvent.VK_RIGHT:
568 if (evt.isAltDown() || !viewport.cursorMode)
570 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
574 alignPanel.getSeqPanel().moveCursor(1, 0);
578 case KeyEvent.VK_SPACE:
579 if (viewport.cursorMode)
581 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
582 || evt.isShiftDown() || evt.isAltDown());
586 // case KeyEvent.VK_A:
587 // if (viewport.cursorMode)
589 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
590 // //System.out.println("A");
594 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
595 * System.out.println("closing bracket"); } break;
597 case KeyEvent.VK_DELETE:
598 case KeyEvent.VK_BACK_SPACE:
599 if (!viewport.cursorMode)
601 cut_actionPerformed(null);
605 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
606 || evt.isShiftDown() || evt.isAltDown());
612 if (viewport.cursorMode)
614 alignPanel.getSeqPanel().setCursorRow();
618 if (viewport.cursorMode && !evt.isControlDown())
620 alignPanel.getSeqPanel().setCursorColumn();
624 if (viewport.cursorMode)
626 alignPanel.getSeqPanel().setCursorPosition();
630 case KeyEvent.VK_ENTER:
631 case KeyEvent.VK_COMMA:
632 if (viewport.cursorMode)
634 alignPanel.getSeqPanel().setCursorRowAndColumn();
639 if (viewport.cursorMode)
641 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
645 if (viewport.cursorMode)
647 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
652 viewport.cursorMode = !viewport.cursorMode;
653 statusBar.setText(MessageManager
654 .formatMessage("label.keyboard_editing_mode", new String[]
655 { (viewport.cursorMode ? "on" : "off") }));
656 if (viewport.cursorMode)
658 ViewportRanges ranges = viewport.getRanges();
659 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
661 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
664 alignPanel.getSeqPanel().seqCanvas.repaint();
670 Help.showHelpWindow();
671 } catch (Exception ex)
673 ex.printStackTrace();
678 boolean toggleSeqs = !evt.isControlDown();
679 boolean toggleCols = !evt.isShiftDown();
680 toggleHiddenRegions(toggleSeqs, toggleCols);
685 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
686 boolean modifyExisting = true; // always modify, don't clear
687 // evt.isShiftDown();
688 boolean invertHighlighted = evt.isAltDown();
689 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
693 case KeyEvent.VK_PAGE_UP:
694 viewport.getRanges().pageUp();
696 case KeyEvent.VK_PAGE_DOWN:
697 viewport.getRanges().pageDown();
703 public void keyReleased(KeyEvent evt)
705 switch (evt.getKeyCode())
707 case KeyEvent.VK_LEFT:
708 if (evt.isAltDown() || !viewport.cursorMode)
710 viewport.firePropertyChange("alignment", null,
711 viewport.getAlignment().getSequences());
715 case KeyEvent.VK_RIGHT:
716 if (evt.isAltDown() || !viewport.cursorMode)
718 viewport.firePropertyChange("alignment", null,
719 viewport.getAlignment().getSequences());
727 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
729 ap.alignFrame = this;
730 avc = new jalview.controller.AlignViewController(this, viewport,
735 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
737 int aSize = alignPanels.size();
739 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
741 if (aSize == 1 && ap.av.getViewName() == null)
743 this.getContentPane().add(ap, BorderLayout.CENTER);
749 setInitialTabVisible();
752 expandViews.setEnabled(true);
753 gatherViews.setEnabled(true);
754 tabbedPane.addTab(ap.av.getViewName(), ap);
756 ap.setVisible(false);
761 if (ap.av.isPadGaps())
763 ap.av.getAlignment().padGaps();
765 ap.av.updateConservation(ap);
766 ap.av.updateConsensus(ap);
767 ap.av.updateStrucConsensus(ap);
771 public void setInitialTabVisible()
773 expandViews.setEnabled(true);
774 gatherViews.setEnabled(true);
775 tabbedPane.setVisible(true);
776 AlignmentPanel first = alignPanels.get(0);
777 tabbedPane.addTab(first.av.getViewName(), first);
778 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
781 public AlignViewport getViewport()
786 /* Set up intrinsic listeners for dynamically generated GUI bits. */
787 private void addServiceListeners()
789 final java.beans.PropertyChangeListener thisListener;
790 Desktop.instance.addJalviewPropertyChangeListener("services",
791 thisListener = new java.beans.PropertyChangeListener()
794 public void propertyChange(PropertyChangeEvent evt)
796 // // System.out.println("Discoverer property change.");
797 // if (evt.getPropertyName().equals("services"))
799 SwingUtilities.invokeLater(new Runnable()
806 "Rebuild WS Menu for service change");
807 BuildWebServiceMenu();
814 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
817 public void internalFrameClosed(
818 javax.swing.event.InternalFrameEvent evt)
820 // System.out.println("deregistering discoverer listener");
821 Desktop.instance.removeJalviewPropertyChangeListener("services",
823 closeMenuItem_actionPerformed(true);
826 // Finally, build the menu once to get current service state
827 new Thread(new Runnable()
832 BuildWebServiceMenu();
838 * Configure menu items that vary according to whether the alignment is
839 * nucleotide or protein
841 public void setGUINucleotide()
843 AlignmentI al = getViewport().getAlignment();
844 boolean nucleotide = al.isNucleotide();
846 loadVcf.setVisible(nucleotide);
847 showTranslation.setVisible(nucleotide);
848 showReverse.setVisible(nucleotide);
849 showReverseComplement.setVisible(nucleotide);
850 conservationMenuItem.setEnabled(!nucleotide);
852 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
853 showGroupConservation.setEnabled(!nucleotide);
855 showComplementMenuItem
856 .setText(nucleotide ? MessageManager.getString("label.protein")
857 : MessageManager.getString("label.nucleotide"));
861 * set up menus for the current viewport. This may be called after any
862 * operation that affects the data in the current view (selection changed,
863 * etc) to update the menus to reflect the new state.
866 public void setMenusForViewport()
868 setMenusFromViewport(viewport);
872 * Need to call this method when tabs are selected for multiple views, or when
873 * loading from Jalview2XML.java
878 public void setMenusFromViewport(AlignViewport av)
880 padGapsMenuitem.setSelected(av.isPadGaps());
881 colourTextMenuItem.setSelected(av.isShowColourText());
882 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
883 modifyPID.setEnabled(abovePIDThreshold.isSelected());
884 conservationMenuItem.setSelected(av.getConservationSelected());
885 modifyConservation.setEnabled(conservationMenuItem.isSelected());
886 seqLimits.setSelected(av.getShowJVSuffix());
887 idRightAlign.setSelected(av.isRightAlignIds());
888 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
889 renderGapsMenuItem.setSelected(av.isRenderGaps());
890 wrapMenuItem.setSelected(av.getWrapAlignment());
891 scaleAbove.setVisible(av.getWrapAlignment());
892 scaleLeft.setVisible(av.getWrapAlignment());
893 scaleRight.setVisible(av.getWrapAlignment());
894 annotationPanelMenuItem.setState(av.isShowAnnotation());
896 * Show/hide annotations only enabled if annotation panel is shown
898 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
899 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
900 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
901 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
902 viewBoxesMenuItem.setSelected(av.getShowBoxes());
903 viewTextMenuItem.setSelected(av.getShowText());
904 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
905 showGroupConsensus.setSelected(av.isShowGroupConsensus());
906 showGroupConservation.setSelected(av.isShowGroupConservation());
907 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
908 showSequenceLogo.setSelected(av.isShowSequenceLogo());
909 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
911 ColourMenuHelper.setColourSelected(colourMenu,
912 av.getGlobalColourScheme());
914 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
915 hiddenMarkers.setState(av.getShowHiddenMarkers());
916 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
917 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
918 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
919 autoCalculate.setSelected(av.autoCalculateConsensus);
920 sortByTree.setSelected(av.sortByTree);
921 listenToViewSelections.setSelected(av.followSelection);
923 showProducts.setEnabled(canShowProducts());
924 setGroovyEnabled(Desktop.getGroovyConsole() != null);
930 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
934 public void setGroovyEnabled(boolean b)
936 runGroovy.setEnabled(b);
939 private IProgressIndicator progressBar;
944 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
947 public void setProgressBar(String message, long id)
949 progressBar.setProgressBar(message, id);
953 public void registerHandler(final long id,
954 final IProgressIndicatorHandler handler)
956 progressBar.registerHandler(id, handler);
961 * @return true if any progress bars are still active
964 public boolean operationInProgress()
966 return progressBar.operationInProgress();
970 * Sets the text of the status bar. Note that setting a null or empty value
971 * will cause the status bar to be hidden, with possibly undesirable flicker
972 * of the screen layout.
975 public void setStatus(String text)
977 statusBar.setText(text);
981 * Added so Castor Mapping file can obtain Jalview Version
983 public String getVersion()
985 return jalview.bin.Cache.getProperty("VERSION");
988 public FeatureRenderer getFeatureRenderer()
990 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
994 public void fetchSequence_actionPerformed(ActionEvent e)
996 new jalview.gui.SequenceFetcher(this);
1000 public void addFromFile_actionPerformed(ActionEvent e)
1002 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1006 public void reload_actionPerformed(ActionEvent e)
1008 if (fileName != null)
1010 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1011 // originating file's format
1012 // TODO: work out how to recover feature settings for correct view(s) when
1013 // file is reloaded.
1014 if (FileFormat.Jalview.equals(currentFileFormat))
1016 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1017 for (int i = 0; i < frames.length; i++)
1019 if (frames[i] instanceof AlignFrame && frames[i] != this
1020 && ((AlignFrame) frames[i]).fileName != null
1021 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1025 frames[i].setSelected(true);
1026 Desktop.instance.closeAssociatedWindows();
1027 } catch (java.beans.PropertyVetoException ex)
1033 Desktop.instance.closeAssociatedWindows();
1035 FileLoader loader = new FileLoader();
1036 DataSourceType protocol = fileName.startsWith("http:")
1037 ? DataSourceType.URL
1038 : DataSourceType.FILE;
1039 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1043 Rectangle bounds = this.getBounds();
1045 FileLoader loader = new FileLoader();
1046 DataSourceType protocol = fileName.startsWith("http:")
1047 ? DataSourceType.URL
1048 : DataSourceType.FILE;
1049 AlignFrame newframe = loader.LoadFileWaitTillLoaded(fileName,
1050 protocol, currentFileFormat);
1052 newframe.setBounds(bounds);
1053 if (featureSettings != null && featureSettings.isShowing())
1055 final Rectangle fspos = featureSettings.frame.getBounds();
1056 // TODO: need a 'show feature settings' function that takes bounds -
1057 // need to refactor Desktop.addFrame
1058 newframe.featureSettings_actionPerformed(null);
1059 final FeatureSettings nfs = newframe.featureSettings;
1060 SwingUtilities.invokeLater(new Runnable()
1065 nfs.frame.setBounds(fspos);
1068 this.featureSettings.close();
1069 this.featureSettings = null;
1071 this.closeMenuItem_actionPerformed(true);
1077 public void addFromText_actionPerformed(ActionEvent e)
1080 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1084 public void addFromURL_actionPerformed(ActionEvent e)
1086 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1090 public void save_actionPerformed(ActionEvent e)
1092 if (fileName == null || (currentFileFormat == null)
1093 || fileName.startsWith("http"))
1095 saveAs_actionPerformed(null);
1099 saveAlignment(fileName, currentFileFormat);
1110 public void saveAs_actionPerformed(ActionEvent e)
1112 String format = currentFileFormat == null ? null
1113 : currentFileFormat.getName();
1114 JalviewFileChooser chooser = JalviewFileChooser
1115 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1117 chooser.setFileView(new JalviewFileView());
1118 chooser.setDialogTitle(
1119 MessageManager.getString("label.save_alignment_to_file"));
1120 chooser.setToolTipText(MessageManager.getString("action.save"));
1122 int value = chooser.showSaveDialog(this);
1124 if (value == JalviewFileChooser.APPROVE_OPTION)
1126 currentFileFormat = chooser.getSelectedFormat();
1127 while (currentFileFormat == null)
1129 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1130 MessageManager.getString(
1131 "label.select_file_format_before_saving"),
1132 MessageManager.getString("label.file_format_not_specified"),
1133 JvOptionPane.WARNING_MESSAGE);
1134 currentFileFormat = chooser.getSelectedFormat();
1135 value = chooser.showSaveDialog(this);
1136 if (value != JalviewFileChooser.APPROVE_OPTION)
1142 fileName = chooser.getSelectedFile().getPath();
1144 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1146 Cache.setProperty("LAST_DIRECTORY", fileName);
1147 saveAlignment(fileName, currentFileFormat);
1151 public boolean saveAlignment(String file, FileFormatI format)
1153 boolean success = true;
1155 if (FileFormat.Jalview.equals(format))
1157 String shortName = title;
1159 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1161 shortName = shortName.substring(
1162 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1165 success = new jalview.project.Jalview2XML().saveAlignment(this, file,
1168 statusBar.setText(MessageManager.formatMessage(
1169 "label.successfully_saved_to_file_in_format", new Object[]
1170 { fileName, format }));
1175 AlignmentExportData exportData = getAlignmentForExport(format,
1177 if (exportData.getSettings().isCancelled())
1181 FormatAdapter f = new FormatAdapter(alignPanel,
1182 exportData.getSettings());
1183 String output = f.formatSequences(format, exportData.getAlignment(), // class
1187 // occur in the distant future
1188 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1189 f.getCacheSuffixDefault(format),
1190 viewport.getAlignment().getHiddenColumns());
1198 // create backupfiles object and get new temp filename destination
1199 BackupFiles backupfiles = new BackupFiles(file);
1203 PrintWriter out = new PrintWriter(
1204 new FileWriter(backupfiles.getTempFilePath()));
1206 // TESTING code here
1207 boolean TESTING = true;
1210 out.print("; TESTSTART\n");
1212 for (int i = 0; i < count; i++)
1214 // Thread.sleep(1000);
1215 out.println("; TEST: " + (count - 1 - i));
1221 out.print("; TESTEND\n");
1224 this.setTitle(file);
1225 statusBar.setText(MessageManager.formatMessage(
1226 "label.successfully_saved_to_file_in_format", new Object[]
1227 { fileName, format.getName() }));
1228 } catch (Exception ex)
1231 ex.printStackTrace();
1234 backupfiles.setWriteSuccess(success);
1235 // do the backup file roll and rename the temp file to actual file
1236 success = backupfiles.rollBackupsAndRenameTempFile();
1243 JvOptionPane.showInternalMessageDialog(this, MessageManager
1244 .formatMessage("label.couldnt_save_file", new Object[]
1246 MessageManager.getString("label.error_saving_file"),
1247 JvOptionPane.WARNING_MESSAGE);
1253 private void warningMessage(String warning, String title)
1255 if (new jalview.util.Platform().isHeadless())
1257 System.err.println("Warning: " + title + "\nWarning: " + warning);
1262 JvOptionPane.showInternalMessageDialog(this, warning, title,
1263 JvOptionPane.WARNING_MESSAGE);
1275 protected void outputText_actionPerformed(ActionEvent e)
1277 FileFormatI fileFormat = FileFormats.getInstance()
1278 .forName(e.getActionCommand());
1279 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1281 if (exportData.getSettings().isCancelled())
1285 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1286 cap.setForInput(null);
1289 FileFormatI format = fileFormat;
1290 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1291 .formatSequences(format, exportData.getAlignment(),
1292 exportData.getOmitHidden(),
1293 exportData.getStartEndPostions(),
1294 viewport.getAlignment().getHiddenColumns()));
1295 Desktop.addInternalFrame(cap, MessageManager
1296 .formatMessage("label.alignment_output_command", new Object[]
1297 { e.getActionCommand() }), 600, 500);
1298 } catch (OutOfMemoryError oom)
1300 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1307 public static AlignmentExportData getAlignmentForExport(
1308 FileFormatI format, AlignViewportI viewport,
1309 AlignExportSettingI exportSettings)
1311 AlignmentI alignmentToExport = null;
1312 AlignExportSettingI settings = exportSettings;
1313 String[] omitHidden = null;
1315 HiddenSequences hiddenSeqs = viewport.getAlignment()
1316 .getHiddenSequences();
1318 alignmentToExport = viewport.getAlignment();
1320 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1321 if (settings == null)
1323 settings = new AlignExportSettings(hasHiddenSeqs,
1324 viewport.hasHiddenColumns(), format);
1326 // settings.isExportAnnotations();
1328 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1330 omitHidden = viewport.getViewAsString(false,
1331 settings.isExportHiddenSequences());
1334 int[] alignmentStartEnd = new int[2];
1335 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1337 alignmentToExport = hiddenSeqs.getFullAlignment();
1341 alignmentToExport = viewport.getAlignment();
1343 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1344 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1345 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1346 omitHidden, alignmentStartEnd, settings);
1357 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1359 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1360 htmlSVG.exportHTML(null);
1364 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1366 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1367 bjs.exportHTML(null);
1370 public void createImageMap(File file, String image)
1372 alignPanel.makePNGImageMap(file, image);
1382 public void createPNG(File f)
1384 alignPanel.makePNG(f);
1394 public void createEPS(File f)
1396 alignPanel.makeEPS(f);
1400 public void createSVG(File f)
1402 alignPanel.makeSVG(f);
1406 public void pageSetup_actionPerformed(ActionEvent e)
1408 PrinterJob printJob = PrinterJob.getPrinterJob();
1409 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1419 public void printMenuItem_actionPerformed(ActionEvent e)
1421 // Putting in a thread avoids Swing painting problems
1422 PrintThread thread = new PrintThread(alignPanel);
1427 public void exportFeatures_actionPerformed(ActionEvent e)
1429 new AnnotationExporter(alignPanel).exportFeatures();
1433 public void exportAnnotations_actionPerformed(ActionEvent e)
1435 new AnnotationExporter(alignPanel).exportAnnotations();
1439 public void associatedData_actionPerformed(ActionEvent e)
1441 // Pick the tree file
1442 JalviewFileChooser chooser = new JalviewFileChooser(
1443 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1444 chooser.setFileView(new JalviewFileView());
1445 chooser.setDialogTitle(
1446 MessageManager.getString("label.load_jalview_annotations"));
1447 chooser.setToolTipText(
1448 MessageManager.getString("label.load_jalview_annotations"));
1450 int value = chooser.showOpenDialog(null);
1452 if (value == JalviewFileChooser.APPROVE_OPTION)
1454 String choice = chooser.getSelectedFile().getPath();
1455 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1456 loadJalviewDataFile(choice, null, null, null);
1462 * Close the current view or all views in the alignment frame. If the frame
1463 * only contains one view then the alignment will be removed from memory.
1465 * @param closeAllTabs
1468 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1470 if (alignPanels != null && alignPanels.size() < 2)
1472 closeAllTabs = true;
1477 if (alignPanels != null)
1481 if (this.isClosed())
1483 // really close all the windows - otherwise wait till
1484 // setClosed(true) is called
1485 for (int i = 0; i < alignPanels.size(); i++)
1487 AlignmentPanel ap = alignPanels.get(i);
1494 closeView(alignPanel);
1501 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1502 * be called recursively, with the frame now in 'closed' state
1504 this.setClosed(true);
1506 } catch (Exception ex)
1508 ex.printStackTrace();
1513 * Close the specified panel and close up tabs appropriately.
1515 * @param panelToClose
1517 public void closeView(AlignmentPanel panelToClose)
1519 int index = tabbedPane.getSelectedIndex();
1520 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1521 alignPanels.remove(panelToClose);
1522 panelToClose.closePanel();
1523 panelToClose = null;
1525 tabbedPane.removeTabAt(closedindex);
1526 tabbedPane.validate();
1528 if (index > closedindex || index == tabbedPane.getTabCount())
1530 // modify currently selected tab index if necessary.
1534 this.tabSelectionChanged(index);
1540 void updateEditMenuBar()
1543 if (viewport.getHistoryList().size() > 0)
1545 undoMenuItem.setEnabled(true);
1546 CommandI command = viewport.getHistoryList().peek();
1547 undoMenuItem.setText(MessageManager
1548 .formatMessage("label.undo_command", new Object[]
1549 { command.getDescription() }));
1553 undoMenuItem.setEnabled(false);
1554 undoMenuItem.setText(MessageManager.getString("action.undo"));
1557 if (viewport.getRedoList().size() > 0)
1559 redoMenuItem.setEnabled(true);
1561 CommandI command = viewport.getRedoList().peek();
1562 redoMenuItem.setText(MessageManager
1563 .formatMessage("label.redo_command", new Object[]
1564 { command.getDescription() }));
1568 redoMenuItem.setEnabled(false);
1569 redoMenuItem.setText(MessageManager.getString("action.redo"));
1574 public void addHistoryItem(CommandI command)
1576 if (command.getSize() > 0)
1578 viewport.addToHistoryList(command);
1579 viewport.clearRedoList();
1580 updateEditMenuBar();
1581 viewport.updateHiddenColumns();
1582 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1583 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1584 // viewport.getColumnSelection()
1585 // .getHiddenColumns().size() > 0);
1591 * @return alignment objects for all views
1593 AlignmentI[] getViewAlignments()
1595 if (alignPanels != null)
1597 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1599 for (AlignmentPanel ap : alignPanels)
1601 als[i++] = ap.av.getAlignment();
1605 if (viewport != null)
1607 return new AlignmentI[] { viewport.getAlignment() };
1619 protected void undoMenuItem_actionPerformed(ActionEvent e)
1621 if (viewport.getHistoryList().isEmpty())
1625 CommandI command = viewport.getHistoryList().pop();
1626 viewport.addToRedoList(command);
1627 command.undoCommand(getViewAlignments());
1629 AlignmentViewport originalSource = getOriginatingSource(command);
1630 updateEditMenuBar();
1632 if (originalSource != null)
1634 if (originalSource != viewport)
1637 "Implementation worry: mismatch of viewport origin for undo");
1639 originalSource.updateHiddenColumns();
1640 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1642 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1643 // viewport.getColumnSelection()
1644 // .getHiddenColumns().size() > 0);
1645 originalSource.firePropertyChange("alignment", null,
1646 originalSource.getAlignment().getSequences());
1657 protected void redoMenuItem_actionPerformed(ActionEvent e)
1659 if (viewport.getRedoList().size() < 1)
1664 CommandI command = viewport.getRedoList().pop();
1665 viewport.addToHistoryList(command);
1666 command.doCommand(getViewAlignments());
1668 AlignmentViewport originalSource = getOriginatingSource(command);
1669 updateEditMenuBar();
1671 if (originalSource != null)
1674 if (originalSource != viewport)
1677 "Implementation worry: mismatch of viewport origin for redo");
1679 originalSource.updateHiddenColumns();
1680 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1682 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1683 // viewport.getColumnSelection()
1684 // .getHiddenColumns().size() > 0);
1685 originalSource.firePropertyChange("alignment", null,
1686 originalSource.getAlignment().getSequences());
1690 AlignmentViewport getOriginatingSource(CommandI command)
1692 AlignmentViewport originalSource = null;
1693 // For sequence removal and addition, we need to fire
1694 // the property change event FROM the viewport where the
1695 // original alignment was altered
1696 AlignmentI al = null;
1697 if (command instanceof EditCommand)
1699 EditCommand editCommand = (EditCommand) command;
1700 al = editCommand.getAlignment();
1701 List<Component> comps = PaintRefresher.components
1702 .get(viewport.getSequenceSetId());
1704 for (Component comp : comps)
1706 if (comp instanceof AlignmentPanel)
1708 if (al == ((AlignmentPanel) comp).av.getAlignment())
1710 originalSource = ((AlignmentPanel) comp).av;
1717 if (originalSource == null)
1719 // The original view is closed, we must validate
1720 // the current view against the closed view first
1723 PaintRefresher.validateSequences(al, viewport.getAlignment());
1726 originalSource = viewport;
1729 return originalSource;
1738 public void moveSelectedSequences(boolean up)
1740 SequenceGroup sg = viewport.getSelectionGroup();
1746 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1747 viewport.getHiddenRepSequences(), up);
1748 alignPanel.paintAlignment(true, false);
1751 synchronized void slideSequences(boolean right, int size)
1753 List<SequenceI> sg = new ArrayList<>();
1754 if (viewport.cursorMode)
1756 sg.add(viewport.getAlignment()
1757 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1759 else if (viewport.getSelectionGroup() != null
1760 && viewport.getSelectionGroup().getSize() != viewport
1761 .getAlignment().getHeight())
1763 sg = viewport.getSelectionGroup()
1764 .getSequences(viewport.getHiddenRepSequences());
1772 List<SequenceI> invertGroup = new ArrayList<>();
1774 for (SequenceI seq : viewport.getAlignment().getSequences())
1776 if (!sg.contains(seq))
1778 invertGroup.add(seq);
1782 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1784 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1785 for (int i = 0; i < invertGroup.size(); i++)
1787 seqs2[i] = invertGroup.get(i);
1790 SlideSequencesCommand ssc;
1793 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1794 viewport.getGapCharacter());
1798 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1799 viewport.getGapCharacter());
1802 int groupAdjustment = 0;
1803 if (ssc.getGapsInsertedBegin() && right)
1805 if (viewport.cursorMode)
1807 alignPanel.getSeqPanel().moveCursor(size, 0);
1811 groupAdjustment = size;
1814 else if (!ssc.getGapsInsertedBegin() && !right)
1816 if (viewport.cursorMode)
1818 alignPanel.getSeqPanel().moveCursor(-size, 0);
1822 groupAdjustment = -size;
1826 if (groupAdjustment != 0)
1828 viewport.getSelectionGroup().setStartRes(
1829 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1830 viewport.getSelectionGroup().setEndRes(
1831 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1835 * just extend the last slide command if compatible; but not if in
1836 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1838 boolean appendHistoryItem = false;
1839 Deque<CommandI> historyList = viewport.getHistoryList();
1840 boolean inSplitFrame = getSplitViewContainer() != null;
1841 if (!inSplitFrame && historyList != null && historyList.size() > 0
1842 && historyList.peek() instanceof SlideSequencesCommand)
1844 appendHistoryItem = ssc.appendSlideCommand(
1845 (SlideSequencesCommand) historyList.peek());
1848 if (!appendHistoryItem)
1850 addHistoryItem(ssc);
1863 protected void copy_actionPerformed(ActionEvent e)
1865 if (viewport.getSelectionGroup() == null)
1869 // TODO: preserve the ordering of displayed alignment annotation in any
1870 // internal paste (particularly sequence associated annotation)
1871 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1872 String[] omitHidden = null;
1874 if (viewport.hasHiddenColumns())
1876 omitHidden = viewport.getViewAsString(true);
1879 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1880 seqs, omitHidden, null);
1882 StringSelection ss = new StringSelection(output);
1886 jalview.gui.Desktop.internalCopy = true;
1887 // Its really worth setting the clipboard contents
1888 // to empty before setting the large StringSelection!!
1889 Toolkit.getDefaultToolkit().getSystemClipboard()
1890 .setContents(new StringSelection(""), null);
1892 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1894 } catch (OutOfMemoryError er)
1896 new OOMWarning("copying region", er);
1900 HiddenColumns hiddenColumns = null;
1901 if (viewport.hasHiddenColumns())
1903 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1904 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1906 // create new HiddenColumns object with copy of hidden regions
1907 // between startRes and endRes, offset by startRes
1908 hiddenColumns = new HiddenColumns(
1909 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1910 hiddenCutoff, hiddenOffset);
1913 Desktop.jalviewClipboard = new Object[] { seqs,
1914 viewport.getAlignment().getDataset(), hiddenColumns };
1915 statusBar.setText(MessageManager.formatMessage(
1916 "label.copied_sequences_to_clipboard", new Object[]
1917 { Integer.valueOf(seqs.length).toString() }));
1927 protected void pasteNew_actionPerformed(ActionEvent e)
1939 protected void pasteThis_actionPerformed(ActionEvent e)
1945 * Paste contents of Jalview clipboard
1947 * @param newAlignment
1948 * true to paste to a new alignment, otherwise add to this.
1950 void paste(boolean newAlignment)
1952 boolean externalPaste = true;
1955 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1956 Transferable contents = c.getContents(this);
1958 if (contents == null)
1967 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1968 if (str.length() < 1)
1973 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
1975 } catch (OutOfMemoryError er)
1977 new OOMWarning("Out of memory pasting sequences!!", er);
1981 SequenceI[] sequences;
1982 boolean annotationAdded = false;
1983 AlignmentI alignment = null;
1985 if (Desktop.jalviewClipboard != null)
1987 // The clipboard was filled from within Jalview, we must use the
1989 // And dataset from the copied alignment
1990 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1991 // be doubly sure that we create *new* sequence objects.
1992 sequences = new SequenceI[newseq.length];
1993 for (int i = 0; i < newseq.length; i++)
1995 sequences[i] = new Sequence(newseq[i]);
1997 alignment = new Alignment(sequences);
1998 externalPaste = false;
2002 // parse the clipboard as an alignment.
2003 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2005 sequences = alignment.getSequencesArray();
2009 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2015 if (Desktop.jalviewClipboard != null)
2017 // dataset is inherited
2018 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2022 // new dataset is constructed
2023 alignment.setDataset(null);
2025 alwidth = alignment.getWidth() + 1;
2029 AlignmentI pastedal = alignment; // preserve pasted alignment object
2030 // Add pasted sequences and dataset into existing alignment.
2031 alignment = viewport.getAlignment();
2032 alwidth = alignment.getWidth() + 1;
2033 // decide if we need to import sequences from an existing dataset
2034 boolean importDs = Desktop.jalviewClipboard != null
2035 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2036 // importDs==true instructs us to copy over new dataset sequences from
2037 // an existing alignment
2038 Vector newDs = (importDs) ? new Vector() : null; // used to create
2039 // minimum dataset set
2041 for (int i = 0; i < sequences.length; i++)
2045 newDs.addElement(null);
2047 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2049 if (importDs && ds != null)
2051 if (!newDs.contains(ds))
2053 newDs.setElementAt(ds, i);
2054 ds = new Sequence(ds);
2055 // update with new dataset sequence
2056 sequences[i].setDatasetSequence(ds);
2060 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2065 // copy and derive new dataset sequence
2066 sequences[i] = sequences[i].deriveSequence();
2067 alignment.getDataset()
2068 .addSequence(sequences[i].getDatasetSequence());
2069 // TODO: avoid creation of duplicate dataset sequences with a
2070 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2072 alignment.addSequence(sequences[i]); // merges dataset
2076 newDs.clear(); // tidy up
2078 if (alignment.getAlignmentAnnotation() != null)
2080 for (AlignmentAnnotation alan : alignment
2081 .getAlignmentAnnotation())
2083 if (alan.graphGroup > fgroup)
2085 fgroup = alan.graphGroup;
2089 if (pastedal.getAlignmentAnnotation() != null)
2091 // Add any annotation attached to alignment.
2092 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2093 for (int i = 0; i < alann.length; i++)
2095 annotationAdded = true;
2096 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2098 AlignmentAnnotation newann = new AlignmentAnnotation(
2100 if (newann.graphGroup > -1)
2102 if (newGraphGroups.size() <= newann.graphGroup
2103 || newGraphGroups.get(newann.graphGroup) == null)
2105 for (int q = newGraphGroups
2106 .size(); q <= newann.graphGroup; q++)
2108 newGraphGroups.add(q, null);
2110 newGraphGroups.set(newann.graphGroup,
2111 Integer.valueOf(++fgroup));
2113 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2117 newann.padAnnotation(alwidth);
2118 alignment.addAnnotation(newann);
2128 addHistoryItem(new EditCommand(
2129 MessageManager.getString("label.add_sequences"),
2130 Action.PASTE, sequences, 0, alignment.getWidth(),
2133 // Add any annotations attached to sequences
2134 for (int i = 0; i < sequences.length; i++)
2136 if (sequences[i].getAnnotation() != null)
2138 AlignmentAnnotation newann;
2139 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2141 annotationAdded = true;
2142 newann = sequences[i].getAnnotation()[a];
2143 newann.adjustForAlignment();
2144 newann.padAnnotation(alwidth);
2145 if (newann.graphGroup > -1)
2147 if (newann.graphGroup > -1)
2149 if (newGraphGroups.size() <= newann.graphGroup
2150 || newGraphGroups.get(newann.graphGroup) == null)
2152 for (int q = newGraphGroups
2153 .size(); q <= newann.graphGroup; q++)
2155 newGraphGroups.add(q, null);
2157 newGraphGroups.set(newann.graphGroup,
2158 Integer.valueOf(++fgroup));
2160 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2164 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2168 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2176 // propagate alignment changed.
2177 viewport.getRanges().setEndSeq(alignment.getHeight());
2178 if (annotationAdded)
2180 // Duplicate sequence annotation in all views.
2181 AlignmentI[] alview = this.getViewAlignments();
2182 for (int i = 0; i < sequences.length; i++)
2184 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2189 for (int avnum = 0; avnum < alview.length; avnum++)
2191 if (alview[avnum] != alignment)
2193 // duplicate in a view other than the one with input focus
2194 int avwidth = alview[avnum].getWidth() + 1;
2195 // this relies on sann being preserved after we
2196 // modify the sequence's annotation array for each duplication
2197 for (int a = 0; a < sann.length; a++)
2199 AlignmentAnnotation newann = new AlignmentAnnotation(
2201 sequences[i].addAlignmentAnnotation(newann);
2202 newann.padAnnotation(avwidth);
2203 alview[avnum].addAnnotation(newann); // annotation was
2204 // duplicated earlier
2205 // TODO JAL-1145 graphGroups are not updated for sequence
2206 // annotation added to several views. This may cause
2208 alview[avnum].setAnnotationIndex(newann, a);
2213 buildSortByAnnotationScoresMenu();
2215 viewport.firePropertyChange("alignment", null,
2216 alignment.getSequences());
2217 if (alignPanels != null)
2219 for (AlignmentPanel ap : alignPanels)
2221 ap.validateAnnotationDimensions(false);
2226 alignPanel.validateAnnotationDimensions(false);
2232 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2234 String newtitle = new String("Copied sequences");
2236 if (Desktop.jalviewClipboard != null
2237 && Desktop.jalviewClipboard[2] != null)
2239 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2240 af.viewport.setHiddenColumns(hc);
2243 // >>>This is a fix for the moment, until a better solution is
2245 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2246 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2247 .getFeatureRenderer());
2249 // TODO: maintain provenance of an alignment, rather than just make the
2250 // title a concatenation of operations.
2253 if (title.startsWith("Copied sequences"))
2259 newtitle = newtitle.concat("- from " + title);
2264 newtitle = new String("Pasted sequences");
2267 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2272 } catch (Exception ex)
2274 ex.printStackTrace();
2275 System.out.println("Exception whilst pasting: " + ex);
2276 // could be anything being pasted in here
2282 protected void expand_newalign(ActionEvent e)
2286 AlignmentI alignment = AlignmentUtils
2287 .expandContext(getViewport().getAlignment(), -1);
2288 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2290 String newtitle = new String("Flanking alignment");
2292 if (Desktop.jalviewClipboard != null
2293 && Desktop.jalviewClipboard[2] != null)
2295 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2296 af.viewport.setHiddenColumns(hc);
2299 // >>>This is a fix for the moment, until a better solution is
2301 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2302 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2303 .getFeatureRenderer());
2305 // TODO: maintain provenance of an alignment, rather than just make the
2306 // title a concatenation of operations.
2308 if (title.startsWith("Copied sequences"))
2314 newtitle = newtitle.concat("- from " + title);
2318 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2320 } catch (Exception ex)
2322 ex.printStackTrace();
2323 System.out.println("Exception whilst pasting: " + ex);
2324 // could be anything being pasted in here
2325 } catch (OutOfMemoryError oom)
2327 new OOMWarning("Viewing flanking region of alignment", oom);
2338 protected void cut_actionPerformed(ActionEvent e)
2340 copy_actionPerformed(null);
2341 delete_actionPerformed(null);
2351 protected void delete_actionPerformed(ActionEvent evt)
2354 SequenceGroup sg = viewport.getSelectionGroup();
2361 * If the cut affects all sequences, warn, remove highlighted columns
2363 if (sg.getSize() == viewport.getAlignment().getHeight())
2365 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2366 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2367 if (isEntireAlignWidth)
2369 int confirm = JvOptionPane.showConfirmDialog(this,
2370 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2371 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2372 JvOptionPane.OK_CANCEL_OPTION);
2374 if (confirm == JvOptionPane.CANCEL_OPTION
2375 || confirm == JvOptionPane.CLOSED_OPTION)
2380 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2381 sg.getEndRes() + 1);
2383 SequenceI[] cut = sg.getSequences()
2384 .toArray(new SequenceI[sg.getSize()]);
2386 addHistoryItem(new EditCommand(
2387 MessageManager.getString("label.cut_sequences"), Action.CUT,
2388 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2389 viewport.getAlignment()));
2391 viewport.setSelectionGroup(null);
2392 viewport.sendSelection();
2393 viewport.getAlignment().deleteGroup(sg);
2395 viewport.firePropertyChange("alignment", null,
2396 viewport.getAlignment().getSequences());
2397 if (viewport.getAlignment().getHeight() < 1)
2401 this.setClosed(true);
2402 } catch (Exception ex)
2415 protected void deleteGroups_actionPerformed(ActionEvent e)
2417 if (avc.deleteGroups())
2419 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2420 alignPanel.updateAnnotation();
2421 alignPanel.paintAlignment(true, true);
2432 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2434 SequenceGroup sg = new SequenceGroup(
2435 viewport.getAlignment().getSequences());
2437 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2438 viewport.setSelectionGroup(sg);
2439 viewport.isSelectionGroupChanged(true);
2440 viewport.sendSelection();
2441 // JAL-2034 - should delegate to
2442 // alignPanel to decide if overview needs
2444 alignPanel.paintAlignment(false, false);
2445 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2455 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2457 if (viewport.cursorMode)
2459 alignPanel.getSeqPanel().keyboardNo1 = null;
2460 alignPanel.getSeqPanel().keyboardNo2 = null;
2462 viewport.setSelectionGroup(null);
2463 viewport.getColumnSelection().clear();
2464 viewport.setSelectionGroup(null);
2465 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2466 // JAL-2034 - should delegate to
2467 // alignPanel to decide if overview needs
2469 alignPanel.paintAlignment(false, false);
2470 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2471 viewport.sendSelection();
2481 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2483 SequenceGroup sg = viewport.getSelectionGroup();
2487 selectAllSequenceMenuItem_actionPerformed(null);
2492 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2494 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2496 // JAL-2034 - should delegate to
2497 // alignPanel to decide if overview needs
2500 alignPanel.paintAlignment(true, false);
2501 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2502 viewport.sendSelection();
2506 public void invertColSel_actionPerformed(ActionEvent e)
2508 viewport.invertColumnSelection();
2509 alignPanel.paintAlignment(true, false);
2510 viewport.sendSelection();
2520 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2522 trimAlignment(true);
2532 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2534 trimAlignment(false);
2537 void trimAlignment(boolean trimLeft)
2539 ColumnSelection colSel = viewport.getColumnSelection();
2542 if (!colSel.isEmpty())
2546 column = colSel.getMin();
2550 column = colSel.getMax();
2554 if (viewport.getSelectionGroup() != null)
2556 seqs = viewport.getSelectionGroup()
2557 .getSequencesAsArray(viewport.getHiddenRepSequences());
2561 seqs = viewport.getAlignment().getSequencesArray();
2564 TrimRegionCommand trimRegion;
2567 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2568 column, viewport.getAlignment());
2569 viewport.getRanges().setStartRes(0);
2573 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2574 column, viewport.getAlignment());
2577 statusBar.setText(MessageManager
2578 .formatMessage("label.removed_columns", new String[]
2579 { Integer.valueOf(trimRegion.getSize()).toString() }));
2581 addHistoryItem(trimRegion);
2583 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2585 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2586 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2588 viewport.getAlignment().deleteGroup(sg);
2592 viewport.firePropertyChange("alignment", null,
2593 viewport.getAlignment().getSequences());
2604 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2606 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2609 if (viewport.getSelectionGroup() != null)
2611 seqs = viewport.getSelectionGroup()
2612 .getSequencesAsArray(viewport.getHiddenRepSequences());
2613 start = viewport.getSelectionGroup().getStartRes();
2614 end = viewport.getSelectionGroup().getEndRes();
2618 seqs = viewport.getAlignment().getSequencesArray();
2621 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2622 "Remove Gapped Columns", seqs, start, end,
2623 viewport.getAlignment());
2625 addHistoryItem(removeGapCols);
2627 statusBar.setText(MessageManager
2628 .formatMessage("label.removed_empty_columns", new Object[]
2629 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2631 // This is to maintain viewport position on first residue
2632 // of first sequence
2633 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2634 ViewportRanges ranges = viewport.getRanges();
2635 int startRes = seq.findPosition(ranges.getStartRes());
2636 // ShiftList shifts;
2637 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2638 // edit.alColumnChanges=shifts.getInverse();
2639 // if (viewport.hasHiddenColumns)
2640 // viewport.getColumnSelection().compensateForEdits(shifts);
2641 ranges.setStartRes(seq.findIndex(startRes) - 1);
2642 viewport.firePropertyChange("alignment", null,
2643 viewport.getAlignment().getSequences());
2654 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2656 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2659 if (viewport.getSelectionGroup() != null)
2661 seqs = viewport.getSelectionGroup()
2662 .getSequencesAsArray(viewport.getHiddenRepSequences());
2663 start = viewport.getSelectionGroup().getStartRes();
2664 end = viewport.getSelectionGroup().getEndRes();
2668 seqs = viewport.getAlignment().getSequencesArray();
2671 // This is to maintain viewport position on first residue
2672 // of first sequence
2673 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2674 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2676 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2677 viewport.getAlignment()));
2679 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2681 viewport.firePropertyChange("alignment", null,
2682 viewport.getAlignment().getSequences());
2693 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2695 viewport.setPadGaps(padGapsMenuitem.isSelected());
2696 viewport.firePropertyChange("alignment", null,
2697 viewport.getAlignment().getSequences());
2707 public void findMenuItem_actionPerformed(ActionEvent e)
2713 * Create a new view of the current alignment.
2716 public void newView_actionPerformed(ActionEvent e)
2718 newView(null, true);
2722 * Creates and shows a new view of the current alignment.
2725 * title of newly created view; if null, one will be generated
2726 * @param copyAnnotation
2727 * if true then duplicate all annnotation, groups and settings
2728 * @return new alignment panel, already displayed.
2730 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2733 * Create a new AlignmentPanel (with its own, new Viewport)
2735 AlignmentPanel newap = new jalview.project.Jalview2XML()
2736 .copyAlignPanel(alignPanel);
2737 if (!copyAnnotation)
2740 * remove all groups and annotation except for the automatic stuff
2742 newap.av.getAlignment().deleteAllGroups();
2743 newap.av.getAlignment().deleteAllAnnotations(false);
2746 newap.av.setGatherViewsHere(false);
2748 if (viewport.getViewName() == null)
2750 viewport.setViewName(MessageManager
2751 .getString("label.view_name_original"));
2755 * Views share the same edits undo and redo stacks
2757 newap.av.setHistoryList(viewport.getHistoryList());
2758 newap.av.setRedoList(viewport.getRedoList());
2761 * copy any visualisation settings that are not saved in the project
2763 newap.av.setColourAppliesToAllGroups(
2764 viewport.getColourAppliesToAllGroups());
2767 * Views share the same mappings; need to deregister any new mappings
2768 * created by copyAlignPanel, and register the new reference to the shared
2771 newap.av.replaceMappings(viewport.getAlignment());
2774 * start up cDNA consensus (if applicable) now mappings are in place
2776 if (newap.av.initComplementConsensus())
2778 newap.refresh(true); // adjust layout of annotations
2781 newap.av.setViewName(getNewViewName(viewTitle));
2783 addAlignmentPanel(newap, true);
2784 newap.alignmentChanged();
2786 if (alignPanels.size() == 2)
2788 viewport.setGatherViewsHere(true);
2790 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2795 * Make a new name for the view, ensuring it is unique within the current
2796 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2797 * these now use viewId. Unique view names are still desirable for usability.)
2802 protected String getNewViewName(String viewTitle)
2804 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2805 boolean addFirstIndex = false;
2806 if (viewTitle == null || viewTitle.trim().length() == 0)
2808 viewTitle = MessageManager.getString("action.view");
2809 addFirstIndex = true;
2813 index = 1;// we count from 1 if given a specific name
2815 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2817 List<Component> comps = PaintRefresher.components
2818 .get(viewport.getSequenceSetId());
2820 List<String> existingNames = getExistingViewNames(comps);
2822 while (existingNames.contains(newViewName))
2824 newViewName = viewTitle + " " + (++index);
2830 * Returns a list of distinct view names found in the given list of
2831 * components. View names are held on the viewport of an AlignmentPanel.
2836 protected List<String> getExistingViewNames(List<Component> comps)
2838 List<String> existingNames = new ArrayList<>();
2839 for (Component comp : comps)
2841 if (comp instanceof AlignmentPanel)
2843 AlignmentPanel ap = (AlignmentPanel) comp;
2844 if (!existingNames.contains(ap.av.getViewName()))
2846 existingNames.add(ap.av.getViewName());
2850 return existingNames;
2854 * Explode tabbed views into separate windows.
2857 public void expandViews_actionPerformed(ActionEvent e)
2859 Desktop.explodeViews(this);
2863 * Gather views in separate windows back into a tabbed presentation.
2866 public void gatherViews_actionPerformed(ActionEvent e)
2868 Desktop.instance.gatherViews(this);
2878 public void font_actionPerformed(ActionEvent e)
2880 new FontChooser(alignPanel);
2890 protected void seqLimit_actionPerformed(ActionEvent e)
2892 viewport.setShowJVSuffix(seqLimits.isSelected());
2894 alignPanel.getIdPanel().getIdCanvas()
2895 .setPreferredSize(alignPanel.calculateIdWidth());
2896 alignPanel.paintAlignment(true, false);
2900 public void idRightAlign_actionPerformed(ActionEvent e)
2902 viewport.setRightAlignIds(idRightAlign.isSelected());
2903 alignPanel.paintAlignment(false, false);
2907 public void centreColumnLabels_actionPerformed(ActionEvent e)
2909 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2910 alignPanel.paintAlignment(false, false);
2916 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2919 protected void followHighlight_actionPerformed()
2922 * Set the 'follow' flag on the Viewport (and scroll to position if now
2925 final boolean state = this.followHighlightMenuItem.getState();
2926 viewport.setFollowHighlight(state);
2929 alignPanel.scrollToPosition(viewport.getSearchResults());
2940 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2942 viewport.setColourText(colourTextMenuItem.isSelected());
2943 alignPanel.paintAlignment(false, false);
2953 public void wrapMenuItem_actionPerformed(ActionEvent e)
2955 scaleAbove.setVisible(wrapMenuItem.isSelected());
2956 scaleLeft.setVisible(wrapMenuItem.isSelected());
2957 scaleRight.setVisible(wrapMenuItem.isSelected());
2958 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2959 alignPanel.updateLayout();
2963 public void showAllSeqs_actionPerformed(ActionEvent e)
2965 viewport.showAllHiddenSeqs();
2969 public void showAllColumns_actionPerformed(ActionEvent e)
2971 viewport.showAllHiddenColumns();
2972 alignPanel.paintAlignment(true, true);
2973 viewport.sendSelection();
2977 public void hideSelSequences_actionPerformed(ActionEvent e)
2979 viewport.hideAllSelectedSeqs();
2983 * called by key handler and the hide all/show all menu items
2988 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2991 boolean hide = false;
2992 SequenceGroup sg = viewport.getSelectionGroup();
2993 if (!toggleSeqs && !toggleCols)
2995 // Hide everything by the current selection - this is a hack - we do the
2996 // invert and then hide
2997 // first check that there will be visible columns after the invert.
2998 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
2999 && sg.getStartRes() <= sg.getEndRes()))
3001 // now invert the sequence set, if required - empty selection implies
3002 // that no hiding is required.
3005 invertSequenceMenuItem_actionPerformed(null);
3006 sg = viewport.getSelectionGroup();
3010 viewport.expandColSelection(sg, true);
3011 // finally invert the column selection and get the new sequence
3013 invertColSel_actionPerformed(null);
3020 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3022 hideSelSequences_actionPerformed(null);
3025 else if (!(toggleCols && viewport.hasSelectedColumns()))
3027 showAllSeqs_actionPerformed(null);
3033 if (viewport.hasSelectedColumns())
3035 hideSelColumns_actionPerformed(null);
3038 viewport.setSelectionGroup(sg);
3043 showAllColumns_actionPerformed(null);
3052 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3053 * event.ActionEvent)
3056 public void hideAllButSelection_actionPerformed(ActionEvent e)
3058 toggleHiddenRegions(false, false);
3059 viewport.sendSelection();
3066 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3070 public void hideAllSelection_actionPerformed(ActionEvent e)
3072 SequenceGroup sg = viewport.getSelectionGroup();
3073 viewport.expandColSelection(sg, false);
3074 viewport.hideAllSelectedSeqs();
3075 viewport.hideSelectedColumns();
3076 alignPanel.updateLayout();
3077 alignPanel.paintAlignment(true, true);
3078 viewport.sendSelection();
3085 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3089 public void showAllhidden_actionPerformed(ActionEvent e)
3091 viewport.showAllHiddenColumns();
3092 viewport.showAllHiddenSeqs();
3093 alignPanel.paintAlignment(true, true);
3094 viewport.sendSelection();
3098 public void hideSelColumns_actionPerformed(ActionEvent e)
3100 viewport.hideSelectedColumns();
3101 alignPanel.updateLayout();
3102 alignPanel.paintAlignment(true, true);
3103 viewport.sendSelection();
3107 public void hiddenMarkers_actionPerformed(ActionEvent e)
3109 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3120 protected void scaleAbove_actionPerformed(ActionEvent e)
3122 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3123 // TODO: do we actually need to update overview for scale above change ?
3124 alignPanel.paintAlignment(true, false);
3134 protected void scaleLeft_actionPerformed(ActionEvent e)
3136 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3137 alignPanel.paintAlignment(true, false);
3147 protected void scaleRight_actionPerformed(ActionEvent e)
3149 viewport.setScaleRightWrapped(scaleRight.isSelected());
3150 alignPanel.paintAlignment(true, false);
3160 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3162 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3163 alignPanel.paintAlignment(false, false);
3173 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3175 viewport.setShowText(viewTextMenuItem.isSelected());
3176 alignPanel.paintAlignment(false, false);
3186 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3188 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3189 alignPanel.paintAlignment(false, false);
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, true);
3231 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3232 * the annotations panel as a whole.
3234 * The options to show/hide all annotations should be enabled when the panel
3235 * is shown, and disabled when the panel is hidden.
3240 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3242 final boolean setVisible = annotationPanelMenuItem.isSelected();
3243 viewport.setShowAnnotation(setVisible);
3244 this.showAllSeqAnnotations.setEnabled(setVisible);
3245 this.hideAllSeqAnnotations.setEnabled(setVisible);
3246 this.showAllAlAnnotations.setEnabled(setVisible);
3247 this.hideAllAlAnnotations.setEnabled(setVisible);
3248 alignPanel.updateLayout();
3252 public void alignmentProperties()
3254 JEditorPane editPane = new JEditorPane("text/html", "");
3255 editPane.setEditable(false);
3256 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3259 MessageManager.formatMessage("label.html_content", new Object[]
3260 { contents.toString() }));
3261 JInternalFrame frame = new JInternalFrame();
3262 frame.getContentPane().add(new JScrollPane(editPane));
3264 Desktop.addInternalFrame(frame, MessageManager
3265 .formatMessage("label.alignment_properties", new Object[]
3266 { getTitle() }), 500, 400);
3276 public void overviewMenuItem_actionPerformed(ActionEvent e)
3278 if (alignPanel.overviewPanel != null)
3283 JInternalFrame frame = new JInternalFrame();
3284 final OverviewPanel overview = new OverviewPanel(alignPanel);
3285 frame.setContentPane(overview);
3286 Desktop.addInternalFrame(frame, MessageManager
3287 .formatMessage("label.overview_params", new Object[]
3288 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3291 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3292 frame.addInternalFrameListener(
3293 new javax.swing.event.InternalFrameAdapter()
3296 public void internalFrameClosed(
3297 javax.swing.event.InternalFrameEvent evt)
3300 alignPanel.setOverviewPanel(null);
3303 if (getKeyListeners().length > 0)
3305 frame.addKeyListener(getKeyListeners()[0]);
3308 alignPanel.setOverviewPanel(overview);
3312 public void textColour_actionPerformed()
3314 new TextColourChooser().chooseColour(alignPanel, null);
3318 * public void covariationColour_actionPerformed() {
3320 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3324 public void annotationColour_actionPerformed()
3326 new AnnotationColourChooser(viewport, alignPanel);
3330 public void annotationColumn_actionPerformed(ActionEvent e)
3332 new AnnotationColumnChooser(viewport, alignPanel);
3336 * Action on the user checking or unchecking the option to apply the selected
3337 * colour scheme to all groups. If unchecked, groups may have their own
3338 * independent colour schemes.
3343 public void applyToAllGroups_actionPerformed(boolean selected)
3345 viewport.setColourAppliesToAllGroups(selected);
3349 * Action on user selecting a colour from the colour menu
3352 * the name (not the menu item label!) of the colour scheme
3355 public void changeColour_actionPerformed(String name)
3358 * 'User Defined' opens a panel to configure or load a
3359 * user-defined colour scheme
3361 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3363 new UserDefinedColours(alignPanel);
3368 * otherwise set the chosen colour scheme (or null for 'None')
3370 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3372 viewport.getAlignment(), viewport.getHiddenRepSequences());
3377 * Actions on setting or changing the alignment colour scheme
3382 public void changeColour(ColourSchemeI cs)
3384 // TODO: pull up to controller method
3385 ColourMenuHelper.setColourSelected(colourMenu, cs);
3387 viewport.setGlobalColourScheme(cs);
3389 alignPanel.paintAlignment(true, true);
3393 * Show the PID threshold slider panel
3396 protected void modifyPID_actionPerformed()
3398 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3399 alignPanel.getViewName());
3400 SliderPanel.showPIDSlider();
3404 * Show the Conservation slider panel
3407 protected void modifyConservation_actionPerformed()
3409 SliderPanel.setConservationSlider(alignPanel,
3410 viewport.getResidueShading(), alignPanel.getViewName());
3411 SliderPanel.showConservationSlider();
3415 * Action on selecting or deselecting (Colour) By Conservation
3418 public void conservationMenuItem_actionPerformed(boolean selected)
3420 modifyConservation.setEnabled(selected);
3421 viewport.setConservationSelected(selected);
3422 viewport.getResidueShading().setConservationApplied(selected);
3424 changeColour(viewport.getGlobalColourScheme());
3427 modifyConservation_actionPerformed();
3431 SliderPanel.hideConservationSlider();
3436 * Action on selecting or deselecting (Colour) Above PID Threshold
3439 public void abovePIDThreshold_actionPerformed(boolean selected)
3441 modifyPID.setEnabled(selected);
3442 viewport.setAbovePIDThreshold(selected);
3445 viewport.getResidueShading().setThreshold(0,
3446 viewport.isIgnoreGapsConsensus());
3449 changeColour(viewport.getGlobalColourScheme());
3452 modifyPID_actionPerformed();
3456 SliderPanel.hidePIDSlider();
3467 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3469 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3470 AlignmentSorter.sortByPID(viewport.getAlignment(),
3471 viewport.getAlignment().getSequenceAt(0));
3472 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3473 viewport.getAlignment()));
3474 alignPanel.paintAlignment(true, false);
3484 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3486 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3487 AlignmentSorter.sortByID(viewport.getAlignment());
3489 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3490 alignPanel.paintAlignment(true, false);
3500 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3502 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3503 AlignmentSorter.sortByLength(viewport.getAlignment());
3504 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3505 viewport.getAlignment()));
3506 alignPanel.paintAlignment(true, false);
3516 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3518 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3519 AlignmentSorter.sortByGroup(viewport.getAlignment());
3520 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3521 viewport.getAlignment()));
3523 alignPanel.paintAlignment(true, false);
3533 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3535 new RedundancyPanel(alignPanel, this);
3545 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3547 if ((viewport.getSelectionGroup() == null)
3548 || (viewport.getSelectionGroup().getSize() < 2))
3550 JvOptionPane.showInternalMessageDialog(this,
3551 MessageManager.getString(
3552 "label.you_must_select_least_two_sequences"),
3553 MessageManager.getString("label.invalid_selection"),
3554 JvOptionPane.WARNING_MESSAGE);
3558 JInternalFrame frame = new JInternalFrame();
3559 frame.setContentPane(new PairwiseAlignPanel(viewport));
3560 Desktop.addInternalFrame(frame,
3561 MessageManager.getString("action.pairwise_alignment"), 600,
3567 public void autoCalculate_actionPerformed(ActionEvent e)
3569 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3570 if (viewport.autoCalculateConsensus)
3572 viewport.firePropertyChange("alignment", null,
3573 viewport.getAlignment().getSequences());
3578 public void sortByTreeOption_actionPerformed(ActionEvent e)
3580 viewport.sortByTree = sortByTree.isSelected();
3584 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3586 viewport.followSelection = listenToViewSelections.isSelected();
3590 * Constructs a tree panel and adds it to the desktop
3593 * tree type (NJ or AV)
3595 * name of score model used to compute the tree
3597 * parameters for the distance or similarity calculation
3599 void newTreePanel(String type, String modelName,
3600 SimilarityParamsI options)
3602 String frameTitle = "";
3605 boolean onSelection = false;
3606 if (viewport.getSelectionGroup() != null
3607 && viewport.getSelectionGroup().getSize() > 0)
3609 SequenceGroup sg = viewport.getSelectionGroup();
3611 /* Decide if the selection is a column region */
3612 for (SequenceI _s : sg.getSequences())
3614 if (_s.getLength() < sg.getEndRes())
3616 JvOptionPane.showMessageDialog(Desktop.desktop,
3617 MessageManager.getString(
3618 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3619 MessageManager.getString(
3620 "label.sequences_selection_not_aligned"),
3621 JvOptionPane.WARNING_MESSAGE);
3630 if (viewport.getAlignment().getHeight() < 2)
3636 tp = new TreePanel(alignPanel, type, modelName, options);
3637 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3639 frameTitle += " from ";
3641 if (viewport.getViewName() != null)
3643 frameTitle += viewport.getViewName() + " of ";
3646 frameTitle += this.title;
3648 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3659 public void addSortByOrderMenuItem(String title,
3660 final AlignmentOrder order)
3662 final JMenuItem item = new JMenuItem(MessageManager
3663 .formatMessage("action.by_title_param", new Object[]
3666 item.addActionListener(new java.awt.event.ActionListener()
3669 public void actionPerformed(ActionEvent e)
3671 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3673 // TODO: JBPNote - have to map order entries to curent SequenceI
3675 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3677 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3678 viewport.getAlignment()));
3680 alignPanel.paintAlignment(true, false);
3686 * Add a new sort by annotation score menu item
3689 * the menu to add the option to
3691 * the label used to retrieve scores for each sequence on the
3694 public void addSortByAnnotScoreMenuItem(JMenu sort,
3695 final String scoreLabel)
3697 final JMenuItem item = new JMenuItem(scoreLabel);
3699 item.addActionListener(new java.awt.event.ActionListener()
3702 public void actionPerformed(ActionEvent e)
3704 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3705 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3706 viewport.getAlignment());// ,viewport.getSelectionGroup());
3707 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3708 viewport.getAlignment()));
3709 alignPanel.paintAlignment(true, false);
3715 * last hash for alignment's annotation array - used to minimise cost of
3718 protected int _annotationScoreVectorHash;
3721 * search the alignment and rebuild the sort by annotation score submenu the
3722 * last alignment annotation vector hash is stored to minimize cost of
3723 * rebuilding in subsequence calls.
3727 public void buildSortByAnnotationScoresMenu()
3729 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3734 if (viewport.getAlignment().getAlignmentAnnotation()
3735 .hashCode() != _annotationScoreVectorHash)
3737 sortByAnnotScore.removeAll();
3738 // almost certainly a quicker way to do this - but we keep it simple
3739 Hashtable scoreSorts = new Hashtable();
3740 AlignmentAnnotation aann[];
3741 for (SequenceI sqa : viewport.getAlignment().getSequences())
3743 aann = sqa.getAnnotation();
3744 for (int i = 0; aann != null && i < aann.length; i++)
3746 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3748 scoreSorts.put(aann[i].label, aann[i].label);
3752 Enumeration labels = scoreSorts.keys();
3753 while (labels.hasMoreElements())
3755 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3756 (String) labels.nextElement());
3758 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3761 _annotationScoreVectorHash = viewport.getAlignment()
3762 .getAlignmentAnnotation().hashCode();
3767 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3768 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3769 * call. Listeners are added to remove the menu item when the treePanel is
3770 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3774 public void buildTreeSortMenu()
3776 sortByTreeMenu.removeAll();
3778 List<Component> comps = PaintRefresher.components
3779 .get(viewport.getSequenceSetId());
3780 List<TreePanel> treePanels = new ArrayList<>();
3781 for (Component comp : comps)
3783 if (comp instanceof TreePanel)
3785 treePanels.add((TreePanel) comp);
3789 if (treePanels.size() < 1)
3791 sortByTreeMenu.setVisible(false);
3795 sortByTreeMenu.setVisible(true);
3797 for (final TreePanel tp : treePanels)
3799 final JMenuItem item = new JMenuItem(tp.getTitle());
3800 item.addActionListener(new java.awt.event.ActionListener()
3803 public void actionPerformed(ActionEvent e)
3805 tp.sortByTree_actionPerformed();
3806 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3811 sortByTreeMenu.add(item);
3815 public boolean sortBy(AlignmentOrder alorder, String undoname)
3817 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3818 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3819 if (undoname != null)
3821 addHistoryItem(new OrderCommand(undoname, oldOrder,
3822 viewport.getAlignment()));
3824 alignPanel.paintAlignment(true, false);
3829 * Work out whether the whole set of sequences or just the selected set will
3830 * be submitted for multiple alignment.
3833 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3835 // Now, check we have enough sequences
3836 AlignmentView msa = null;
3838 if ((viewport.getSelectionGroup() != null)
3839 && (viewport.getSelectionGroup().getSize() > 1))
3841 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3842 // some common interface!
3844 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3845 * SequenceI[sz = seqs.getSize(false)];
3847 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3848 * seqs.getSequenceAt(i); }
3850 msa = viewport.getAlignmentView(true);
3852 else if (viewport.getSelectionGroup() != null
3853 && viewport.getSelectionGroup().getSize() == 1)
3855 int option = JvOptionPane.showConfirmDialog(this,
3856 MessageManager.getString("warn.oneseq_msainput_selection"),
3857 MessageManager.getString("label.invalid_selection"),
3858 JvOptionPane.OK_CANCEL_OPTION);
3859 if (option == JvOptionPane.OK_OPTION)
3861 msa = viewport.getAlignmentView(false);
3866 msa = viewport.getAlignmentView(false);
3872 * Decides what is submitted to a secondary structure prediction service: the
3873 * first sequence in the alignment, or in the current selection, or, if the
3874 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3875 * region or the whole alignment. (where the first sequence in the set is the
3876 * one that the prediction will be for).
3878 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3880 AlignmentView seqs = null;
3882 if ((viewport.getSelectionGroup() != null)
3883 && (viewport.getSelectionGroup().getSize() > 0))
3885 seqs = viewport.getAlignmentView(true);
3889 seqs = viewport.getAlignmentView(false);
3891 // limit sequences - JBPNote in future - could spawn multiple prediction
3893 // TODO: viewport.getAlignment().isAligned is a global state - the local
3894 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3895 if (!viewport.getAlignment().isAligned(false))
3897 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3898 // TODO: if seqs.getSequences().length>1 then should really have warned
3912 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3914 // Pick the tree file
3915 JalviewFileChooser chooser = new JalviewFileChooser(
3916 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3917 chooser.setFileView(new JalviewFileView());
3918 chooser.setDialogTitle(
3919 MessageManager.getString("label.select_newick_like_tree_file"));
3920 chooser.setToolTipText(
3921 MessageManager.getString("label.load_tree_file"));
3923 int value = chooser.showOpenDialog(null);
3925 if (value == JalviewFileChooser.APPROVE_OPTION)
3927 String filePath = chooser.getSelectedFile().getPath();
3928 Cache.setProperty("LAST_DIRECTORY", filePath);
3929 NewickFile fin = null;
3932 fin = new NewickFile(filePath, DataSourceType.FILE);
3933 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3934 } catch (Exception ex)
3936 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3937 MessageManager.getString("label.problem_reading_tree_file"),
3938 JvOptionPane.WARNING_MESSAGE);
3939 ex.printStackTrace();
3941 if (fin != null && fin.hasWarningMessage())
3943 JvOptionPane.showMessageDialog(Desktop.desktop,
3944 fin.getWarningMessage(),
3946 .getString("label.possible_problem_with_tree_file"),
3947 JvOptionPane.WARNING_MESSAGE);
3952 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3954 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3957 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3958 int h, int x, int y)
3960 return showNewickTree(nf, treeTitle, null, w, h, x, y);
3964 * Add a treeviewer for the tree extracted from a Newick file object to the
3965 * current alignment view
3972 * Associated alignment input data (or null)
3981 * @return TreePanel handle
3983 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
3984 AlignmentView input, int w, int h, int x, int y)
3986 TreePanel tp = null;
3992 if (nf.getTree() != null)
3994 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4000 tp.setLocation(x, y);
4003 Desktop.addInternalFrame(tp, treeTitle, w, h);
4005 } catch (Exception ex)
4007 ex.printStackTrace();
4013 private boolean buildingMenu = false;
4016 * Generates menu items and listener event actions for web service clients
4019 public void BuildWebServiceMenu()
4021 while (buildingMenu)
4025 System.err.println("Waiting for building menu to finish.");
4027 } catch (Exception e)
4031 final AlignFrame me = this;
4032 buildingMenu = true;
4033 new Thread(new Runnable()
4038 final List<JMenuItem> legacyItems = new ArrayList<>();
4041 // System.err.println("Building ws menu again "
4042 // + Thread.currentThread());
4043 // TODO: add support for context dependent disabling of services based
4045 // alignment and current selection
4046 // TODO: add additional serviceHandle parameter to specify abstract
4048 // class independently of AbstractName
4049 // TODO: add in rediscovery GUI function to restart discoverer
4050 // TODO: group services by location as well as function and/or
4052 // object broker mechanism.
4053 final Vector<JMenu> wsmenu = new Vector<>();
4054 final IProgressIndicator af = me;
4057 * do not i18n these strings - they are hard-coded in class
4058 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4059 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4061 final JMenu msawsmenu = new JMenu("Alignment");
4062 final JMenu secstrmenu = new JMenu(
4063 "Secondary Structure Prediction");
4064 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4065 final JMenu analymenu = new JMenu("Analysis");
4066 final JMenu dismenu = new JMenu("Protein Disorder");
4067 // JAL-940 - only show secondary structure prediction services from
4068 // the legacy server
4069 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4071 Discoverer.services != null && (Discoverer.services.size() > 0))
4073 // TODO: refactor to allow list of AbstractName/Handler bindings to
4075 // stored or retrieved from elsewhere
4076 // No MSAWS used any more:
4077 // Vector msaws = null; // (Vector)
4078 // Discoverer.services.get("MsaWS");
4079 Vector secstrpr = (Vector) Discoverer.services
4081 if (secstrpr != null)
4083 // Add any secondary structure prediction services
4084 for (int i = 0, j = secstrpr.size(); i < j; i++)
4086 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4088 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4089 .getServiceClient(sh);
4090 int p = secstrmenu.getItemCount();
4091 impl.attachWSMenuEntry(secstrmenu, me);
4092 int q = secstrmenu.getItemCount();
4093 for (int litm = p; litm < q; litm++)
4095 legacyItems.add(secstrmenu.getItem(litm));
4101 // Add all submenus in the order they should appear on the web
4103 wsmenu.add(msawsmenu);
4104 wsmenu.add(secstrmenu);
4105 wsmenu.add(dismenu);
4106 wsmenu.add(analymenu);
4107 // No search services yet
4108 // wsmenu.add(seqsrchmenu);
4110 javax.swing.SwingUtilities.invokeLater(new Runnable()
4117 webService.removeAll();
4118 // first, add discovered services onto the webservices menu
4119 if (wsmenu.size() > 0)
4121 for (int i = 0, j = wsmenu.size(); i < j; i++)
4123 webService.add(wsmenu.get(i));
4128 webService.add(me.webServiceNoServices);
4130 // TODO: move into separate menu builder class.
4131 boolean new_sspred = false;
4132 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4134 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4135 if (jws2servs != null)
4137 if (jws2servs.hasServices())
4139 jws2servs.attachWSMenuEntry(webService, me);
4140 for (Jws2Instance sv : jws2servs.getServices())
4142 if (sv.description.toLowerCase().contains("jpred"))
4144 for (JMenuItem jmi : legacyItems)
4146 jmi.setVisible(false);
4152 if (jws2servs.isRunning())
4154 JMenuItem tm = new JMenuItem(
4155 "Still discovering JABA Services");
4156 tm.setEnabled(false);
4161 build_urlServiceMenu(me.webService);
4162 build_fetchdbmenu(webService);
4163 for (JMenu item : wsmenu)
4165 if (item.getItemCount() == 0)
4167 item.setEnabled(false);
4171 item.setEnabled(true);
4174 } catch (Exception e)
4177 "Exception during web service menu building process.",
4182 } catch (Exception e)
4185 buildingMenu = false;
4192 * construct any groupURL type service menu entries.
4196 private void build_urlServiceMenu(JMenu webService)
4198 // TODO: remove this code when 2.7 is released
4199 // DEBUG - alignmentView
4201 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4202 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4204 * @Override public void actionPerformed(ActionEvent e) {
4205 * jalview.datamodel.AlignmentView
4206 * .testSelectionViews(af.viewport.getAlignment(),
4207 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4209 * }); webService.add(testAlView);
4211 // TODO: refactor to RestClient discoverer and merge menu entries for
4212 // rest-style services with other types of analysis/calculation service
4213 // SHmmr test client - still being implemented.
4214 // DEBUG - alignmentView
4216 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4219 client.attachWSMenuEntry(
4220 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4226 * Searches the alignment sequences for xRefs and builds the Show
4227 * Cross-References menu (formerly called Show Products), with database
4228 * sources for which cross-references are found (protein sources for a
4229 * nucleotide alignment and vice versa)
4231 * @return true if Show Cross-references menu should be enabled
4233 public boolean canShowProducts()
4235 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4236 AlignmentI dataset = viewport.getAlignment().getDataset();
4238 showProducts.removeAll();
4239 final boolean dna = viewport.getAlignment().isNucleotide();
4241 if (seqs == null || seqs.length == 0)
4243 // nothing to see here.
4247 boolean showp = false;
4250 List<String> ptypes = new CrossRef(seqs, dataset)
4251 .findXrefSourcesForSequences(dna);
4253 for (final String source : ptypes)
4256 final AlignFrame af = this;
4257 JMenuItem xtype = new JMenuItem(source);
4258 xtype.addActionListener(new ActionListener()
4261 public void actionPerformed(ActionEvent e)
4263 showProductsFor(af.viewport.getSequenceSelection(), dna,
4267 showProducts.add(xtype);
4269 showProducts.setVisible(showp);
4270 showProducts.setEnabled(showp);
4271 } catch (Exception e)
4274 "canShowProducts threw an exception - please report to help@jalview.org",
4282 * Finds and displays cross-references for the selected sequences (protein
4283 * products for nucleotide sequences, dna coding sequences for peptides).
4286 * the sequences to show cross-references for
4288 * true if from a nucleotide alignment (so showing proteins)
4290 * the database to show cross-references for
4292 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4293 final String source)
4295 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4300 * Construct and display a new frame containing the translation of this
4301 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4304 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4306 AlignmentI al = null;
4309 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4311 al = dna.translateCdna(codeTable);
4312 } catch (Exception ex)
4314 jalview.bin.Cache.log.error(
4315 "Exception during translation. Please report this !", ex);
4316 final String msg = MessageManager.getString(
4317 "label.error_when_translating_sequences_submit_bug_report");
4318 final String errorTitle = MessageManager
4319 .getString("label.implementation_error")
4320 + MessageManager.getString("label.translation_failed");
4321 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4322 JvOptionPane.ERROR_MESSAGE);
4325 if (al == null || al.getHeight() == 0)
4327 final String msg = MessageManager.getString(
4328 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4329 final String errorTitle = MessageManager
4330 .getString("label.translation_failed");
4331 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4332 JvOptionPane.WARNING_MESSAGE);
4336 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4337 af.setFileFormat(this.currentFileFormat);
4338 final String newTitle = MessageManager
4339 .formatMessage("label.translation_of_params", new Object[]
4340 { this.getTitle(), codeTable.getId() });
4341 af.setTitle(newTitle);
4342 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4344 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4345 viewport.openSplitFrame(af, new Alignment(seqs));
4349 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4356 * Set the file format
4360 public void setFileFormat(FileFormatI format)
4362 this.currentFileFormat = format;
4366 * Try to load a features file onto the alignment.
4369 * contents or path to retrieve file
4371 * access mode of file (see jalview.io.AlignFile)
4372 * @return true if features file was parsed correctly.
4374 public boolean parseFeaturesFile(String file, DataSourceType sourceType)
4376 return avc.parseFeaturesFile(file, sourceType,
4377 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4382 public void refreshFeatureUI(boolean enableIfNecessary)
4384 // note - currently this is only still here rather than in the controller
4385 // because of the featureSettings hard reference that is yet to be
4387 if (enableIfNecessary)
4389 viewport.setShowSequenceFeatures(true);
4390 showSeqFeatures.setSelected(true);
4396 public void dragEnter(DropTargetDragEvent evt)
4401 public void dragExit(DropTargetEvent evt)
4406 public void dragOver(DropTargetDragEvent evt)
4411 public void dropActionChanged(DropTargetDragEvent evt)
4416 public void drop(DropTargetDropEvent evt)
4418 // JAL-1552 - acceptDrop required before getTransferable call for
4419 // Java's Transferable for native dnd
4420 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4421 Transferable t = evt.getTransferable();
4422 final AlignFrame thisaf = this;
4423 final List<String> files = new ArrayList<>();
4424 List<DataSourceType> protocols = new ArrayList<>();
4428 Desktop.transferFromDropTarget(files, protocols, evt, t);
4429 } catch (Exception e)
4431 e.printStackTrace();
4435 new Thread(new Runnable()
4442 // check to see if any of these files have names matching sequences
4445 SequenceIdMatcher idm = new SequenceIdMatcher(
4446 viewport.getAlignment().getSequencesArray());
4448 * Object[] { String,SequenceI}
4450 ArrayList<Object[]> filesmatched = new ArrayList<>();
4451 ArrayList<String> filesnotmatched = new ArrayList<>();
4452 for (int i = 0; i < files.size(); i++)
4454 String file = files.get(i).toString();
4456 DataSourceType protocol = FormatAdapter.checkProtocol(file);
4457 if (protocol == DataSourceType.FILE)
4459 File fl = new File(file);
4460 pdbfn = fl.getName();
4462 else if (protocol == DataSourceType.URL)
4464 URL url = new URL(file);
4465 pdbfn = url.getFile();
4467 if (pdbfn.length() > 0)
4469 // attempt to find a match in the alignment
4470 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4471 int l = 0, c = pdbfn.indexOf(".");
4472 while (mtch == null && c != -1)
4477 } while ((c = pdbfn.indexOf(".", l)) > l);
4480 pdbfn = pdbfn.substring(0, l);
4482 mtch = idm.findAllIdMatches(pdbfn);
4486 FileFormatI type = null;
4489 type = new IdentifyFile().identify(file, protocol);
4490 } catch (Exception ex)
4494 if (type != null && type.isStructureFile())
4496 filesmatched.add(new Object[] { file, protocol, mtch });
4500 // File wasn't named like one of the sequences or wasn't a PDB
4502 filesnotmatched.add(file);
4506 if (filesmatched.size() > 0)
4508 boolean autoAssociate = Cache
4509 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4512 String msg = MessageManager.formatMessage(
4513 "label.automatically_associate_structure_files_with_sequences_same_name",
4515 { Integer.valueOf(filesmatched.size())
4517 String ttl = MessageManager.getString(
4518 "label.automatically_associate_structure_files_by_name");
4519 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4520 ttl, JvOptionPane.YES_NO_OPTION);
4521 autoAssociate = choice == JvOptionPane.YES_OPTION;
4525 for (Object[] fm : filesmatched)
4527 // try and associate
4528 // TODO: may want to set a standard ID naming formalism for
4529 // associating PDB files which have no IDs.
4530 for (SequenceI toassoc : (SequenceI[]) fm[2])
4532 PDBEntry pe = new AssociatePdbFileWithSeq()
4533 .associatePdbWithSeq((String) fm[0],
4534 (DataSourceType) fm[1], toassoc, false,
4538 System.err.println("Associated file : "
4539 + ((String) fm[0]) + " with "
4540 + toassoc.getDisplayId(true));
4544 // TODO: do we need to update overview ? only if features are
4546 alignPanel.paintAlignment(true, false);
4552 * add declined structures as sequences
4554 for (Object[] o : filesmatched)
4556 filesnotmatched.add((String) o[0]);
4560 if (filesnotmatched.size() > 0)
4562 if (assocfiles > 0 && (Cache.getDefault(
4563 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4564 || JvOptionPane.showConfirmDialog(thisaf,
4565 "<html>" + MessageManager.formatMessage(
4566 "label.ignore_unmatched_dropped_files_info",
4569 filesnotmatched.size())
4572 MessageManager.getString(
4573 "label.ignore_unmatched_dropped_files"),
4574 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4578 for (String fn : filesnotmatched)
4580 loadJalviewDataFile(fn, null, null, null);
4584 } catch (Exception ex)
4586 ex.printStackTrace();
4594 * Attempt to load a "dropped" file or URL string, by testing in turn for
4596 * <li>an Annotation file</li>
4597 * <li>a JNet file</li>
4598 * <li>a features file</li>
4599 * <li>else try to interpret as an alignment file</li>
4603 * either a filename or a URL string.
4605 public void loadJalviewDataFile(String file, DataSourceType sourceType,
4606 FileFormatI format, SequenceI assocSeq)
4610 if (sourceType == null)
4612 sourceType = FormatAdapter.checkProtocol(file);
4614 // if the file isn't identified, or not positively identified as some
4615 // other filetype (PFAM is default unidentified alignment file type) then
4616 // try to parse as annotation.
4617 boolean isAnnotation = (format == null
4618 || FileFormat.Pfam.equals(format))
4619 ? new AnnotationFile().annotateAlignmentView(viewport,
4625 // first see if its a T-COFFEE score file
4626 TCoffeeScoreFile tcf = null;
4629 tcf = new TCoffeeScoreFile(file, sourceType);
4632 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4636 new TCoffeeColourScheme(viewport.getAlignment()));
4637 isAnnotation = true;
4638 statusBar.setText(MessageManager.getString(
4639 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4643 // some problem - if no warning its probable that the ID matching
4644 // process didn't work
4645 JvOptionPane.showMessageDialog(Desktop.desktop,
4646 tcf.getWarningMessage() == null
4647 ? MessageManager.getString(
4648 "label.check_file_matches_sequence_ids_alignment")
4649 : tcf.getWarningMessage(),
4650 MessageManager.getString(
4651 "label.problem_reading_tcoffee_score_file"),
4652 JvOptionPane.WARNING_MESSAGE);
4659 } catch (Exception x)
4662 "Exception when processing data source as T-COFFEE score file",
4668 // try to see if its a JNet 'concise' style annotation file *before*
4670 // try to parse it as a features file
4673 format = new IdentifyFile().identify(file, sourceType);
4675 if (FileFormat.ScoreMatrix == format)
4677 ScoreMatrixFile sm = new ScoreMatrixFile(
4678 new FileParse(file, sourceType));
4680 // todo: i18n this message
4681 statusBar.setText(MessageManager.formatMessage(
4682 "label.successfully_loaded_matrix",
4683 sm.getMatrixName()));
4685 else if (FileFormat.Jnet.equals(format))
4687 JPredFile predictions = new JPredFile(file, sourceType);
4688 new JnetAnnotationMaker();
4689 JnetAnnotationMaker.add_annotation(predictions,
4690 viewport.getAlignment(), 0, false);
4691 viewport.getAlignment().setupJPredAlignment();
4692 isAnnotation = true;
4694 // else if (IdentifyFile.FeaturesFile.equals(format))
4695 else if (FileFormat.Features.equals(format))
4697 if (parseFeaturesFile(file, sourceType))
4699 alignPanel.paintAlignment(true, true);
4704 new FileLoader().LoadFile(viewport, file, sourceType, format);
4711 alignPanel.adjustAnnotationHeight();
4712 viewport.updateSequenceIdColours();
4713 buildSortByAnnotationScoresMenu();
4714 alignPanel.paintAlignment(true, true);
4716 } catch (Exception ex)
4718 ex.printStackTrace();
4719 } catch (OutOfMemoryError oom)
4724 } catch (Exception x)
4729 + (sourceType != null
4730 ? (sourceType == DataSourceType.PASTE
4732 : "using " + sourceType + " from "
4736 ? "(parsing as '" + format + "' file)"
4738 oom, Desktop.desktop);
4743 * Method invoked by the ChangeListener on the tabbed pane, in other words
4744 * when a different tabbed pane is selected by the user or programmatically.
4747 public void tabSelectionChanged(int index)
4751 alignPanel = alignPanels.get(index);
4752 viewport = alignPanel.av;
4753 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4754 setMenusFromViewport(viewport);
4758 * 'focus' any colour slider that is open to the selected viewport
4760 if (viewport.getConservationSelected())
4762 SliderPanel.setConservationSlider(alignPanel,
4763 viewport.getResidueShading(), alignPanel.getViewName());
4767 SliderPanel.hideConservationSlider();
4769 if (viewport.getAbovePIDThreshold())
4771 SliderPanel.setPIDSliderSource(alignPanel,
4772 viewport.getResidueShading(), alignPanel.getViewName());
4776 SliderPanel.hidePIDSlider();
4780 * If there is a frame linked to this one in a SplitPane, switch it to the
4781 * same view tab index. No infinite recursion of calls should happen, since
4782 * tabSelectionChanged() should not get invoked on setting the selected
4783 * index to an unchanged value. Guard against setting an invalid index
4784 * before the new view peer tab has been created.
4786 final AlignViewportI peer = viewport.getCodingComplement();
4789 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4790 .getAlignPanel().alignFrame;
4791 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4793 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4799 * On right mouse click on view tab, prompt for and set new view name.
4802 public void tabbedPane_mousePressed(MouseEvent e)
4804 if (e.isPopupTrigger())
4806 String msg = MessageManager.getString("label.enter_view_name");
4807 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4808 JvOptionPane.QUESTION_MESSAGE);
4812 viewport.setViewName(reply);
4813 // TODO warn if reply is in getExistingViewNames()?
4814 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4819 public AlignViewport getCurrentView()
4825 * Open the dialog for regex description parsing.
4828 protected void extractScores_actionPerformed(ActionEvent e)
4830 ParseProperties pp = new jalview.analysis.ParseProperties(
4831 viewport.getAlignment());
4832 // TODO: verify regex and introduce GUI dialog for version 2.5
4833 // if (pp.getScoresFromDescription("col", "score column ",
4834 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4836 if (pp.getScoresFromDescription("description column",
4837 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4839 buildSortByAnnotationScoresMenu();
4847 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4851 protected void showDbRefs_actionPerformed(ActionEvent e)
4853 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4859 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4863 protected void showNpFeats_actionPerformed(ActionEvent e)
4865 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4869 * find the viewport amongst the tabs in this alignment frame and close that
4874 public boolean closeView(AlignViewportI av)
4878 this.closeMenuItem_actionPerformed(false);
4881 Component[] comp = tabbedPane.getComponents();
4882 for (int i = 0; comp != null && i < comp.length; i++)
4884 if (comp[i] instanceof AlignmentPanel)
4886 if (((AlignmentPanel) comp[i]).av == av)
4889 closeView((AlignmentPanel) comp[i]);
4897 protected void build_fetchdbmenu(JMenu webService)
4899 // Temporary hack - DBRef Fetcher always top level ws entry.
4900 // TODO We probably want to store a sequence database checklist in
4901 // preferences and have checkboxes.. rather than individual sources selected
4903 final JMenu rfetch = new JMenu(
4904 MessageManager.getString("action.fetch_db_references"));
4905 rfetch.setToolTipText(MessageManager.getString(
4906 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4907 webService.add(rfetch);
4909 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4910 MessageManager.getString("option.trim_retrieved_seqs"));
4911 trimrs.setToolTipText(
4912 MessageManager.getString("label.trim_retrieved_sequences"));
4914 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4915 trimrs.addActionListener(new ActionListener()
4918 public void actionPerformed(ActionEvent e)
4920 trimrs.setSelected(trimrs.isSelected());
4921 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4922 Boolean.valueOf(trimrs.isSelected()).toString());
4926 JMenuItem fetchr = new JMenuItem(
4927 MessageManager.getString("label.standard_databases"));
4928 fetchr.setToolTipText(
4929 MessageManager.getString("label.fetch_embl_uniprot"));
4930 fetchr.addActionListener(new ActionListener()
4934 public void actionPerformed(ActionEvent e)
4936 new Thread(new Runnable()
4941 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4942 .getAlignment().isNucleotide();
4943 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4944 alignPanel.av.getSequenceSelection(),
4945 alignPanel.alignFrame, null,
4946 alignPanel.alignFrame.featureSettings, isNucleotide);
4947 dbRefFetcher.addListener(new FetchFinishedListenerI()
4950 public void finished()
4952 AlignFrame.this.setMenusForViewport();
4955 dbRefFetcher.fetchDBRefs(false);
4963 final AlignFrame me = this;
4964 new Thread(new Runnable()
4969 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
4970 .getSequenceFetcherSingleton(me);
4971 javax.swing.SwingUtilities.invokeLater(new Runnable()
4976 String[] dbclasses = sf.getOrderedSupportedSources();
4977 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
4978 // jalview.util.QuickSort.sort(otherdb, otherdb);
4979 List<DbSourceProxy> otherdb;
4980 JMenu dfetch = new JMenu();
4981 JMenu ifetch = new JMenu();
4982 JMenuItem fetchr = null;
4983 int comp = 0, icomp = 0, mcomp = 15;
4984 String mname = null;
4986 for (String dbclass : dbclasses)
4988 otherdb = sf.getSourceProxy(dbclass);
4989 // add a single entry for this class, or submenu allowing 'fetch
4991 if (otherdb == null || otherdb.size() < 1)
4995 // List<DbSourceProxy> dbs=otherdb;
4996 // otherdb=new ArrayList<DbSourceProxy>();
4997 // for (DbSourceProxy db:dbs)
4999 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5003 mname = "From " + dbclass;
5005 if (otherdb.size() == 1)
5007 final DbSourceProxy[] dassource = otherdb
5008 .toArray(new DbSourceProxy[0]);
5009 DbSourceProxy src = otherdb.get(0);
5010 fetchr = new JMenuItem(src.getDbSource());
5011 fetchr.addActionListener(new ActionListener()
5015 public void actionPerformed(ActionEvent e)
5017 new Thread(new Runnable()
5023 boolean isNucleotide = alignPanel.alignFrame
5024 .getViewport().getAlignment()
5026 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5027 alignPanel.av.getSequenceSelection(),
5028 alignPanel.alignFrame, dassource,
5029 alignPanel.alignFrame.featureSettings,
5032 .addListener(new FetchFinishedListenerI()
5035 public void finished()
5037 AlignFrame.this.setMenusForViewport();
5040 dbRefFetcher.fetchDBRefs(false);
5046 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5047 MessageManager.formatMessage(
5048 "label.fetch_retrieve_from", new Object[]
5049 { src.getDbName() })));
5055 final DbSourceProxy[] dassource = otherdb
5056 .toArray(new DbSourceProxy[0]);
5058 DbSourceProxy src = otherdb.get(0);
5059 fetchr = new JMenuItem(MessageManager
5060 .formatMessage("label.fetch_all_param", new Object[]
5061 { src.getDbSource() }));
5062 fetchr.addActionListener(new ActionListener()
5065 public void actionPerformed(ActionEvent e)
5067 new Thread(new Runnable()
5073 boolean isNucleotide = alignPanel.alignFrame
5074 .getViewport().getAlignment()
5076 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5077 alignPanel.av.getSequenceSelection(),
5078 alignPanel.alignFrame, dassource,
5079 alignPanel.alignFrame.featureSettings,
5082 .addListener(new FetchFinishedListenerI()
5085 public void finished()
5087 AlignFrame.this.setMenusForViewport();
5090 dbRefFetcher.fetchDBRefs(false);
5096 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5097 MessageManager.formatMessage(
5098 "label.fetch_retrieve_from_all_sources",
5100 { Integer.valueOf(otherdb.size())
5102 src.getDbSource(), src.getDbName() })));
5105 // and then build the rest of the individual menus
5106 ifetch = new JMenu(MessageManager.formatMessage(
5107 "label.source_from_db_source", new Object[]
5108 { src.getDbSource() }));
5110 String imname = null;
5112 for (DbSourceProxy sproxy : otherdb)
5114 String dbname = sproxy.getDbName();
5115 String sname = dbname.length() > 5
5116 ? dbname.substring(0, 5) + "..."
5118 String msname = dbname.length() > 10
5119 ? dbname.substring(0, 10) + "..."
5123 imname = MessageManager
5124 .formatMessage("label.from_msname", new Object[]
5127 fetchr = new JMenuItem(msname);
5128 final DbSourceProxy[] dassrc = { sproxy };
5129 fetchr.addActionListener(new ActionListener()
5133 public void actionPerformed(ActionEvent e)
5135 new Thread(new Runnable()
5141 boolean isNucleotide = alignPanel.alignFrame
5142 .getViewport().getAlignment()
5144 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5145 alignPanel.av.getSequenceSelection(),
5146 alignPanel.alignFrame, dassrc,
5147 alignPanel.alignFrame.featureSettings,
5150 .addListener(new FetchFinishedListenerI()
5153 public void finished()
5155 AlignFrame.this.setMenusForViewport();
5158 dbRefFetcher.fetchDBRefs(false);
5164 fetchr.setToolTipText(
5165 "<html>" + MessageManager.formatMessage(
5166 "label.fetch_retrieve_from", new Object[]
5170 if (++icomp >= mcomp || i == (otherdb.size()))
5172 ifetch.setText(MessageManager.formatMessage(
5173 "label.source_to_target", imname, sname));
5175 ifetch = new JMenu();
5183 if (comp >= mcomp || dbi >= (dbclasses.length))
5185 dfetch.setText(MessageManager.formatMessage(
5186 "label.source_to_target", mname, dbclass));
5188 dfetch = new JMenu();
5201 * Left justify the whole alignment.
5204 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5206 AlignmentI al = viewport.getAlignment();
5208 viewport.firePropertyChange("alignment", null, al);
5212 * Right justify the whole alignment.
5215 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5217 AlignmentI al = viewport.getAlignment();
5219 viewport.firePropertyChange("alignment", null, al);
5223 public void setShowSeqFeatures(boolean b)
5225 showSeqFeatures.setSelected(b);
5226 viewport.setShowSequenceFeatures(b);
5233 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5234 * awt.event.ActionEvent)
5237 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5239 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5240 alignPanel.paintAlignment(false, false);
5247 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5251 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5253 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5254 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5262 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5263 * .event.ActionEvent)
5266 protected void showGroupConservation_actionPerformed(ActionEvent e)
5268 viewport.setShowGroupConservation(showGroupConservation.getState());
5269 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5276 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5277 * .event.ActionEvent)
5280 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5282 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5283 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5290 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5291 * .event.ActionEvent)
5294 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5296 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5297 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5301 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5303 showSequenceLogo.setState(true);
5304 viewport.setShowSequenceLogo(true);
5305 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5306 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5310 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5312 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5319 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5320 * .event.ActionEvent)
5323 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5325 if (avc.makeGroupsFromSelection())
5327 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5328 alignPanel.updateAnnotation();
5329 alignPanel.paintAlignment(true,
5330 viewport.needToUpdateStructureViews());
5334 public void clearAlignmentSeqRep()
5336 // TODO refactor alignmentseqrep to controller
5337 if (viewport.getAlignment().hasSeqrep())
5339 viewport.getAlignment().setSeqrep(null);
5340 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5341 alignPanel.updateAnnotation();
5342 alignPanel.paintAlignment(true, true);
5347 protected void createGroup_actionPerformed(ActionEvent e)
5349 if (avc.createGroup())
5351 if (applyAutoAnnotationSettings.isSelected())
5353 alignPanel.updateAnnotation(true, false);
5355 alignPanel.alignmentChanged();
5360 protected void unGroup_actionPerformed(ActionEvent e)
5364 alignPanel.alignmentChanged();
5369 * make the given alignmentPanel the currently selected tab
5371 * @param alignmentPanel
5373 public void setDisplayedView(AlignmentPanel alignmentPanel)
5375 if (!viewport.getSequenceSetId()
5376 .equals(alignmentPanel.av.getSequenceSetId()))
5378 throw new Error(MessageManager.getString(
5379 "error.implementation_error_cannot_show_view_alignment_frame"));
5381 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5382 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5384 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5389 * Action on selection of menu options to Show or Hide annotations.
5392 * @param forSequences
5393 * update sequence-related annotations
5394 * @param forAlignment
5395 * update non-sequence-related annotations
5398 protected void setAnnotationsVisibility(boolean visible,
5399 boolean forSequences, boolean forAlignment)
5401 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5402 .getAlignmentAnnotation();
5407 for (AlignmentAnnotation aa : anns)
5410 * don't display non-positional annotations on an alignment
5412 if (aa.annotations == null)
5416 boolean apply = (aa.sequenceRef == null && forAlignment)
5417 || (aa.sequenceRef != null && forSequences);
5420 aa.visible = visible;
5423 alignPanel.validateAnnotationDimensions(true);
5424 alignPanel.alignmentChanged();
5428 * Store selected annotation sort order for the view and repaint.
5431 protected void sortAnnotations_actionPerformed()
5433 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5435 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5436 alignPanel.paintAlignment(false, false);
5441 * @return alignment panels in this alignment frame
5443 public List<? extends AlignmentViewPanel> getAlignPanels()
5445 // alignPanels is never null
5446 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5451 * Open a new alignment window, with the cDNA associated with this (protein)
5452 * alignment, aligned as is the protein.
5454 protected void viewAsCdna_actionPerformed()
5456 // TODO no longer a menu action - refactor as required
5457 final AlignmentI alignment = getViewport().getAlignment();
5458 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5459 if (mappings == null)
5463 List<SequenceI> cdnaSeqs = new ArrayList<>();
5464 for (SequenceI aaSeq : alignment.getSequences())
5466 for (AlignedCodonFrame acf : mappings)
5468 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5472 * There is a cDNA mapping for this protein sequence - add to new
5473 * alignment. It will share the same dataset sequence as other mapped
5474 * cDNA (no new mappings need to be created).
5476 final Sequence newSeq = new Sequence(dnaSeq);
5477 newSeq.setDatasetSequence(dnaSeq);
5478 cdnaSeqs.add(newSeq);
5482 if (cdnaSeqs.size() == 0)
5484 // show a warning dialog no mapped cDNA
5487 AlignmentI cdna = new Alignment(
5488 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5489 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5490 AlignFrame.DEFAULT_HEIGHT);
5491 cdna.alignAs(alignment);
5492 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5494 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5495 AlignFrame.DEFAULT_HEIGHT);
5499 * Set visibility of dna/protein complement view (available when shown in a
5505 protected void showComplement_actionPerformed(boolean show)
5507 SplitContainerI sf = getSplitViewContainer();
5510 sf.setComplementVisible(this, show);
5515 * Generate the reverse (optionally complemented) of the selected sequences,
5516 * and add them to the alignment
5519 protected void showReverse_actionPerformed(boolean complement)
5521 AlignmentI al = null;
5524 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5525 al = dna.reverseCdna(complement);
5526 viewport.addAlignment(al, "");
5527 addHistoryItem(new EditCommand(
5528 MessageManager.getString("label.add_sequences"), Action.PASTE,
5529 al.getSequencesArray(), 0, al.getWidth(),
5530 viewport.getAlignment()));
5531 } catch (Exception ex)
5533 System.err.println(ex.getMessage());
5539 * Try to run a script in the Groovy console, having first ensured that this
5540 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5541 * be targeted at this alignment.
5544 protected void runGroovy_actionPerformed()
5546 Jalview.setCurrentAlignFrame(this);
5547 groovy.ui.Console console = Desktop.getGroovyConsole();
5548 if (console != null)
5552 console.runScript();
5553 } catch (Exception ex)
5555 System.err.println((ex.toString()));
5556 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5557 MessageManager.getString("label.couldnt_run_groovy_script"),
5558 MessageManager.getString("label.groovy_support_failed"),
5559 JvOptionPane.ERROR_MESSAGE);
5564 System.err.println("Can't run Groovy script as console not found");
5569 * Hides columns containing (or not containing) a specified feature, provided
5570 * that would not leave all columns hidden
5572 * @param featureType
5573 * @param columnsContaining
5576 public boolean hideFeatureColumns(String featureType,
5577 boolean columnsContaining)
5579 boolean notForHiding = avc.markColumnsContainingFeatures(
5580 columnsContaining, false, false, featureType);
5583 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5584 false, featureType))
5586 getViewport().hideSelectedColumns();
5594 protected void selectHighlightedColumns_actionPerformed(
5595 ActionEvent actionEvent)
5597 // include key modifier check in case user selects from menu
5598 avc.markHighlightedColumns(
5599 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5600 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5601 | ActionEvent.CTRL_MASK)) != 0);
5605 * Rebuilds the Colour menu, including any user-defined colours which have
5606 * been loaded either on startup or during the session
5608 public void buildColourMenu()
5610 colourMenu.removeAll();
5612 colourMenu.add(applyToAllGroups);
5613 colourMenu.add(textColour);
5614 colourMenu.addSeparator();
5616 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5617 viewport.getAlignment(), false);
5619 colourMenu.add(annotationColour);
5620 bg.add(annotationColour);
5621 colourMenu.addSeparator();
5622 colourMenu.add(conservationMenuItem);
5623 colourMenu.add(modifyConservation);
5624 colourMenu.add(abovePIDThreshold);
5625 colourMenu.add(modifyPID);
5627 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5628 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5632 * Open a dialog (if not already open) that allows the user to select and
5633 * calculate PCA or Tree analysis
5635 protected void openTreePcaDialog()
5637 if (alignPanel.getCalculationDialog() == null)
5639 new CalculationChooser(AlignFrame.this);
5644 protected void loadVcf_actionPerformed()
5646 JalviewFileChooser chooser = new JalviewFileChooser(
5647 Cache.getProperty("LAST_DIRECTORY"));
5648 chooser.setFileView(new JalviewFileView());
5649 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5650 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5652 int value = chooser.showOpenDialog(null);
5654 if (value == JalviewFileChooser.APPROVE_OPTION)
5656 String choice = chooser.getSelectedFile().getPath();
5657 Cache.setProperty("LAST_DIRECTORY", choice);
5658 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5659 new VCFLoader(choice).loadVCF(seqs, this);
5665 class PrintThread extends Thread
5669 public PrintThread(AlignmentPanel ap)
5674 static PageFormat pf;
5679 PrinterJob printJob = PrinterJob.getPrinterJob();
5683 printJob.setPrintable(ap, pf);
5687 printJob.setPrintable(ap);
5690 if (printJob.printDialog())
5695 } catch (Exception PrintException)
5697 PrintException.printStackTrace();