2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.analysis.CrossRef;
26 import jalview.analysis.Dna;
27 import jalview.analysis.ParseProperties;
28 import jalview.analysis.SequenceIdMatcher;
29 import jalview.api.AlignExportSettingI;
30 import jalview.api.AlignViewControllerGuiI;
31 import jalview.api.AlignViewControllerI;
32 import jalview.api.AlignViewportI;
33 import jalview.api.AlignmentViewPanel;
34 import jalview.api.FeatureSettingsControllerI;
35 import jalview.api.SplitContainerI;
36 import jalview.api.ViewStyleI;
37 import jalview.api.analysis.SimilarityParamsI;
38 import jalview.bin.Cache;
39 import jalview.bin.Jalview;
40 import jalview.commands.CommandI;
41 import jalview.commands.EditCommand;
42 import jalview.commands.EditCommand.Action;
43 import jalview.commands.OrderCommand;
44 import jalview.commands.RemoveGapColCommand;
45 import jalview.commands.RemoveGapsCommand;
46 import jalview.commands.SlideSequencesCommand;
47 import jalview.commands.TrimRegionCommand;
48 import jalview.datamodel.AlignedCodonFrame;
49 import jalview.datamodel.Alignment;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentExportData;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.AlignmentOrder;
54 import jalview.datamodel.AlignmentView;
55 import jalview.datamodel.ColumnSelection;
56 import jalview.datamodel.HiddenColumns;
57 import jalview.datamodel.HiddenSequences;
58 import jalview.datamodel.PDBEntry;
59 import jalview.datamodel.SeqCigar;
60 import jalview.datamodel.Sequence;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.datamodel.SequenceI;
63 import jalview.gui.ColourMenuHelper.ColourChangeListener;
64 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
65 import jalview.io.AlignmentProperties;
66 import jalview.io.AnnotationFile;
67 import jalview.io.BioJsHTMLOutput;
68 import jalview.io.DataSourceType;
69 import jalview.io.FileFormat;
70 import jalview.io.FileFormatI;
71 import jalview.io.FileFormats;
72 import jalview.io.FileLoader;
73 import jalview.io.FileParse;
74 import jalview.io.FormatAdapter;
75 import jalview.io.HtmlSvgOutput;
76 import jalview.io.IdentifyFile;
77 import jalview.io.JPredFile;
78 import jalview.io.JalviewFileChooser;
79 import jalview.io.JalviewFileView;
80 import jalview.io.JnetAnnotationMaker;
81 import jalview.io.NewickFile;
82 import jalview.io.ScoreMatrixFile;
83 import jalview.io.TCoffeeScoreFile;
84 import jalview.io.vcf.VCFLoader;
85 import jalview.jbgui.GAlignFrame;
86 import jalview.schemes.ColourSchemeI;
87 import jalview.schemes.ColourSchemes;
88 import jalview.schemes.ResidueColourScheme;
89 import jalview.schemes.TCoffeeColourScheme;
90 import jalview.util.MessageManager;
91 import jalview.viewmodel.AlignmentViewport;
92 import jalview.viewmodel.ViewportRanges;
93 import jalview.ws.DBRefFetcher;
94 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
95 import jalview.ws.jws1.Discoverer;
96 import jalview.ws.jws2.Jws2Discoverer;
97 import jalview.ws.jws2.jabaws2.Jws2Instance;
98 import jalview.ws.seqfetcher.DbSourceProxy;
100 import java.awt.BorderLayout;
101 import java.awt.Component;
102 import java.awt.Rectangle;
103 import java.awt.Toolkit;
104 import java.awt.datatransfer.Clipboard;
105 import java.awt.datatransfer.DataFlavor;
106 import java.awt.datatransfer.StringSelection;
107 import java.awt.datatransfer.Transferable;
108 import java.awt.dnd.DnDConstants;
109 import java.awt.dnd.DropTargetDragEvent;
110 import java.awt.dnd.DropTargetDropEvent;
111 import java.awt.dnd.DropTargetEvent;
112 import java.awt.dnd.DropTargetListener;
113 import java.awt.event.ActionEvent;
114 import java.awt.event.ActionListener;
115 import java.awt.event.FocusAdapter;
116 import java.awt.event.FocusEvent;
117 import java.awt.event.ItemEvent;
118 import java.awt.event.ItemListener;
119 import java.awt.event.KeyAdapter;
120 import java.awt.event.KeyEvent;
121 import java.awt.event.MouseEvent;
122 import java.awt.print.PageFormat;
123 import java.awt.print.PrinterJob;
124 import java.beans.PropertyChangeEvent;
125 import java.beans.PropertyChangeListener;
127 import java.io.FileWriter;
128 import java.io.PrintWriter;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Deque;
133 import java.util.Enumeration;
134 import java.util.Hashtable;
135 import java.util.List;
136 import java.util.Vector;
138 import javax.swing.JCheckBoxMenuItem;
139 import javax.swing.JEditorPane;
140 import javax.swing.JFileChooser;
141 import javax.swing.JInternalFrame;
142 import javax.swing.JLayeredPane;
143 import javax.swing.JMenu;
144 import javax.swing.JMenuItem;
145 import javax.swing.JScrollPane;
146 import javax.swing.SwingUtilities;
152 * @version $Revision$
154 public class AlignFrame extends GAlignFrame implements DropTargetListener,
155 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener,
156 PropertyChangeListener
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;
187 * Creates a new AlignFrame object with specific width and height.
193 public AlignFrame(AlignmentI al, int width, int height)
195 this(al, null, width, height);
199 * Creates a new AlignFrame object with specific width, height and
205 * @param sequenceSetId
207 public AlignFrame(AlignmentI al, int width, int height,
208 String sequenceSetId)
210 this(al, null, width, height, sequenceSetId);
214 * Creates a new AlignFrame object with specific width, height and
220 * @param sequenceSetId
223 public AlignFrame(AlignmentI al, int width, int height,
224 String sequenceSetId, String viewId)
226 this(al, null, width, height, sequenceSetId, viewId);
230 * new alignment window with hidden columns
234 * @param hiddenColumns
235 * ColumnSelection or null
237 * Width of alignment frame
241 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
244 this(al, hiddenColumns, width, height, null);
248 * Create alignment frame for al with hiddenColumns, a specific width and
249 * height, and specific sequenceId
252 * @param hiddenColumns
255 * @param sequenceSetId
258 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
259 int height, String sequenceSetId)
261 this(al, hiddenColumns, width, height, sequenceSetId, null);
265 * Create alignment frame for al with hiddenColumns, a specific width and
266 * height, and specific sequenceId
269 * @param hiddenColumns
272 * @param sequenceSetId
277 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
278 int height, String sequenceSetId, String viewId)
280 setSize(width, height);
282 if (al.getDataset() == null)
287 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
289 alignPanel = new AlignmentPanel(this, viewport);
291 addAlignmentPanel(alignPanel, true);
295 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
296 HiddenColumns hiddenColumns, int width, int height)
298 setSize(width, height);
300 if (al.getDataset() == null)
305 viewport = new AlignViewport(al, hiddenColumns);
307 if (hiddenSeqs != null && hiddenSeqs.length > 0)
309 viewport.hideSequence(hiddenSeqs);
311 alignPanel = new AlignmentPanel(this, viewport);
312 addAlignmentPanel(alignPanel, true);
317 * Make a new AlignFrame from existing alignmentPanels
324 public AlignFrame(AlignmentPanel ap)
328 addAlignmentPanel(ap, false);
333 public void propertyChange(PropertyChangeEvent evt)
335 Desktop.getDesktop().propertyChange(evt);
342 * @return true if we have any features
345 protected boolean haveAlignmentFeatures() {
346 AlignmentI alignment = getViewport().getAlignment();
348 for (int i = 0; i < alignment.getHeight(); i++)
350 SequenceI seq = alignment.getSequenceAt(i);
351 for (String group : seq.getFeatures().getFeatureGroups(true))
353 if (group != null)return true;
360 * initalise the alignframe from the underlying viewport data and the
365 if (!Jalview.isHeadlessMode())
367 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
370 avc = new jalview.controller.AlignViewController(this, viewport,
372 if (viewport.getAlignmentConservationAnnotation() == null)
374 // BLOSUM62Colour.setEnabled(false);
375 conservationMenuItem.setEnabled(false);
376 modifyConservation.setEnabled(false);
377 // PIDColour.setEnabled(false);
378 // abovePIDThreshold.setEnabled(false);
379 // modifyPID.setEnabled(false);
382 String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT",
385 if (sortby.equals("Id"))
387 sortIDMenuItem_actionPerformed(null);
389 else if (sortby.equals("Pairwise Identity"))
391 sortPairwiseMenuItem_actionPerformed(null);
395 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
397 setMenusFromViewport(viewport);
398 buildSortByAnnotationScoresMenu();
399 calculateTree.addActionListener(new ActionListener()
403 public void actionPerformed(ActionEvent e)
410 if (Desktop.desktop != null)
412 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
414 * BH 2018 ignore service listeners
420 addServiceListeners();
425 if (viewport.getWrapAlignment())
427 wrapMenuItem_actionPerformed(null);
430 if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW", false))
432 this.overviewMenuItem_actionPerformed(null);
437 final List<AlignmentPanel> selviews = new ArrayList<>();
438 final List<AlignmentPanel> origview = new ArrayList<>();
439 final String menuLabel = MessageManager
440 .getString("label.copy_format_from");
441 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
442 new ViewSetProvider()
446 public AlignmentPanel[] getAllAlignmentPanels()
449 origview.add(alignPanel);
450 // make an array of all alignment panels except for this one
451 List<AlignmentPanel> aps = new ArrayList<>(
452 Arrays.asList(Desktop.getAlignmentPanels(null)));
453 aps.remove(AlignFrame.this.alignPanel);
454 return aps.toArray(new AlignmentPanel[aps.size()]);
456 }, selviews, new ItemListener()
460 public void itemStateChanged(ItemEvent e)
462 if (origview.size() > 0)
464 final AlignmentPanel ap = origview.get(0);
467 * Copy the ViewStyle of the selected panel to 'this one'.
468 * Don't change value of 'scaleProteinAsCdna' unless copying
471 ViewStyleI vs = selviews.get(0).getAlignViewport()
473 boolean fromSplitFrame = selviews.get(0)
474 .getAlignViewport().getCodingComplement() != null;
477 vs.setScaleProteinAsCdna(ap.getAlignViewport()
478 .getViewStyle().isScaleProteinAsCdna());
480 ap.getAlignViewport().setViewStyle(vs);
483 * Also rescale ViewStyle of SplitFrame complement if there is
484 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
485 * the whole ViewStyle (allow cDNA protein to have different
488 AlignViewportI complement = ap.getAlignViewport()
489 .getCodingComplement();
490 if (complement != null && vs.isScaleProteinAsCdna())
492 AlignFrame af = Desktop.getAlignFrameFor(complement);
493 ((SplitFrame) af.getSplitViewContainer())
495 af.setMenusForViewport();
499 ap.setSelected(true);
500 ap.alignFrame.setMenusForViewport();
505 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
506 .indexOf("devel") > -1
507 || Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase()
508 .indexOf("test") > -1)
510 formatMenu.add(vsel);
512 addFocusListener(new FocusAdapter()
515 public void focusGained(FocusEvent e)
517 Jalview.setCurrentAlignFrame(AlignFrame.this);
524 * Change the filename and format for the alignment, and enable the 'reload'
525 * button functionality.
532 public void setFileName(String file, FileFormatI format)
535 setFileFormat(format);
536 reload.setEnabled(true);
540 * JavaScript will have this, maybe others. More dependable than a file name
541 * and maintains a reference to the actual bytes loaded.
545 public void setFileObject(File file) {
546 this.fileObject = file;
550 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
553 void addKeyListener()
555 addKeyListener(new KeyAdapter()
558 public void keyPressed(KeyEvent evt)
560 if (viewport.cursorMode
561 && ((evt.getKeyCode() >= KeyEvent.VK_0
562 && evt.getKeyCode() <= KeyEvent.VK_9)
563 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
564 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
565 && Character.isDigit(evt.getKeyChar()))
567 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
570 switch (evt.getKeyCode())
573 case 27: // escape key
574 deselectAllSequenceMenuItem_actionPerformed(null);
578 case KeyEvent.VK_DOWN:
579 if (evt.isAltDown() || !viewport.cursorMode)
581 moveSelectedSequences(false);
583 if (viewport.cursorMode)
585 alignPanel.getSeqPanel().moveCursor(0, 1);
590 if (evt.isAltDown() || !viewport.cursorMode)
592 moveSelectedSequences(true);
594 if (viewport.cursorMode)
596 alignPanel.getSeqPanel().moveCursor(0, -1);
601 case KeyEvent.VK_LEFT:
602 if (evt.isAltDown() || !viewport.cursorMode)
604 slideSequences(false,
605 alignPanel.getSeqPanel().getKeyboardNo1());
609 alignPanel.getSeqPanel().moveCursor(-1, 0);
614 case KeyEvent.VK_RIGHT:
615 if (evt.isAltDown() || !viewport.cursorMode)
617 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
621 alignPanel.getSeqPanel().moveCursor(1, 0);
625 case KeyEvent.VK_SPACE:
626 if (viewport.cursorMode)
628 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
629 || evt.isShiftDown() || evt.isAltDown());
633 // case KeyEvent.VK_A:
634 // if (viewport.cursorMode)
636 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
637 // //System.out.println("A");
641 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
642 * System.out.println("closing bracket"); } break;
644 case KeyEvent.VK_DELETE:
645 case KeyEvent.VK_BACK_SPACE:
646 if (!viewport.cursorMode)
648 cut_actionPerformed(null);
652 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
653 || evt.isShiftDown() || evt.isAltDown());
659 if (viewport.cursorMode)
661 alignPanel.getSeqPanel().setCursorRow();
665 if (viewport.cursorMode && !evt.isControlDown())
667 alignPanel.getSeqPanel().setCursorColumn();
671 if (viewport.cursorMode)
673 alignPanel.getSeqPanel().setCursorPosition();
677 case KeyEvent.VK_ENTER:
678 case KeyEvent.VK_COMMA:
679 if (viewport.cursorMode)
681 alignPanel.getSeqPanel().setCursorRowAndColumn();
686 if (viewport.cursorMode)
688 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
692 if (viewport.cursorMode)
694 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
699 viewport.cursorMode = !viewport.cursorMode;
700 statusBar.setText(MessageManager
701 .formatMessage("label.keyboard_editing_mode", new String[]
702 { (viewport.cursorMode ? "on" : "off") }));
703 if (viewport.cursorMode)
705 ViewportRanges ranges = viewport.getRanges();
706 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
708 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
711 alignPanel.getSeqPanel().seqCanvas.repaint();
717 Help.showHelpWindow();
718 } catch (Exception ex)
720 ex.printStackTrace();
725 boolean toggleSeqs = !evt.isControlDown();
726 boolean toggleCols = !evt.isShiftDown();
727 toggleHiddenRegions(toggleSeqs, toggleCols);
732 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
733 boolean modifyExisting = true; // always modify, don't clear
734 // evt.isShiftDown();
735 boolean invertHighlighted = evt.isAltDown();
736 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
740 case KeyEvent.VK_PAGE_UP:
741 viewport.getRanges().pageUp();
743 case KeyEvent.VK_PAGE_DOWN:
744 viewport.getRanges().pageDown();
750 public void keyReleased(KeyEvent evt)
752 switch (evt.getKeyCode())
754 case KeyEvent.VK_LEFT:
755 if (evt.isAltDown() || !viewport.cursorMode)
757 viewport.firePropertyChange("alignment", null,
758 viewport.getAlignment().getSequences());
762 case KeyEvent.VK_RIGHT:
763 if (evt.isAltDown() || !viewport.cursorMode)
765 viewport.firePropertyChange("alignment", null,
766 viewport.getAlignment().getSequences());
774 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
776 ap.alignFrame = this;
777 avc = new jalview.controller.AlignViewController(this, viewport,
782 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
784 int aSize = alignPanels.size();
786 tabbedPane.setVisible(aSize > 1 || ap.av.viewName != null);
788 if (aSize == 1 && ap.av.viewName == null)
790 this.getContentPane().add(ap, BorderLayout.CENTER);
796 setInitialTabVisible();
799 expandViews.setEnabled(true);
800 gatherViews.setEnabled(true);
801 tabbedPane.addTab(ap.av.viewName, ap);
803 ap.setVisible(false);
808 if (ap.av.isPadGaps())
810 ap.av.getAlignment().padGaps();
812 ap.av.updateConservation(ap);
813 ap.av.updateConsensus(ap);
814 ap.av.updateStrucConsensus(ap);
818 public void setInitialTabVisible()
820 expandViews.setEnabled(true);
821 gatherViews.setEnabled(true);
822 tabbedPane.setVisible(true);
823 AlignmentPanel first = alignPanels.get(0);
824 tabbedPane.addTab(first.av.viewName, first);
825 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
828 public AlignViewport getViewport()
833 /* Set up intrinsic listeners for dynamically generated GUI bits. */
834 private void addServiceListeners()
836 final java.beans.PropertyChangeListener thisListener;
837 Desktop.instance.addJalviewPropertyChangeListener("services",
838 thisListener = new java.beans.PropertyChangeListener()
841 public void propertyChange(PropertyChangeEvent evt)
843 // // System.out.println("Discoverer property change.");
844 // if (evt.getPropertyName().equals("services"))
846 SwingUtilities.invokeLater(new Runnable()
853 "Rebuild WS Menu for service change");
854 BuildWebServiceMenu();
861 addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
864 public void internalFrameClosed(
865 javax.swing.event.InternalFrameEvent evt)
867 // System.out.println("deregistering discoverer listener");
868 Desktop.instance.removeJalviewPropertyChangeListener("services",
870 closeMenuItem_actionPerformed(true);
873 // Finally, build the menu once to get current service state
874 new Thread(new Runnable()
879 BuildWebServiceMenu();
885 * Configure menu items that vary according to whether the alignment is
886 * nucleotide or protein
888 public void setGUINucleotide()
890 AlignmentI al = getViewport().getAlignment();
891 boolean nucleotide = al.isNucleotide();
893 loadVcf.setVisible(nucleotide);
894 showTranslation.setVisible(nucleotide);
895 showReverse.setVisible(nucleotide);
896 showReverseComplement.setVisible(nucleotide);
897 conservationMenuItem.setEnabled(!nucleotide);
899 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
900 showGroupConservation.setEnabled(!nucleotide);
902 showComplementMenuItem
903 .setText(nucleotide ? MessageManager.getString("label.protein")
904 : MessageManager.getString("label.nucleotide"));
908 * set up menus for the current viewport. This may be called after any
909 * operation that affects the data in the current view (selection changed,
910 * etc) to update the menus to reflect the new state.
913 public void setMenusForViewport()
915 setMenusFromViewport(viewport);
919 * Need to call this method when tabs are selected for multiple views, or when
920 * loading from Jalview2XML.java
925 void setMenusFromViewport(AlignViewport av)
927 padGapsMenuitem.setSelected(av.isPadGaps());
928 colourTextMenuItem.setSelected(av.isShowColourText());
929 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
930 modifyPID.setEnabled(abovePIDThreshold.isSelected());
931 conservationMenuItem.setSelected(av.getConservationSelected());
932 modifyConservation.setEnabled(conservationMenuItem.isSelected());
933 seqLimits.setSelected(av.getShowJVSuffix());
934 idRightAlign.setSelected(av.isRightAlignIds());
935 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
936 renderGapsMenuItem.setSelected(av.isRenderGaps());
937 wrapMenuItem.setSelected(av.getWrapAlignment());
938 scaleAbove.setVisible(av.getWrapAlignment());
939 scaleLeft.setVisible(av.getWrapAlignment());
940 scaleRight.setVisible(av.getWrapAlignment());
941 annotationPanelMenuItem.setState(av.isShowAnnotation());
943 * Show/hide annotations only enabled if annotation panel is shown
945 showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
946 hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
947 showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
948 hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
949 viewBoxesMenuItem.setSelected(av.getShowBoxes());
950 viewTextMenuItem.setSelected(av.getShowText());
951 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
952 showGroupConsensus.setSelected(av.isShowGroupConsensus());
953 showGroupConservation.setSelected(av.isShowGroupConservation());
954 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
955 showSequenceLogo.setSelected(av.isShowSequenceLogo());
956 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
958 ColourMenuHelper.setColourSelected(colourMenu,
959 av.getGlobalColourScheme());
961 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
962 hiddenMarkers.setState(av.getShowHiddenMarkers());
963 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
964 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
965 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
966 autoCalculate.setSelected(av.autoCalculateConsensus);
967 sortByTree.setSelected(av.sortByTree);
968 listenToViewSelections.setSelected(av.followSelection);
970 showProducts.setEnabled(canShowProducts());
971 setGroovyEnabled(Desktop.getGroovyConsole() != null);
977 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
981 public void setGroovyEnabled(boolean b)
983 runGroovy.setEnabled(b);
986 private IProgressIndicator progressBar;
991 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
994 public void setProgressBar(String message, long id)
996 progressBar.setProgressBar(message, id);
1000 public void registerHandler(final long id,
1001 final IProgressIndicatorHandler handler)
1003 progressBar.registerHandler(id, handler);
1008 * @return true if any progress bars are still active
1011 public boolean operationInProgress()
1013 return progressBar.operationInProgress();
1017 public void setStatus(String text)
1019 statusBar.setText(text);
1023 * Added so Castor Mapping file can obtain Jalview Version
1025 public String getVersion()
1027 return jalview.bin.Cache.getProperty("VERSION");
1030 public FeatureRenderer getFeatureRenderer()
1032 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1036 public void fetchSequence_actionPerformed(ActionEvent e)
1038 new jalview.gui.SequenceFetcher(this);
1042 public void addFromFile_actionPerformed(ActionEvent e)
1044 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1048 public void reload_actionPerformed(ActionEvent e)
1050 if (fileName != null)
1052 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1053 // originating file's format
1054 // TODO: work out how to recover feature settings for correct view(s) when
1055 // file is reloaded.
1056 if (FileFormat.Jalview.equals(currentFileFormat))
1058 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1059 for (int i = 0; i < frames.length; i++)
1061 if (frames[i] instanceof AlignFrame && frames[i] != this
1062 && ((AlignFrame) frames[i]).fileName != null
1063 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1067 frames[i].setSelected(true);
1068 Desktop.instance.closeAssociatedWindows();
1069 } catch (java.beans.PropertyVetoException ex)
1075 Desktop.instance.closeAssociatedWindows();
1077 FileLoader loader = new FileLoader();
1078 DataSourceType protocol = fileName.startsWith("http:")
1079 ? DataSourceType.URL : DataSourceType.FILE;
1080 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1084 Rectangle bounds = this.getBounds();
1086 FileLoader loader = new FileLoader();
1088 AlignFrame newframe = null;
1090 if (fileObject == null)
1093 DataSourceType protocol = (fileName.startsWith("http:")
1094 ? DataSourceType.URL : DataSourceType.FILE);
1095 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1100 newframe = loader.LoadFileWaitTillLoaded(fileObject, DataSourceType.FILE, currentFileFormat);
1103 newframe.setBounds(bounds);
1104 if (featureSettings != null && featureSettings.isShowing())
1106 final Rectangle fspos = featureSettings.frame.getBounds();
1107 // TODO: need a 'show feature settings' function that takes bounds -
1108 // need to refactor Desktop.addFrame
1109 newframe.featureSettings_actionPerformed(null);
1110 final FeatureSettings nfs = newframe.featureSettings;
1111 SwingUtilities.invokeLater(new Runnable()
1116 nfs.frame.setBounds(fspos);
1119 this.featureSettings.close();
1120 this.featureSettings = null;
1122 this.closeMenuItem_actionPerformed(true);
1128 public void addFromText_actionPerformed(ActionEvent e)
1131 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1135 public void addFromURL_actionPerformed(ActionEvent e)
1137 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1141 public void save_actionPerformed(ActionEvent e)
1143 if (fileName == null || (currentFileFormat == null)
1144 || fileName.startsWith("http"))
1146 saveAs_actionPerformed(null);
1150 saveAlignment(fileName, currentFileFormat);
1161 public void saveAs_actionPerformed(ActionEvent e)
1163 // TODO: JAL-3048 JalviewFileChooser - Save option
1165 String format = currentFileFormat == null ? null
1166 : currentFileFormat.getName();
1167 JalviewFileChooser chooser = JalviewFileChooser
1168 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1170 chooser.setFileView(new JalviewFileView());
1171 chooser.setDialogTitle(
1172 MessageManager.getString("label.save_alignment_to_file"));
1173 chooser.setToolTipText(MessageManager.getString("action.save"));
1175 int value = chooser.showSaveDialog(this);
1178 if (value == JalviewFileChooser.APPROVE_OPTION)
1180 currentFileFormat = chooser.getSelectedFormat();
1181 while (currentFileFormat == null)
1183 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1184 MessageManager.getString(
1185 "label.select_file_format_before_saving"),
1186 MessageManager.getString("label.file_format_not_specified"),
1187 JvOptionPane.WARNING_MESSAGE);
1188 currentFileFormat = chooser.getSelectedFormat();
1189 value = chooser.showSaveDialog(this);
1190 if (value != JalviewFileChooser.APPROVE_OPTION)
1196 fileName = chooser.getSelectedFile().getPath();
1198 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1200 Cache.setProperty("LAST_DIRECTORY", fileName);
1201 saveAlignment(fileName, currentFileFormat);
1205 public boolean saveAlignment(String file, FileFormatI format)
1207 boolean success = true;
1209 if (FileFormat.Jalview.equals(format))
1211 String shortName = title;
1213 if (shortName.indexOf(java.io.File.separatorChar) > -1)
1215 shortName = shortName.substring(
1216 shortName.lastIndexOf(java.io.File.separatorChar) + 1);
1219 success = new Jalview2XML().saveAlignment(this, file, shortName);
1221 statusBar.setText(MessageManager.formatMessage(
1222 "label.successfully_saved_to_file_in_format", new Object[]
1223 { fileName, format }));
1228 AlignmentExportData exportData = getAlignmentForExport(format,
1230 if (exportData.getSettings().isCancelled())
1234 FormatAdapter f = new FormatAdapter(alignPanel,
1235 exportData.getSettings());
1236 String output = f.formatSequences(format, exportData.getAlignment(), // class
1240 // occur in the distant future
1241 exportData.getOmitHidden(), exportData.getStartEndPostions(),
1242 f.getCacheSuffixDefault(format),
1243 viewport.getAlignment().getHiddenColumns());
1253 PrintWriter out = new PrintWriter(new FileWriter(file));
1257 this.setTitle(file);
1258 statusBar.setText(MessageManager.formatMessage(
1259 "label.successfully_saved_to_file_in_format", new Object[]
1260 { fileName, format.getName() }));
1261 } catch (Exception ex)
1264 ex.printStackTrace();
1271 JvOptionPane.showInternalMessageDialog(this, MessageManager
1272 .formatMessage("label.couldnt_save_file", new Object[]
1274 MessageManager.getString("label.error_saving_file"),
1275 JvOptionPane.WARNING_MESSAGE);
1281 private void warningMessage(String warning, String title)
1283 if (new jalview.util.Platform().isHeadless())
1285 System.err.println("Warning: " + title + "\nWarning: " + warning);
1290 JvOptionPane.showInternalMessageDialog(this, warning, title,
1291 JvOptionPane.WARNING_MESSAGE);
1303 protected void outputText_actionPerformed(ActionEvent e)
1305 FileFormatI fileFormat = FileFormats.getInstance()
1306 .forName(e.getActionCommand());
1307 AlignmentExportData exportData = getAlignmentForExport(fileFormat,
1309 if (exportData.getSettings().isCancelled())
1313 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1314 cap.setForInput(null);
1317 FileFormatI format = fileFormat;
1318 cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
1319 .formatSequences(format, exportData.getAlignment(),
1320 exportData.getOmitHidden(),
1321 exportData.getStartEndPostions(),
1322 viewport.getAlignment().getHiddenColumns()));
1323 Desktop.addInternalFrame(cap, MessageManager
1324 .formatMessage("label.alignment_output_command", new Object[]
1325 { e.getActionCommand() }), 600, 500);
1326 } catch (OutOfMemoryError oom)
1328 new OOMWarning("Outputting alignment as " + e.getActionCommand(),
1335 public static AlignmentExportData getAlignmentForExport(
1336 FileFormatI format, AlignViewportI viewport,
1337 AlignExportSettingI exportSettings)
1339 AlignmentI alignmentToExport = null;
1340 AlignExportSettingI settings = exportSettings;
1341 String[] omitHidden = null;
1343 HiddenSequences hiddenSeqs = viewport.getAlignment()
1344 .getHiddenSequences();
1346 alignmentToExport = viewport.getAlignment();
1348 boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
1349 if (settings == null)
1351 settings = new AlignExportSettings(hasHiddenSeqs,
1352 viewport.hasHiddenColumns(), format);
1354 // settings.isExportAnnotations();
1356 if (viewport.hasHiddenColumns() && !settings.isExportHiddenColumns())
1358 omitHidden = viewport.getViewAsString(false,
1359 settings.isExportHiddenSequences());
1362 int[] alignmentStartEnd = new int[2];
1363 if (hasHiddenSeqs && settings.isExportHiddenSequences())
1365 alignmentToExport = hiddenSeqs.getFullAlignment();
1369 alignmentToExport = viewport.getAlignment();
1371 alignmentStartEnd = viewport.getAlignment().getHiddenColumns()
1372 .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
1373 AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
1374 omitHidden, alignmentStartEnd, settings);
1385 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1387 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1388 htmlSVG.exportHTML(null);
1392 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1394 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1395 bjs.exportHTML(null);
1398 public void createImageMap(File file, String image)
1400 alignPanel.makePNGImageMap(file, image);
1410 public void createPNG(File f)
1412 alignPanel.makePNG(f);
1422 public void createEPS(File f)
1424 alignPanel.makeEPS(f);
1428 public void createSVG(File f)
1430 alignPanel.makeSVG(f);
1434 public void pageSetup_actionPerformed(ActionEvent e)
1436 PrinterJob printJob = PrinterJob.getPrinterJob();
1437 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1447 public void printMenuItem_actionPerformed(ActionEvent e)
1449 // Putting in a thread avoids Swing painting problems
1450 PrintThread thread = new PrintThread(alignPanel);
1455 public void exportFeatures_actionPerformed(ActionEvent e)
1457 new AnnotationExporter(alignPanel).exportFeatures();
1461 public void exportAnnotations_actionPerformed(ActionEvent e)
1463 new AnnotationExporter(alignPanel).exportAnnotations();
1467 public void associatedData_actionPerformed(ActionEvent e)
1469 JalviewFileChooser chooser = new JalviewFileChooser(
1470 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1471 chooser.setFileView(new JalviewFileView());
1472 chooser.setDialogTitle(
1473 MessageManager.getString("label.load_jalview_annotations"));
1474 chooser.setToolTipText(
1475 MessageManager.getString("label.load_jalview_annotations"));
1477 Desktop.getDesktop().dialogData = new Object[] { "SelectedFile",
1484 Object[] data = Desktop.getDesktop().dialogData;
1485 int value = ((Integer) data[0]).intValue();
1487 if (value == JFileChooser.APPROVE_OPTION)
1489 JalviewFileChooser chooser = (JalviewFileChooser) data[2];
1490 String choice = chooser.getSelectedFile().getPath();
1491 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1492 loadJalviewDataFile(choice, null, null, null);
1498 chooser.showOpenDialog(null);
1505 * Close the current view or all views in the alignment frame. If the frame
1506 * only contains one view then the alignment will be removed from memory.
1508 * @param closeAllTabs
1511 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1513 if (alignPanels != null && alignPanels.size() < 2)
1515 closeAllTabs = true;
1520 if (alignPanels != null)
1524 if (this.isClosed())
1526 // really close all the windows - otherwise wait till
1527 // setClosed(true) is called
1528 for (int i = 0; i < alignPanels.size(); i++)
1530 AlignmentPanel ap = alignPanels.get(i);
1537 closeView(alignPanel);
1544 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1545 * be called recursively, with the frame now in 'closed' state
1547 this.setClosed(true);
1549 } catch (Exception ex)
1551 ex.printStackTrace();
1556 * Close the specified panel and close up tabs appropriately.
1558 * @param panelToClose
1560 public void closeView(AlignmentPanel panelToClose)
1562 int index = tabbedPane.getSelectedIndex();
1563 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1564 alignPanels.remove(panelToClose);
1565 panelToClose.closePanel();
1566 panelToClose = null;
1568 tabbedPane.removeTabAt(closedindex);
1569 tabbedPane.validate();
1571 if (index > closedindex || index == tabbedPane.getTabCount())
1573 // modify currently selected tab index if necessary.
1577 this.tabSelectionChanged(index);
1583 void updateEditMenuBar()
1586 if (viewport.getHistoryList().size() > 0)
1588 undoMenuItem.setEnabled(true);
1589 CommandI command = viewport.getHistoryList().peek();
1590 undoMenuItem.setText(MessageManager
1591 .formatMessage("label.undo_command", new Object[]
1592 { command.getDescription() }));
1596 undoMenuItem.setEnabled(false);
1597 undoMenuItem.setText(MessageManager.getString("action.undo"));
1600 if (viewport.getRedoList().size() > 0)
1602 redoMenuItem.setEnabled(true);
1604 CommandI command = viewport.getRedoList().peek();
1605 redoMenuItem.setText(MessageManager
1606 .formatMessage("label.redo_command", new Object[]
1607 { command.getDescription() }));
1611 redoMenuItem.setEnabled(false);
1612 redoMenuItem.setText(MessageManager.getString("action.redo"));
1617 public void addHistoryItem(CommandI command)
1619 if (command.getSize() > 0)
1621 viewport.addToHistoryList(command);
1622 viewport.clearRedoList();
1623 updateEditMenuBar();
1624 viewport.updateHiddenColumns();
1625 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1626 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1627 // viewport.getColumnSelection()
1628 // .getHiddenColumns().size() > 0);
1634 * @return alignment objects for all views
1636 AlignmentI[] getViewAlignments()
1638 if (alignPanels != null)
1640 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1642 for (AlignmentPanel ap : alignPanels)
1644 als[i++] = ap.av.getAlignment();
1648 if (viewport != null)
1650 return new AlignmentI[] { viewport.getAlignment() };
1662 protected void undoMenuItem_actionPerformed(ActionEvent e)
1664 if (viewport.getHistoryList().isEmpty())
1668 CommandI command = viewport.getHistoryList().pop();
1669 viewport.addToRedoList(command);
1670 command.undoCommand(getViewAlignments());
1672 AlignmentViewport originalSource = getOriginatingSource(command);
1673 updateEditMenuBar();
1675 if (originalSource != null)
1677 if (originalSource != viewport)
1680 "Implementation worry: mismatch of viewport origin for undo");
1682 originalSource.updateHiddenColumns();
1683 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1685 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1686 // viewport.getColumnSelection()
1687 // .getHiddenColumns().size() > 0);
1688 originalSource.firePropertyChange("alignment", null,
1689 originalSource.getAlignment().getSequences());
1700 protected void redoMenuItem_actionPerformed(ActionEvent e)
1702 if (viewport.getRedoList().size() < 1)
1707 CommandI command = viewport.getRedoList().pop();
1708 viewport.addToHistoryList(command);
1709 command.doCommand(getViewAlignments());
1711 AlignmentViewport originalSource = getOriginatingSource(command);
1712 updateEditMenuBar();
1714 if (originalSource != null)
1717 if (originalSource != viewport)
1720 "Implementation worry: mismatch of viewport origin for redo");
1722 originalSource.updateHiddenColumns();
1723 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1725 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1726 // viewport.getColumnSelection()
1727 // .getHiddenColumns().size() > 0);
1728 originalSource.firePropertyChange("alignment", null,
1729 originalSource.getAlignment().getSequences());
1733 AlignmentViewport getOriginatingSource(CommandI command)
1735 AlignmentViewport originalSource = null;
1736 // For sequence removal and addition, we need to fire
1737 // the property change event FROM the viewport where the
1738 // original alignment was altered
1739 AlignmentI al = null;
1740 if (command instanceof EditCommand)
1742 EditCommand editCommand = (EditCommand) command;
1743 al = editCommand.getAlignment();
1744 List<Component> comps = PaintRefresher.components
1745 .get(viewport.getSequenceSetId());
1747 for (Component comp : comps)
1749 if (comp instanceof AlignmentPanel)
1751 if (al == ((AlignmentPanel) comp).av.getAlignment())
1753 originalSource = ((AlignmentPanel) comp).av;
1760 if (originalSource == null)
1762 // The original view is closed, we must validate
1763 // the current view against the closed view first
1766 PaintRefresher.validateSequences(al, viewport.getAlignment());
1769 originalSource = viewport;
1772 return originalSource;
1781 public void moveSelectedSequences(boolean up)
1783 SequenceGroup sg = viewport.getSelectionGroup();
1789 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1790 viewport.getHiddenRepSequences(), up);
1791 alignPanel.paintAlignment(true, false);
1794 synchronized void slideSequences(boolean right, int size)
1796 List<SequenceI> sg = new ArrayList<>();
1797 if (viewport.cursorMode)
1799 sg.add(viewport.getAlignment()
1800 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1802 else if (viewport.getSelectionGroup() != null
1803 && viewport.getSelectionGroup().getSize() != viewport
1804 .getAlignment().getHeight())
1806 sg = viewport.getSelectionGroup()
1807 .getSequences(viewport.getHiddenRepSequences());
1815 List<SequenceI> invertGroup = new ArrayList<>();
1817 for (SequenceI seq : viewport.getAlignment().getSequences())
1819 if (!sg.contains(seq))
1821 invertGroup.add(seq);
1825 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1827 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1828 for (int i = 0; i < invertGroup.size(); i++)
1830 seqs2[i] = invertGroup.get(i);
1833 SlideSequencesCommand ssc;
1836 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1837 viewport.getGapCharacter());
1841 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1842 viewport.getGapCharacter());
1845 int groupAdjustment = 0;
1846 if (ssc.getGapsInsertedBegin() && right)
1848 if (viewport.cursorMode)
1850 alignPanel.getSeqPanel().moveCursor(size, 0);
1854 groupAdjustment = size;
1857 else if (!ssc.getGapsInsertedBegin() && !right)
1859 if (viewport.cursorMode)
1861 alignPanel.getSeqPanel().moveCursor(-size, 0);
1865 groupAdjustment = -size;
1869 if (groupAdjustment != 0)
1871 viewport.getSelectionGroup().setStartRes(
1872 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1873 viewport.getSelectionGroup().setEndRes(
1874 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1878 * just extend the last slide command if compatible; but not if in
1879 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1881 boolean appendHistoryItem = false;
1882 Deque<CommandI> historyList = viewport.getHistoryList();
1883 boolean inSplitFrame = getSplitViewContainer() != null;
1884 if (!inSplitFrame && historyList != null && historyList.size() > 0
1885 && historyList.peek() instanceof SlideSequencesCommand)
1887 appendHistoryItem = ssc.appendSlideCommand(
1888 (SlideSequencesCommand) historyList.peek());
1891 if (!appendHistoryItem)
1893 addHistoryItem(ssc);
1906 protected void copy_actionPerformed(ActionEvent e)
1908 if (viewport.getSelectionGroup() == null)
1912 // TODO: preserve the ordering of displayed alignment annotation in any
1913 // internal paste (particularly sequence associated annotation)
1914 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1915 String[] omitHidden = null;
1917 if (viewport.hasHiddenColumns())
1919 omitHidden = viewport.getViewAsString(true);
1922 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1923 seqs, omitHidden, null);
1925 StringSelection ss = new StringSelection(output);
1929 jalview.gui.Desktop.internalCopy = true;
1930 // Its really worth setting the clipboard contents
1931 // to empty before setting the large StringSelection!!
1932 Toolkit.getDefaultToolkit().getSystemClipboard()
1933 .setContents(new StringSelection(""), null);
1935 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1937 } catch (OutOfMemoryError er)
1939 new OOMWarning("copying region", er);
1943 HiddenColumns hiddenColumns = null;
1944 if (viewport.hasHiddenColumns())
1946 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1947 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1949 // create new HiddenColumns object with copy of hidden regions
1950 // between startRes and endRes, offset by startRes
1951 hiddenColumns = new HiddenColumns(
1952 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1953 hiddenCutoff, hiddenOffset);
1956 Desktop.jalviewClipboard = new Object[] { seqs,
1957 viewport.getAlignment().getDataset(), hiddenColumns };
1958 statusBar.setText(MessageManager.formatMessage(
1959 "label.copied_sequences_to_clipboard", new Object[]
1960 { Integer.valueOf(seqs.length).toString() }));
1970 protected void pasteNew_actionPerformed(ActionEvent e)
1982 protected void pasteThis_actionPerformed(ActionEvent e)
1988 * Paste contents of Jalview clipboard
1990 * @param newAlignment
1991 * true to paste to a new alignment, otherwise add to this.
1993 void paste(boolean newAlignment)
1995 boolean externalPaste = true;
1998 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1999 Transferable contents = c.getContents(this);
2001 if (contents == null)
2010 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2011 if (str.length() < 1)
2016 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2018 } catch (OutOfMemoryError er)
2020 new OOMWarning("Out of memory pasting sequences!!", er);
2024 SequenceI[] sequences;
2025 boolean annotationAdded = false;
2026 AlignmentI alignment = null;
2028 if (Desktop.jalviewClipboard != null)
2030 // The clipboard was filled from within Jalview, we must use the
2032 // And dataset from the copied alignment
2033 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2034 // be doubly sure that we create *new* sequence objects.
2035 sequences = new SequenceI[newseq.length];
2036 for (int i = 0; i < newseq.length; i++)
2038 sequences[i] = new Sequence(newseq[i]);
2040 alignment = new Alignment(sequences);
2041 externalPaste = false;
2045 // parse the clipboard as an alignment.
2046 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2048 sequences = alignment.getSequencesArray();
2052 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2058 if (Desktop.jalviewClipboard != null)
2060 // dataset is inherited
2061 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2065 // new dataset is constructed
2066 alignment.setDataset(null);
2068 alwidth = alignment.getWidth() + 1;
2072 AlignmentI pastedal = alignment; // preserve pasted alignment object
2073 // Add pasted sequences and dataset into existing alignment.
2074 alignment = viewport.getAlignment();
2075 alwidth = alignment.getWidth() + 1;
2076 // decide if we need to import sequences from an existing dataset
2077 boolean importDs = Desktop.jalviewClipboard != null
2078 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2079 // importDs==true instructs us to copy over new dataset sequences from
2080 // an existing alignment
2081 Vector newDs = (importDs) ? new Vector() : null; // used to create
2082 // minimum dataset set
2084 for (int i = 0; i < sequences.length; i++)
2088 newDs.addElement(null);
2090 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2092 if (importDs && ds != null)
2094 if (!newDs.contains(ds))
2096 newDs.setElementAt(ds, i);
2097 ds = new Sequence(ds);
2098 // update with new dataset sequence
2099 sequences[i].setDatasetSequence(ds);
2103 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2108 // copy and derive new dataset sequence
2109 sequences[i] = sequences[i].deriveSequence();
2110 alignment.getDataset()
2111 .addSequence(sequences[i].getDatasetSequence());
2112 // TODO: avoid creation of duplicate dataset sequences with a
2113 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2115 alignment.addSequence(sequences[i]); // merges dataset
2119 newDs.clear(); // tidy up
2121 if (alignment.getAlignmentAnnotation() != null)
2123 for (AlignmentAnnotation alan : alignment
2124 .getAlignmentAnnotation())
2126 if (alan.graphGroup > fgroup)
2128 fgroup = alan.graphGroup;
2132 if (pastedal.getAlignmentAnnotation() != null)
2134 // Add any annotation attached to alignment.
2135 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2136 for (int i = 0; i < alann.length; i++)
2138 annotationAdded = true;
2139 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2141 AlignmentAnnotation newann = new AlignmentAnnotation(
2143 if (newann.graphGroup > -1)
2145 if (newGraphGroups.size() <= newann.graphGroup
2146 || newGraphGroups.get(newann.graphGroup) == null)
2148 for (int q = newGraphGroups
2149 .size(); q <= newann.graphGroup; q++)
2151 newGraphGroups.add(q, null);
2153 newGraphGroups.set(newann.graphGroup,
2154 new Integer(++fgroup));
2156 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2160 newann.padAnnotation(alwidth);
2161 alignment.addAnnotation(newann);
2171 addHistoryItem(new EditCommand(
2172 MessageManager.getString("label.add_sequences"),
2173 Action.PASTE, sequences, 0, alignment.getWidth(),
2176 // Add any annotations attached to sequences
2177 for (int i = 0; i < sequences.length; i++)
2179 if (sequences[i].getAnnotation() != null)
2181 AlignmentAnnotation newann;
2182 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2184 annotationAdded = true;
2185 newann = sequences[i].getAnnotation()[a];
2186 newann.adjustForAlignment();
2187 newann.padAnnotation(alwidth);
2188 if (newann.graphGroup > -1)
2190 if (newann.graphGroup > -1)
2192 if (newGraphGroups.size() <= newann.graphGroup
2193 || newGraphGroups.get(newann.graphGroup) == null)
2195 for (int q = newGraphGroups
2196 .size(); q <= newann.graphGroup; q++)
2198 newGraphGroups.add(q, null);
2200 newGraphGroups.set(newann.graphGroup,
2201 new Integer(++fgroup));
2203 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2207 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2211 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2219 // propagate alignment changed.
2220 viewport.getRanges().setEndSeq(alignment.getHeight());
2221 if (annotationAdded)
2223 // Duplicate sequence annotation in all views.
2224 AlignmentI[] alview = this.getViewAlignments();
2225 for (int i = 0; i < sequences.length; i++)
2227 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2232 for (int avnum = 0; avnum < alview.length; avnum++)
2234 if (alview[avnum] != alignment)
2236 // duplicate in a view other than the one with input focus
2237 int avwidth = alview[avnum].getWidth() + 1;
2238 // this relies on sann being preserved after we
2239 // modify the sequence's annotation array for each duplication
2240 for (int a = 0; a < sann.length; a++)
2242 AlignmentAnnotation newann = new AlignmentAnnotation(
2244 sequences[i].addAlignmentAnnotation(newann);
2245 newann.padAnnotation(avwidth);
2246 alview[avnum].addAnnotation(newann); // annotation was
2247 // duplicated earlier
2248 // TODO JAL-1145 graphGroups are not updated for sequence
2249 // annotation added to several views. This may cause
2251 alview[avnum].setAnnotationIndex(newann, a);
2256 buildSortByAnnotationScoresMenu();
2258 viewport.firePropertyChange("alignment", null,
2259 alignment.getSequences());
2260 if (alignPanels != null)
2262 for (AlignmentPanel ap : alignPanels)
2264 ap.validateAnnotationDimensions(false);
2269 alignPanel.validateAnnotationDimensions(false);
2275 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2277 String newtitle = new String("Copied sequences");
2279 if (Desktop.jalviewClipboard != null
2280 && Desktop.jalviewClipboard[2] != null)
2282 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2283 af.viewport.setHiddenColumns(hc);
2286 // >>>This is a fix for the moment, until a better solution is
2288 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2289 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2290 .getFeatureRenderer());
2292 // TODO: maintain provenance of an alignment, rather than just make the
2293 // title a concatenation of operations.
2296 if (title.startsWith("Copied sequences"))
2302 newtitle = newtitle.concat("- from " + title);
2307 newtitle = new String("Pasted sequences");
2310 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2315 } catch (Exception ex)
2317 ex.printStackTrace();
2318 System.out.println("Exception whilst pasting: " + ex);
2319 // could be anything being pasted in here
2325 protected void expand_newalign(ActionEvent e)
2329 AlignmentI alignment = AlignmentUtils
2330 .expandContext(getViewport().getAlignment(), -1);
2331 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2333 String newtitle = new String("Flanking alignment");
2335 if (Desktop.jalviewClipboard != null
2336 && Desktop.jalviewClipboard[2] != null)
2338 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2339 af.viewport.setHiddenColumns(hc);
2342 // >>>This is a fix for the moment, until a better solution is
2344 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2345 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2346 .getFeatureRenderer());
2348 // TODO: maintain provenance of an alignment, rather than just make the
2349 // title a concatenation of operations.
2351 if (title.startsWith("Copied sequences"))
2357 newtitle = newtitle.concat("- from " + title);
2361 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2363 } catch (Exception ex)
2365 ex.printStackTrace();
2366 System.out.println("Exception whilst pasting: " + ex);
2367 // could be anything being pasted in here
2368 } catch (OutOfMemoryError oom)
2370 new OOMWarning("Viewing flanking region of alignment", oom);
2381 protected void cut_actionPerformed(ActionEvent e)
2383 copy_actionPerformed(null);
2384 delete_actionPerformed(null);
2394 protected void delete_actionPerformed(ActionEvent evt)
2397 SequenceGroup sg = viewport.getSelectionGroup();
2404 * If the cut affects all sequences, warn, remove highlighted columns
2406 if (sg.getSize() == viewport.getAlignment().getHeight())
2408 boolean isEntireAlignWidth = (((sg.getEndRes() - sg.getStartRes())
2409 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2410 if (isEntireAlignWidth)
2412 int confirm = JvOptionPane.showConfirmDialog(this,
2413 MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2414 MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2415 JvOptionPane.OK_CANCEL_OPTION);
2417 if (confirm == JvOptionPane.CANCEL_OPTION
2418 || confirm == JvOptionPane.CLOSED_OPTION)
2423 viewport.getColumnSelection().removeElements(sg.getStartRes(),
2424 sg.getEndRes() + 1);
2426 SequenceI[] cut = sg.getSequences()
2427 .toArray(new SequenceI[sg.getSize()]);
2429 addHistoryItem(new EditCommand(
2430 MessageManager.getString("label.cut_sequences"), Action.CUT,
2431 cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2432 viewport.getAlignment()));
2434 viewport.setSelectionGroup(null);
2435 viewport.sendSelection();
2436 viewport.getAlignment().deleteGroup(sg);
2438 viewport.firePropertyChange("alignment", null,
2439 viewport.getAlignment().getSequences());
2440 if (viewport.getAlignment().getHeight() < 1)
2444 this.setClosed(true);
2445 } catch (Exception ex)
2458 protected void deleteGroups_actionPerformed(ActionEvent e)
2460 if (avc.deleteGroups())
2462 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2463 alignPanel.updateAnnotation();
2464 alignPanel.paintAlignment(true, true);
2475 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2477 SequenceGroup sg = new SequenceGroup();
2479 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2481 sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2484 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2485 viewport.setSelectionGroup(sg);
2486 viewport.sendSelection();
2487 // JAL-2034 - should delegate to
2488 // alignPanel to decide if overview needs
2490 alignPanel.paintAlignment(false, false);
2491 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2501 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2503 if (viewport.cursorMode)
2505 alignPanel.getSeqPanel().keyboardNo1 = null;
2506 alignPanel.getSeqPanel().keyboardNo2 = null;
2508 viewport.setSelectionGroup(null);
2509 viewport.getColumnSelection().clear();
2510 viewport.setSelectionGroup(null);
2511 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2512 // JAL-2034 - should delegate to
2513 // alignPanel to decide if overview needs
2515 alignPanel.paintAlignment(false, false);
2516 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2517 viewport.sendSelection();
2527 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2529 SequenceGroup sg = viewport.getSelectionGroup();
2533 selectAllSequenceMenuItem_actionPerformed(null);
2538 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2540 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2542 // JAL-2034 - should delegate to
2543 // alignPanel to decide if overview needs
2546 alignPanel.paintAlignment(true, false);
2547 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2548 viewport.sendSelection();
2552 public void invertColSel_actionPerformed(ActionEvent e)
2554 viewport.invertColumnSelection();
2555 alignPanel.paintAlignment(true, false);
2556 viewport.sendSelection();
2566 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2568 trimAlignment(true);
2578 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2580 trimAlignment(false);
2583 void trimAlignment(boolean trimLeft)
2585 ColumnSelection colSel = viewport.getColumnSelection();
2588 if (!colSel.isEmpty())
2592 column = colSel.getMin();
2596 column = colSel.getMax();
2600 if (viewport.getSelectionGroup() != null)
2602 seqs = viewport.getSelectionGroup()
2603 .getSequencesAsArray(viewport.getHiddenRepSequences());
2607 seqs = viewport.getAlignment().getSequencesArray();
2610 TrimRegionCommand trimRegion;
2613 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2614 column, viewport.getAlignment());
2615 viewport.getRanges().setStartRes(0);
2619 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2620 column, viewport.getAlignment());
2623 statusBar.setText(MessageManager
2624 .formatMessage("label.removed_columns", new String[]
2625 { Integer.valueOf(trimRegion.getSize()).toString() }));
2627 addHistoryItem(trimRegion);
2629 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2631 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2632 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2634 viewport.getAlignment().deleteGroup(sg);
2638 viewport.firePropertyChange("alignment", null,
2639 viewport.getAlignment().getSequences());
2650 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2652 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2655 if (viewport.getSelectionGroup() != null)
2657 seqs = viewport.getSelectionGroup()
2658 .getSequencesAsArray(viewport.getHiddenRepSequences());
2659 start = viewport.getSelectionGroup().getStartRes();
2660 end = viewport.getSelectionGroup().getEndRes();
2664 seqs = viewport.getAlignment().getSequencesArray();
2667 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2668 "Remove Gapped Columns", seqs, start, end,
2669 viewport.getAlignment());
2671 addHistoryItem(removeGapCols);
2673 statusBar.setText(MessageManager
2674 .formatMessage("label.removed_empty_columns", new Object[]
2675 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2677 // This is to maintain viewport position on first residue
2678 // of first sequence
2679 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2680 ViewportRanges ranges = viewport.getRanges();
2681 int startRes = seq.findPosition(ranges.getStartRes());
2682 // ShiftList shifts;
2683 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2684 // edit.alColumnChanges=shifts.getInverse();
2685 // if (viewport.hasHiddenColumns)
2686 // viewport.getColumnSelection().compensateForEdits(shifts);
2687 ranges.setStartRes(seq.findIndex(startRes) - 1);
2688 viewport.firePropertyChange("alignment", null,
2689 viewport.getAlignment().getSequences());
2700 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2702 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2705 if (viewport.getSelectionGroup() != null)
2707 seqs = viewport.getSelectionGroup()
2708 .getSequencesAsArray(viewport.getHiddenRepSequences());
2709 start = viewport.getSelectionGroup().getStartRes();
2710 end = viewport.getSelectionGroup().getEndRes();
2714 seqs = viewport.getAlignment().getSequencesArray();
2717 // This is to maintain viewport position on first residue
2718 // of first sequence
2719 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2720 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2722 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2723 viewport.getAlignment()));
2725 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2727 viewport.firePropertyChange("alignment", null,
2728 viewport.getAlignment().getSequences());
2739 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2741 viewport.setPadGaps(padGapsMenuitem.isSelected());
2742 viewport.firePropertyChange("alignment", null,
2743 viewport.getAlignment().getSequences());
2753 public void findMenuItem_actionPerformed(ActionEvent e)
2759 * Create a new view of the current alignment.
2762 public void newView_actionPerformed(ActionEvent e)
2764 newView(null, true);
2768 * Creates and shows a new view of the current alignment.
2771 * title of newly created view; if null, one will be generated
2772 * @param copyAnnotation
2773 * if true then duplicate all annnotation, groups and settings
2774 * @return new alignment panel, already displayed.
2776 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2779 * Create a new AlignmentPanel (with its own, new Viewport)
2781 AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel);
2782 if (!copyAnnotation)
2785 * remove all groups and annotation except for the automatic stuff
2787 newap.av.getAlignment().deleteAllGroups();
2788 newap.av.getAlignment().deleteAllAnnotations(false);
2791 newap.av.setGatherViewsHere(false);
2793 if (viewport.viewName == null)
2795 viewport.viewName = MessageManager
2796 .getString("label.view_name_original");
2800 * Views share the same edits undo and redo stacks
2802 newap.av.setHistoryList(viewport.getHistoryList());
2803 newap.av.setRedoList(viewport.getRedoList());
2806 * Views share the same mappings; need to deregister any new mappings
2807 * created by copyAlignPanel, and register the new reference to the shared
2810 newap.av.replaceMappings(viewport.getAlignment());
2813 * start up cDNA consensus (if applicable) now mappings are in place
2815 if (newap.av.initComplementConsensus())
2817 newap.refresh(true); // adjust layout of annotations
2820 newap.av.viewName = getNewViewName(viewTitle);
2822 addAlignmentPanel(newap, true);
2823 newap.alignmentChanged();
2825 if (alignPanels.size() == 2)
2827 viewport.setGatherViewsHere(true);
2829 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2834 * Make a new name for the view, ensuring it is unique within the current
2835 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2836 * these now use viewId. Unique view names are still desirable for usability.)
2841 protected String getNewViewName(String viewTitle)
2843 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2844 boolean addFirstIndex = false;
2845 if (viewTitle == null || viewTitle.trim().length() == 0)
2847 viewTitle = MessageManager.getString("action.view");
2848 addFirstIndex = true;
2852 index = 1;// we count from 1 if given a specific name
2854 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2856 List<Component> comps = PaintRefresher.components
2857 .get(viewport.getSequenceSetId());
2859 List<String> existingNames = getExistingViewNames(comps);
2861 while (existingNames.contains(newViewName))
2863 newViewName = viewTitle + " " + (++index);
2869 * Returns a list of distinct view names found in the given list of
2870 * components. View names are held on the viewport of an AlignmentPanel.
2875 protected List<String> getExistingViewNames(List<Component> comps)
2877 List<String> existingNames = new ArrayList<>();
2878 for (Component comp : comps)
2880 if (comp instanceof AlignmentPanel)
2882 AlignmentPanel ap = (AlignmentPanel) comp;
2883 if (!existingNames.contains(ap.av.viewName))
2885 existingNames.add(ap.av.viewName);
2889 return existingNames;
2893 * Explode tabbed views into separate windows.
2896 public void expandViews_actionPerformed(ActionEvent e)
2898 Desktop.explodeViews(this);
2902 * Gather views in separate windows back into a tabbed presentation.
2905 public void gatherViews_actionPerformed(ActionEvent e)
2907 Desktop.instance.gatherViews(this);
2917 public void font_actionPerformed(ActionEvent e)
2919 new FontChooser(alignPanel);
2929 protected void seqLimit_actionPerformed(ActionEvent e)
2931 viewport.setShowJVSuffix(seqLimits.isSelected());
2933 alignPanel.getIdPanel().getIdCanvas()
2934 .setPreferredSize(alignPanel.calculateIdWidth());
2935 alignPanel.paintAlignment(true, false);
2939 public void idRightAlign_actionPerformed(ActionEvent e)
2941 viewport.setRightAlignIds(idRightAlign.isSelected());
2942 alignPanel.paintAlignment(false, false);
2946 public void centreColumnLabels_actionPerformed(ActionEvent e)
2948 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2949 alignPanel.paintAlignment(false, false);
2955 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2958 protected void followHighlight_actionPerformed()
2961 * Set the 'follow' flag on the Viewport (and scroll to position if now
2964 final boolean state = this.followHighlightMenuItem.getState();
2965 viewport.setFollowHighlight(state);
2968 alignPanel.scrollToPosition(viewport.getSearchResults(), false);
2979 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2981 viewport.setColourText(colourTextMenuItem.isSelected());
2982 alignPanel.paintAlignment(false, false);
2992 public void wrapMenuItem_actionPerformed(ActionEvent e)
2994 scaleAbove.setVisible(wrapMenuItem.isSelected());
2995 scaleLeft.setVisible(wrapMenuItem.isSelected());
2996 scaleRight.setVisible(wrapMenuItem.isSelected());
2997 viewport.setWrapAlignment(wrapMenuItem.isSelected());
2998 alignPanel.updateLayout();
3002 public void showAllSeqs_actionPerformed(ActionEvent e)
3004 viewport.showAllHiddenSeqs();
3008 public void showAllColumns_actionPerformed(ActionEvent e)
3010 viewport.showAllHiddenColumns();
3011 alignPanel.paintAlignment(true, true);
3012 viewport.sendSelection();
3016 public void hideSelSequences_actionPerformed(ActionEvent e)
3018 viewport.hideAllSelectedSeqs();
3022 * called by key handler and the hide all/show all menu items
3027 private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3030 boolean hide = false;
3031 SequenceGroup sg = viewport.getSelectionGroup();
3032 if (!toggleSeqs && !toggleCols)
3034 // Hide everything by the current selection - this is a hack - we do the
3035 // invert and then hide
3036 // first check that there will be visible columns after the invert.
3037 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3038 && sg.getStartRes() <= sg.getEndRes()))
3040 // now invert the sequence set, if required - empty selection implies
3041 // that no hiding is required.
3044 invertSequenceMenuItem_actionPerformed(null);
3045 sg = viewport.getSelectionGroup();
3049 viewport.expandColSelection(sg, true);
3050 // finally invert the column selection and get the new sequence
3052 invertColSel_actionPerformed(null);
3059 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3061 hideSelSequences_actionPerformed(null);
3064 else if (!(toggleCols && viewport.hasSelectedColumns()))
3066 showAllSeqs_actionPerformed(null);
3072 if (viewport.hasSelectedColumns())
3074 hideSelColumns_actionPerformed(null);
3077 viewport.setSelectionGroup(sg);
3082 showAllColumns_actionPerformed(null);
3091 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3092 * event.ActionEvent)
3095 public void hideAllButSelection_actionPerformed(ActionEvent e)
3097 toggleHiddenRegions(false, false);
3098 viewport.sendSelection();
3105 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3109 public void hideAllSelection_actionPerformed(ActionEvent e)
3111 SequenceGroup sg = viewport.getSelectionGroup();
3112 viewport.expandColSelection(sg, false);
3113 viewport.hideAllSelectedSeqs();
3114 viewport.hideSelectedColumns();
3115 alignPanel.paintAlignment(true, true);
3116 viewport.sendSelection();
3123 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3127 public void showAllhidden_actionPerformed(ActionEvent e)
3129 viewport.showAllHiddenColumns();
3130 viewport.showAllHiddenSeqs();
3131 alignPanel.paintAlignment(true, true);
3132 viewport.sendSelection();
3136 public void hideSelColumns_actionPerformed(ActionEvent e)
3138 viewport.hideSelectedColumns();
3139 alignPanel.paintAlignment(true, true);
3140 viewport.sendSelection();
3144 public void hiddenMarkers_actionPerformed(ActionEvent e)
3146 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3157 protected void scaleAbove_actionPerformed(ActionEvent e)
3159 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3160 // TODO: do we actually need to update overview for scale above change ?
3161 alignPanel.paintAlignment(true, false);
3171 protected void scaleLeft_actionPerformed(ActionEvent e)
3173 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3174 alignPanel.paintAlignment(true, false);
3184 protected void scaleRight_actionPerformed(ActionEvent e)
3186 viewport.setScaleRightWrapped(scaleRight.isSelected());
3187 alignPanel.paintAlignment(true, false);
3197 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3199 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3200 alignPanel.paintAlignment(false, false);
3210 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3212 viewport.setShowText(viewTextMenuItem.isSelected());
3213 alignPanel.paintAlignment(false, false);
3223 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3225 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3226 alignPanel.paintAlignment(false, false);
3229 public FeatureSettings featureSettings;
3232 public FeatureSettingsControllerI getFeatureSettingsUI()
3234 return featureSettings;
3238 public void featureSettings_actionPerformed(ActionEvent e)
3240 if (featureSettings != null)
3242 featureSettings.close();
3243 featureSettings = null;
3245 if (!showSeqFeatures.isSelected())
3247 // make sure features are actually displayed
3248 showSeqFeatures.setSelected(true);
3249 showSeqFeatures_actionPerformed(null);
3251 featureSettings = new FeatureSettings(this);
3255 * Set or clear 'Show Sequence Features'
3261 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3263 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3264 alignPanel.paintAlignment(true, true);
3268 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3269 * the annotations panel as a whole.
3271 * The options to show/hide all annotations should be enabled when the panel
3272 * is shown, and disabled when the panel is hidden.
3277 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3279 final boolean setVisible = annotationPanelMenuItem.isSelected();
3280 viewport.setShowAnnotation(setVisible);
3281 this.showAllSeqAnnotations.setEnabled(setVisible);
3282 this.hideAllSeqAnnotations.setEnabled(setVisible);
3283 this.showAllAlAnnotations.setEnabled(setVisible);
3284 this.hideAllAlAnnotations.setEnabled(setVisible);
3285 alignPanel.updateLayout();
3289 public void alignmentProperties()
3291 JEditorPane editPane = new JEditorPane("text/html", "");
3292 editPane.setEditable(false);
3293 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3296 MessageManager.formatMessage("label.html_content", new Object[]
3297 { contents.toString() }));
3298 JInternalFrame frame = new JInternalFrame();
3299 frame.getContentPane().add(new JScrollPane(editPane));
3301 Desktop.addInternalFrame(frame, MessageManager
3302 .formatMessage("label.alignment_properties", new Object[]
3303 { getTitle() }), 500, 400);
3313 public void overviewMenuItem_actionPerformed(ActionEvent e)
3315 if (alignPanel.overviewPanel != null)
3320 JInternalFrame frame = new JInternalFrame();
3321 final OverviewPanel overview = new OverviewPanel(alignPanel);
3322 frame.setContentPane(overview);
3323 Desktop.addInternalFrame(frame, MessageManager
3324 .formatMessage("label.overview_params", new Object[]
3325 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3328 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3329 frame.addInternalFrameListener(
3330 new javax.swing.event.InternalFrameAdapter()
3333 public void internalFrameClosed(
3334 javax.swing.event.InternalFrameEvent evt)
3337 alignPanel.setOverviewPanel(null);
3340 if (getKeyListeners().length > 0)
3342 frame.addKeyListener(getKeyListeners()[0]);
3345 alignPanel.setOverviewPanel(overview);
3349 public void textColour_actionPerformed()
3351 new TextColourChooser().chooseColour(alignPanel, null);
3355 * public void covariationColour_actionPerformed() {
3357 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3361 public void annotationColour_actionPerformed()
3363 new AnnotationColourChooser(viewport, alignPanel);
3367 public void annotationColumn_actionPerformed(ActionEvent e)
3369 new AnnotationColumnChooser(viewport, alignPanel);
3373 * Action on the user checking or unchecking the option to apply the selected
3374 * colour scheme to all groups. If unchecked, groups may have their own
3375 * independent colour schemes.
3380 public void applyToAllGroups_actionPerformed(boolean selected)
3382 viewport.setColourAppliesToAllGroups(selected);
3386 * Action on user selecting a colour from the colour menu
3389 * the name (not the menu item label!) of the colour scheme
3392 public void changeColour_actionPerformed(String name)
3395 * 'User Defined' opens a panel to configure or load a
3396 * user-defined colour scheme
3398 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3400 new UserDefinedColours(alignPanel);
3405 * otherwise set the chosen colour scheme (or null for 'None')
3407 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3408 viewport.getAlignment(), viewport.getHiddenRepSequences());
3413 * Actions on setting or changing the alignment colour scheme
3418 public void changeColour(ColourSchemeI cs)
3420 // TODO: pull up to controller method
3421 ColourMenuHelper.setColourSelected(colourMenu, cs);
3423 viewport.setGlobalColourScheme(cs);
3425 alignPanel.paintAlignment(true, true);
3429 * Show the PID threshold slider panel
3432 protected void modifyPID_actionPerformed()
3434 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3435 alignPanel.getViewName());
3436 SliderPanel.showPIDSlider();
3440 * Show the Conservation slider panel
3443 protected void modifyConservation_actionPerformed()
3445 SliderPanel.setConservationSlider(alignPanel,
3446 viewport.getResidueShading(), alignPanel.getViewName());
3447 SliderPanel.showConservationSlider();
3451 * Action on selecting or deselecting (Colour) By Conservation
3454 public void conservationMenuItem_actionPerformed(boolean selected)
3456 modifyConservation.setEnabled(selected);
3457 viewport.setConservationSelected(selected);
3458 viewport.getResidueShading().setConservationApplied(selected);
3460 changeColour(viewport.getGlobalColourScheme());
3463 modifyConservation_actionPerformed();
3467 SliderPanel.hideConservationSlider();
3472 * Action on selecting or deselecting (Colour) Above PID Threshold
3475 public void abovePIDThreshold_actionPerformed(boolean selected)
3477 modifyPID.setEnabled(selected);
3478 viewport.setAbovePIDThreshold(selected);
3481 viewport.getResidueShading().setThreshold(0,
3482 viewport.isIgnoreGapsConsensus());
3485 changeColour(viewport.getGlobalColourScheme());
3488 modifyPID_actionPerformed();
3492 SliderPanel.hidePIDSlider();
3503 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3505 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3506 AlignmentSorter.sortByPID(viewport.getAlignment(),
3507 viewport.getAlignment().getSequenceAt(0));
3508 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3509 viewport.getAlignment()));
3510 alignPanel.paintAlignment(true, false);
3520 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3522 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3523 AlignmentSorter.sortByID(viewport.getAlignment());
3525 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3526 alignPanel.paintAlignment(true, false);
3536 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3538 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3539 AlignmentSorter.sortByLength(viewport.getAlignment());
3540 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3541 viewport.getAlignment()));
3542 alignPanel.paintAlignment(true, false);
3552 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3554 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3555 AlignmentSorter.sortByGroup(viewport.getAlignment());
3556 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3557 viewport.getAlignment()));
3559 alignPanel.paintAlignment(true, false);
3569 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3571 new RedundancyPanel(alignPanel, this);
3581 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3583 if ((viewport.getSelectionGroup() == null)
3584 || (viewport.getSelectionGroup().getSize() < 2))
3586 JvOptionPane.showInternalMessageDialog(this,
3587 MessageManager.getString(
3588 "label.you_must_select_least_two_sequences"),
3589 MessageManager.getString("label.invalid_selection"),
3590 JvOptionPane.WARNING_MESSAGE);
3594 JInternalFrame frame = new JInternalFrame();
3595 frame.setContentPane(new PairwiseAlignPanel(viewport));
3596 Desktop.addInternalFrame(frame,
3597 MessageManager.getString("action.pairwise_alignment"), 600,
3603 public void autoCalculate_actionPerformed(ActionEvent e)
3605 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3606 if (viewport.autoCalculateConsensus)
3608 viewport.firePropertyChange("alignment", null,
3609 viewport.getAlignment().getSequences());
3614 public void sortByTreeOption_actionPerformed(ActionEvent e)
3616 viewport.sortByTree = sortByTree.isSelected();
3620 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3622 viewport.followSelection = listenToViewSelections.isSelected();
3626 * Constructs a tree panel and adds it to the desktop
3629 * tree type (NJ or AV)
3631 * name of score model used to compute the tree
3633 * parameters for the distance or similarity calculation
3635 void newTreePanel(String type, String modelName,
3636 SimilarityParamsI options)
3638 String frameTitle = "";
3641 boolean onSelection = false;
3642 if (viewport.getSelectionGroup() != null
3643 && viewport.getSelectionGroup().getSize() > 0)
3645 SequenceGroup sg = viewport.getSelectionGroup();
3647 /* Decide if the selection is a column region */
3648 for (SequenceI _s : sg.getSequences())
3650 if (_s.getLength() < sg.getEndRes())
3652 JvOptionPane.showMessageDialog(Desktop.desktop,
3653 MessageManager.getString(
3654 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3655 MessageManager.getString(
3656 "label.sequences_selection_not_aligned"),
3657 JvOptionPane.WARNING_MESSAGE);
3666 if (viewport.getAlignment().getHeight() < 2)
3672 tp = new TreePanel(alignPanel, type, modelName, options);
3673 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3675 frameTitle += " from ";
3677 if (viewport.viewName != null)
3679 frameTitle += viewport.viewName + " of ";
3682 frameTitle += this.title;
3684 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3695 public void addSortByOrderMenuItem(String title,
3696 final AlignmentOrder order)
3698 final JMenuItem item = new JMenuItem(MessageManager
3699 .formatMessage("action.by_title_param", new Object[]
3702 item.addActionListener(new java.awt.event.ActionListener()
3705 public void actionPerformed(ActionEvent e)
3707 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3709 // TODO: JBPNote - have to map order entries to curent SequenceI
3711 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3713 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3714 viewport.getAlignment()));
3716 alignPanel.paintAlignment(true, false);
3722 * Add a new sort by annotation score menu item
3725 * the menu to add the option to
3727 * the label used to retrieve scores for each sequence on the
3730 public void addSortByAnnotScoreMenuItem(JMenu sort,
3731 final String scoreLabel)
3733 final JMenuItem item = new JMenuItem(scoreLabel);
3735 item.addActionListener(new java.awt.event.ActionListener()
3738 public void actionPerformed(ActionEvent e)
3740 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3741 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3742 viewport.getAlignment());// ,viewport.getSelectionGroup());
3743 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3744 viewport.getAlignment()));
3745 alignPanel.paintAlignment(true, false);
3751 * last hash for alignment's annotation array - used to minimise cost of
3754 protected int _annotationScoreVectorHash;
3757 * search the alignment and rebuild the sort by annotation score submenu the
3758 * last alignment annotation vector hash is stored to minimize cost of
3759 * rebuilding in subsequence calls.
3763 public void buildSortByAnnotationScoresMenu()
3765 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3770 if (viewport.getAlignment().getAlignmentAnnotation()
3771 .hashCode() != _annotationScoreVectorHash)
3773 sortByAnnotScore.removeAll();
3774 // almost certainly a quicker way to do this - but we keep it simple
3775 Hashtable scoreSorts = new Hashtable();
3776 AlignmentAnnotation aann[];
3777 for (SequenceI sqa : viewport.getAlignment().getSequences())
3779 aann = sqa.getAnnotation();
3780 for (int i = 0; aann != null && i < aann.length; i++)
3782 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3784 scoreSorts.put(aann[i].label, aann[i].label);
3788 Enumeration labels = scoreSorts.keys();
3789 while (labels.hasMoreElements())
3791 addSortByAnnotScoreMenuItem(sortByAnnotScore,
3792 (String) labels.nextElement());
3794 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3797 _annotationScoreVectorHash = viewport.getAlignment()
3798 .getAlignmentAnnotation().hashCode();
3803 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3804 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3805 * call. Listeners are added to remove the menu item when the treePanel is
3806 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3810 public void buildTreeSortMenu()
3812 sortByTreeMenu.removeAll();
3814 List<Component> comps = PaintRefresher.components
3815 .get(viewport.getSequenceSetId());
3816 List<TreePanel> treePanels = new ArrayList<>();
3817 for (Component comp : comps)
3819 if (comp instanceof TreePanel)
3821 treePanels.add((TreePanel) comp);
3825 if (treePanels.size() < 1)
3827 sortByTreeMenu.setVisible(false);
3831 sortByTreeMenu.setVisible(true);
3833 for (final TreePanel tp : treePanels)
3835 final JMenuItem item = new JMenuItem(tp.getTitle());
3836 item.addActionListener(new java.awt.event.ActionListener()
3839 public void actionPerformed(ActionEvent e)
3841 tp.sortByTree_actionPerformed();
3842 addHistoryItem(tp.sortAlignmentIn(alignPanel));
3847 sortByTreeMenu.add(item);
3851 public boolean sortBy(AlignmentOrder alorder, String undoname)
3853 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3854 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3855 if (undoname != null)
3857 addHistoryItem(new OrderCommand(undoname, oldOrder,
3858 viewport.getAlignment()));
3860 alignPanel.paintAlignment(true, false);
3865 * Work out whether the whole set of sequences or just the selected set will
3866 * be submitted for multiple alignment.
3869 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3871 // Now, check we have enough sequences
3872 AlignmentView msa = null;
3874 if ((viewport.getSelectionGroup() != null)
3875 && (viewport.getSelectionGroup().getSize() > 1))
3877 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3878 // some common interface!
3880 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3881 * SequenceI[sz = seqs.getSize(false)];
3883 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3884 * seqs.getSequenceAt(i); }
3886 msa = viewport.getAlignmentView(true);
3888 else if (viewport.getSelectionGroup() != null
3889 && viewport.getSelectionGroup().getSize() == 1)
3891 int option = JvOptionPane.showConfirmDialog(this,
3892 MessageManager.getString("warn.oneseq_msainput_selection"),
3893 MessageManager.getString("label.invalid_selection"),
3894 JvOptionPane.OK_CANCEL_OPTION);
3895 if (option == JvOptionPane.OK_OPTION)
3897 msa = viewport.getAlignmentView(false);
3902 msa = viewport.getAlignmentView(false);
3908 * Decides what is submitted to a secondary structure prediction service: the
3909 * first sequence in the alignment, or in the current selection, or, if the
3910 * alignment is 'aligned' (ie padded with gaps), then the currently selected
3911 * region or the whole alignment. (where the first sequence in the set is the
3912 * one that the prediction will be for).
3914 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3916 AlignmentView seqs = null;
3918 if ((viewport.getSelectionGroup() != null)
3919 && (viewport.getSelectionGroup().getSize() > 0))
3921 seqs = viewport.getAlignmentView(true);
3925 seqs = viewport.getAlignmentView(false);
3927 // limit sequences - JBPNote in future - could spawn multiple prediction
3929 // TODO: viewport.getAlignment().isAligned is a global state - the local
3930 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3931 if (!viewport.getAlignment().isAligned(false))
3933 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3934 // TODO: if seqs.getSequences().length>1 then should really have warned
3948 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3950 // TODO: JAL-3048 JalviewFileChooser
3951 // Pick the tree file
3952 JalviewFileChooser chooser = new JalviewFileChooser(
3953 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3954 chooser.setFileView(new JalviewFileView());
3955 chooser.setDialogTitle(
3956 MessageManager.getString("label.select_newick_like_tree_file"));
3957 chooser.setToolTipText(
3958 MessageManager.getString("label.load_tree_file"));
3960 int value = chooser.showOpenDialog(null);
3962 if (value == JalviewFileChooser.APPROVE_OPTION)
3964 String filePath = chooser.getSelectedFile().getPath();
3965 Cache.setProperty("LAST_DIRECTORY", filePath);
3966 NewickFile fin = null;
3969 fin = new NewickFile(filePath, DataSourceType.FILE);
3970 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
3971 } catch (Exception ex)
3973 JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
3974 MessageManager.getString("label.problem_reading_tree_file"),
3975 JvOptionPane.WARNING_MESSAGE);
3976 ex.printStackTrace();
3978 if (fin != null && fin.hasWarningMessage())
3980 JvOptionPane.showMessageDialog(Desktop.desktop,
3981 fin.getWarningMessage(),
3983 .getString("label.possible_problem_with_tree_file"),
3984 JvOptionPane.WARNING_MESSAGE);
3989 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
3991 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
3994 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
3995 int h, int x, int y)
3997 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4001 * Add a treeviewer for the tree extracted from a Newick file object to the
4002 * current alignment view
4009 * Associated alignment input data (or null)
4018 * @return TreePanel handle
4020 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4021 AlignmentView input, int w, int h, int x, int y)
4023 TreePanel tp = null;
4029 if (nf.getTree() != null)
4031 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4037 tp.setLocation(x, y);
4040 Desktop.addInternalFrame(tp, treeTitle, w, h);
4042 } catch (Exception ex)
4044 ex.printStackTrace();
4050 private boolean buildingMenu = false;
4053 * Generates menu items and listener event actions for web service clients
4056 public void BuildWebServiceMenu()
4058 while (buildingMenu)
4062 System.err.println("Waiting for building menu to finish.");
4064 } catch (Exception e)
4068 final AlignFrame me = this;
4069 buildingMenu = true;
4070 new Thread(new Runnable()
4075 final List<JMenuItem> legacyItems = new ArrayList<>();
4078 // System.err.println("Building ws menu again "
4079 // + Thread.currentThread());
4080 // TODO: add support for context dependent disabling of services based
4082 // alignment and current selection
4083 // TODO: add additional serviceHandle parameter to specify abstract
4085 // class independently of AbstractName
4086 // TODO: add in rediscovery GUI function to restart discoverer
4087 // TODO: group services by location as well as function and/or
4089 // object broker mechanism.
4090 final Vector<JMenu> wsmenu = new Vector<>();
4091 final IProgressIndicator af = me;
4094 * do not i18n these strings - they are hard-coded in class
4095 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4096 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4098 final JMenu msawsmenu = new JMenu("Alignment");
4099 final JMenu secstrmenu = new JMenu(
4100 "Secondary Structure Prediction");
4101 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4102 final JMenu analymenu = new JMenu("Analysis");
4103 final JMenu dismenu = new JMenu("Protein Disorder");
4104 // JAL-940 - only show secondary structure prediction services from
4105 // the legacy server
4106 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4108 Discoverer.services != null && (Discoverer.services.size() > 0))
4110 // TODO: refactor to allow list of AbstractName/Handler bindings to
4112 // stored or retrieved from elsewhere
4113 // No MSAWS used any more:
4114 // Vector msaws = null; // (Vector)
4115 // Discoverer.services.get("MsaWS");
4116 Vector secstrpr = (Vector) Discoverer.services
4118 if (secstrpr != null)
4120 // Add any secondary structure prediction services
4121 for (int i = 0, j = secstrpr.size(); i < j; i++)
4123 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4125 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4126 .getServiceClient(sh);
4127 int p = secstrmenu.getItemCount();
4128 impl.attachWSMenuEntry(secstrmenu, me);
4129 int q = secstrmenu.getItemCount();
4130 for (int litm = p; litm < q; litm++)
4132 legacyItems.add(secstrmenu.getItem(litm));
4138 // Add all submenus in the order they should appear on the web
4140 wsmenu.add(msawsmenu);
4141 wsmenu.add(secstrmenu);
4142 wsmenu.add(dismenu);
4143 wsmenu.add(analymenu);
4144 // No search services yet
4145 // wsmenu.add(seqsrchmenu);
4147 javax.swing.SwingUtilities.invokeLater(new Runnable()
4154 webService.removeAll();
4155 // first, add discovered services onto the webservices menu
4156 if (wsmenu.size() > 0)
4158 for (int i = 0, j = wsmenu.size(); i < j; i++)
4160 webService.add(wsmenu.get(i));
4165 webService.add(me.webServiceNoServices);
4167 // TODO: move into separate menu builder class.
4168 boolean new_sspred = false;
4169 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4171 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4172 if (jws2servs != null)
4174 if (jws2servs.hasServices())
4176 jws2servs.attachWSMenuEntry(webService, me);
4177 for (Jws2Instance sv : jws2servs.getServices())
4179 if (sv.description.toLowerCase().contains("jpred"))
4181 for (JMenuItem jmi : legacyItems)
4183 jmi.setVisible(false);
4189 if (jws2servs.isRunning())
4191 JMenuItem tm = new JMenuItem(
4192 "Still discovering JABA Services");
4193 tm.setEnabled(false);
4198 build_urlServiceMenu(me.webService);
4199 build_fetchdbmenu(webService);
4200 for (JMenu item : wsmenu)
4202 if (item.getItemCount() == 0)
4204 item.setEnabled(false);
4208 item.setEnabled(true);
4211 } catch (Exception e)
4214 "Exception during web service menu building process.",
4219 } catch (Exception e)
4222 buildingMenu = false;
4229 * construct any groupURL type service menu entries.
4233 private void build_urlServiceMenu(JMenu webService)
4235 // TODO: remove this code when 2.7 is released
4236 // DEBUG - alignmentView
4238 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4239 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4241 * @Override public void actionPerformed(ActionEvent e) {
4242 * jalview.datamodel.AlignmentView
4243 * .testSelectionViews(af.viewport.getAlignment(),
4244 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4246 * }); webService.add(testAlView);
4248 // TODO: refactor to RestClient discoverer and merge menu entries for
4249 // rest-style services with other types of analysis/calculation service
4250 // SHmmr test client - still being implemented.
4251 // DEBUG - alignmentView
4253 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4256 client.attachWSMenuEntry(
4257 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4263 * Searches the alignment sequences for xRefs and builds the Show
4264 * Cross-References menu (formerly called Show Products), with database
4265 * sources for which cross-references are found (protein sources for a
4266 * nucleotide alignment and vice versa)
4268 * @return true if Show Cross-references menu should be enabled
4270 public boolean canShowProducts()
4272 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4273 AlignmentI dataset = viewport.getAlignment().getDataset();
4275 showProducts.removeAll();
4276 final boolean dna = viewport.getAlignment().isNucleotide();
4278 if (seqs == null || seqs.length == 0)
4280 // nothing to see here.
4284 boolean showp = false;
4287 List<String> ptypes = new CrossRef(seqs, dataset)
4288 .findXrefSourcesForSequences(dna);
4290 for (final String source : ptypes)
4293 final AlignFrame af = this;
4294 JMenuItem xtype = new JMenuItem(source);
4295 xtype.addActionListener(new ActionListener()
4298 public void actionPerformed(ActionEvent e)
4300 showProductsFor(af.viewport.getSequenceSelection(), dna,
4304 showProducts.add(xtype);
4306 showProducts.setVisible(showp);
4307 showProducts.setEnabled(showp);
4308 } catch (Exception e)
4311 "canShowProducts threw an exception - please report to help@jalview.org",
4319 * Finds and displays cross-references for the selected sequences (protein
4320 * products for nucleotide sequences, dna coding sequences for peptides).
4323 * the sequences to show cross-references for
4325 * true if from a nucleotide alignment (so showing proteins)
4327 * the database to show cross-references for
4329 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4330 final String source)
4332 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4337 * Construct and display a new frame containing the translation of this
4338 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4341 public void showTranslation_actionPerformed(ActionEvent e)
4343 AlignmentI al = null;
4346 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4348 al = dna.translateCdna();
4349 } catch (Exception ex)
4351 jalview.bin.Cache.log.error(
4352 "Exception during translation. Please report this !", ex);
4353 final String msg = MessageManager.getString(
4354 "label.error_when_translating_sequences_submit_bug_report");
4355 final String errorTitle = MessageManager
4356 .getString("label.implementation_error")
4357 + MessageManager.getString("label.translation_failed");
4358 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4359 JvOptionPane.ERROR_MESSAGE);
4362 if (al == null || al.getHeight() == 0)
4364 final String msg = MessageManager.getString(
4365 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4366 final String errorTitle = MessageManager
4367 .getString("label.translation_failed");
4368 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4369 JvOptionPane.WARNING_MESSAGE);
4373 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4374 af.setFileFormat(this.currentFileFormat);
4375 final String newTitle = MessageManager
4376 .formatMessage("label.translation_of_params", new Object[]
4377 { this.getTitle() });
4378 af.setTitle(newTitle);
4379 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4381 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4382 viewport.openSplitFrame(af, new Alignment(seqs));
4386 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4393 * Set the file format
4397 public void setFileFormat(FileFormatI format)
4399 this.currentFileFormat = format;
4403 * Try to load a features file onto the alignment.
4406 * contents or path to retrieve file or a File object
4408 * access mode of file (see jalview.io.AlignFile)
4409 * @return true if features file was parsed correctly.
4411 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4414 return avc.parseFeaturesFile(file, sourceType,
4415 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4420 public void refreshFeatureUI(boolean enableIfNecessary)
4422 // note - currently this is only still here rather than in the controller
4423 // because of the featureSettings hard reference that is yet to be
4425 if (enableIfNecessary)
4427 viewport.setShowSequenceFeatures(true);
4428 showSeqFeatures.setSelected(true);
4434 public void dragEnter(DropTargetDragEvent evt)
4439 public void dragExit(DropTargetEvent evt)
4444 public void dragOver(DropTargetDragEvent evt)
4449 public void dropActionChanged(DropTargetDragEvent evt)
4454 public void drop(DropTargetDropEvent evt)
4456 // JAL-1552 - acceptDrop required before getTransferable call for
4457 // Java's Transferable for native dnd
4458 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4459 Transferable t = evt.getTransferable();
4462 final AlignFrame thisaf = this;
4463 final List<Object> files = new ArrayList<>();
4464 List<DataSourceType> protocols = new ArrayList<>();
4468 Desktop.transferFromDropTarget(files, protocols, evt, t);
4469 } catch (Exception e)
4471 e.printStackTrace();
4475 new Thread(new Runnable()
4482 // check to see if any of these files have names matching sequences
4485 SequenceIdMatcher idm = new SequenceIdMatcher(
4486 viewport.getAlignment().getSequencesArray());
4488 * Object[] { String,SequenceI}
4490 ArrayList<Object[]> filesmatched = new ArrayList<>();
4491 ArrayList<Object> filesnotmatched = new ArrayList<>();
4492 for (int i = 0; i < files.size(); i++)
4495 Object file = files.get(i);
4496 String fileName = file.toString();
4498 DataSourceType protocol = (file instanceof File ? DataSourceType.FILE : FormatAdapter.checkProtocol(fileName));
4499 if (protocol == DataSourceType.FILE)
4501 File fl = (file instanceof File ? (File) file : new File(fileName));
4502 pdbfn = fl.getName();
4504 else if (protocol == DataSourceType.URL)
4506 URL url = new URL(fileName);
4507 pdbfn = url.getFile();
4509 if (pdbfn.length() > 0)
4511 // attempt to find a match in the alignment
4512 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4513 int l = 0, c = pdbfn.indexOf(".");
4514 while (mtch == null && c != -1)
4519 } while ((c = pdbfn.indexOf(".", l)) > l);
4522 pdbfn = pdbfn.substring(0, l);
4524 mtch = idm.findAllIdMatches(pdbfn);
4531 type = new IdentifyFile().identify(file, protocol);
4532 } catch (Exception ex)
4536 if (type != null && type.isStructureFile())
4538 filesmatched.add(new Object[] { file, protocol, mtch });
4542 // File wasn't named like one of the sequences or wasn't a PDB
4544 filesnotmatched.add(file);
4548 if (filesmatched.size() > 0)
4550 boolean autoAssociate = Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4553 String msg = MessageManager.formatMessage(
4554 "label.automatically_associate_structure_files_with_sequences_same_name",
4556 { Integer.valueOf(filesmatched.size())
4558 String ttl = MessageManager.getString(
4559 "label.automatically_associate_structure_files_by_name");
4560 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4561 ttl, JvOptionPane.YES_NO_OPTION);
4562 autoAssociate = choice == JvOptionPane.YES_OPTION;
4566 for (Object[] fm : filesmatched)
4568 // try and associate
4569 // TODO: may want to set a standard ID naming formalism for
4570 // associating PDB files which have no IDs.
4571 for (SequenceI toassoc : (SequenceI[]) fm[2])
4573 PDBEntry pe = new AssociatePdbFileWithSeq()
4574 .associatePdbWithSeq((String) fm[0],
4575 (DataSourceType) fm[1], toassoc, false,
4579 System.err.println("Associated file : "
4580 + ((String) fm[0]) + " with "
4581 + toassoc.getDisplayId(true));
4585 // TODO: do we need to update overview ? only if features are
4587 alignPanel.paintAlignment(true, false);
4593 * add declined structures as sequences
4595 for (Object[] o : filesmatched)
4597 filesnotmatched.add(o[0]);
4601 if (filesnotmatched.size() > 0)
4603 if (assocfiles > 0 && (Cache.getDefault(
4604 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4605 || JvOptionPane.showConfirmDialog(thisaf,
4606 "<html>" + MessageManager.formatMessage(
4607 "label.ignore_unmatched_dropped_files_info",
4610 filesnotmatched.size())
4613 MessageManager.getString(
4614 "label.ignore_unmatched_dropped_files"),
4615 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4619 for (Object fn : filesnotmatched)
4621 loadJalviewDataFile(fn, null, null, null);
4625 } catch (Exception ex)
4627 ex.printStackTrace();
4635 * Attempt to load a "dropped" file or URL string, by testing in turn for
4637 * <li>an Annotation file</li>
4638 * <li>a JNet file</li>
4639 * <li>a features file</li>
4640 * <li>else try to interpret as an alignment file</li>
4644 * either a filename or a URL string.
4646 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4647 FileFormatI format, SequenceI assocSeq)
4649 // BH 2018 was String file
4652 if (sourceType == null)
4654 sourceType = FormatAdapter.checkProtocol(file);
4656 // if the file isn't identified, or not positively identified as some
4657 // other filetype (PFAM is default unidentified alignment file type) then
4658 // try to parse as annotation.
4659 boolean isAnnotation = (format == null
4660 || FileFormat.Pfam.equals(format))
4661 ? new AnnotationFile().annotateAlignmentView(viewport,
4667 // first see if its a T-COFFEE score file
4668 TCoffeeScoreFile tcf = null;
4671 tcf = new TCoffeeScoreFile(file, sourceType);
4674 if (tcf.annotateAlignment(viewport.getAlignment(), true))
4678 new TCoffeeColourScheme(viewport.getAlignment()));
4679 isAnnotation = true;
4680 statusBar.setText(MessageManager.getString(
4681 "label.successfully_pasted_tcoffee_scores_to_alignment"));
4685 // some problem - if no warning its probable that the ID matching
4686 // process didn't work
4687 JvOptionPane.showMessageDialog(Desktop.desktop,
4688 tcf.getWarningMessage() == null
4689 ? MessageManager.getString(
4690 "label.check_file_matches_sequence_ids_alignment")
4691 : tcf.getWarningMessage(),
4692 MessageManager.getString(
4693 "label.problem_reading_tcoffee_score_file"),
4694 JvOptionPane.WARNING_MESSAGE);
4701 } catch (Exception x)
4704 "Exception when processing data source as T-COFFEE score file",
4710 // try to see if its a JNet 'concise' style annotation file *before*
4712 // try to parse it as a features file
4715 format = new IdentifyFile().identify(file, sourceType);
4717 if (FileFormat.ScoreMatrix == format)
4719 ScoreMatrixFile sm = new ScoreMatrixFile(
4720 new FileParse(file, sourceType));
4722 // todo: i18n this message
4723 statusBar.setText(MessageManager.formatMessage(
4724 "label.successfully_loaded_matrix",
4725 sm.getMatrixName()));
4727 else if (FileFormat.Jnet.equals(format))
4729 JPredFile predictions = new JPredFile(file, sourceType);
4730 new JnetAnnotationMaker();
4731 JnetAnnotationMaker.add_annotation(predictions,
4732 viewport.getAlignment(), 0, false);
4733 viewport.getAlignment().setupJPredAlignment();
4734 isAnnotation = true;
4736 // else if (IdentifyFile.FeaturesFile.equals(format))
4737 else if (FileFormat.Features.equals(format))
4739 if (parseFeaturesFile(file, sourceType))
4741 alignPanel.paintAlignment(true, true);
4746 new FileLoader().LoadFile(viewport, file, sourceType, format);
4753 alignPanel.adjustAnnotationHeight();
4754 viewport.updateSequenceIdColours();
4755 buildSortByAnnotationScoresMenu();
4756 alignPanel.paintAlignment(true, true);
4758 } catch (Exception ex)
4760 ex.printStackTrace();
4761 } catch (OutOfMemoryError oom)
4766 } catch (Exception x)
4771 + (sourceType != null
4772 ? (sourceType == DataSourceType.PASTE
4774 : "using " + sourceType + " from "
4778 ? "(parsing as '" + format + "' file)"
4780 oom, Desktop.desktop);
4785 * Method invoked by the ChangeListener on the tabbed pane, in other words
4786 * when a different tabbed pane is selected by the user or programmatically.
4789 public void tabSelectionChanged(int index)
4793 alignPanel = alignPanels.get(index);
4794 viewport = alignPanel.av;
4795 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4796 setMenusFromViewport(viewport);
4800 * 'focus' any colour slider that is open to the selected viewport
4802 if (viewport.getConservationSelected())
4804 SliderPanel.setConservationSlider(alignPanel,
4805 viewport.getResidueShading(), alignPanel.getViewName());
4809 SliderPanel.hideConservationSlider();
4811 if (viewport.getAbovePIDThreshold())
4813 SliderPanel.setPIDSliderSource(alignPanel,
4814 viewport.getResidueShading(), alignPanel.getViewName());
4818 SliderPanel.hidePIDSlider();
4822 * If there is a frame linked to this one in a SplitPane, switch it to the
4823 * same view tab index. No infinite recursion of calls should happen, since
4824 * tabSelectionChanged() should not get invoked on setting the selected
4825 * index to an unchanged value. Guard against setting an invalid index
4826 * before the new view peer tab has been created.
4828 final AlignViewportI peer = viewport.getCodingComplement();
4831 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4832 .getAlignPanel().alignFrame;
4833 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4835 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4841 * On right mouse click on view tab, prompt for and set new view name.
4844 public void tabbedPane_mousePressed(MouseEvent e)
4846 if (e.isPopupTrigger())
4848 String msg = MessageManager.getString("label.enter_view_name");
4849 String reply = JvOptionPane.showInternalInputDialog(this, msg, msg,
4850 JvOptionPane.QUESTION_MESSAGE);
4854 viewport.viewName = reply;
4855 // TODO warn if reply is in getExistingViewNames()?
4856 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4861 public AlignViewport getCurrentView()
4867 * Open the dialog for regex description parsing.
4870 protected void extractScores_actionPerformed(ActionEvent e)
4872 ParseProperties pp = new jalview.analysis.ParseProperties(
4873 viewport.getAlignment());
4874 // TODO: verify regex and introduce GUI dialog for version 2.5
4875 // if (pp.getScoresFromDescription("col", "score column ",
4876 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4878 if (pp.getScoresFromDescription("description column",
4879 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4881 buildSortByAnnotationScoresMenu();
4889 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4893 protected void showDbRefs_actionPerformed(ActionEvent e)
4895 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4901 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4905 protected void showNpFeats_actionPerformed(ActionEvent e)
4907 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4911 * find the viewport amongst the tabs in this alignment frame and close that
4916 public boolean closeView(AlignViewportI av)
4920 this.closeMenuItem_actionPerformed(false);
4923 Component[] comp = tabbedPane.getComponents();
4924 for (int i = 0; comp != null && i < comp.length; i++)
4926 if (comp[i] instanceof AlignmentPanel)
4928 if (((AlignmentPanel) comp[i]).av == av)
4931 closeView((AlignmentPanel) comp[i]);
4939 protected void build_fetchdbmenu(JMenu webService)
4941 // Temporary hack - DBRef Fetcher always top level ws entry.
4942 // TODO We probably want to store a sequence database checklist in
4943 // preferences and have checkboxes.. rather than individual sources selected
4945 final JMenu rfetch = new JMenu(
4946 MessageManager.getString("action.fetch_db_references"));
4947 rfetch.setToolTipText(MessageManager.getString(
4948 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4949 webService.add(rfetch);
4951 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4952 MessageManager.getString("option.trim_retrieved_seqs"));
4953 trimrs.setToolTipText(
4954 MessageManager.getString("label.trim_retrieved_sequences"));
4956 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
4957 trimrs.addActionListener(new ActionListener()
4960 public void actionPerformed(ActionEvent e)
4962 trimrs.setSelected(trimrs.isSelected());
4963 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
4964 Boolean.valueOf(trimrs.isSelected()).toString());
4968 JMenuItem fetchr = new JMenuItem(
4969 MessageManager.getString("label.standard_databases"));
4970 fetchr.setToolTipText(
4971 MessageManager.getString("label.fetch_embl_uniprot"));
4972 fetchr.addActionListener(new ActionListener()
4976 public void actionPerformed(ActionEvent e)
4978 new Thread(new Runnable()
4983 boolean isNucleotide = alignPanel.alignFrame.getViewport()
4984 .getAlignment().isNucleotide();
4985 DBRefFetcher dbRefFetcher = new DBRefFetcher(
4986 alignPanel.av.getSequenceSelection(),
4987 alignPanel.alignFrame, null,
4988 alignPanel.alignFrame.featureSettings, isNucleotide);
4989 dbRefFetcher.addListener(new FetchFinishedListenerI()
4992 public void finished()
4994 AlignFrame.this.setMenusForViewport();
4997 dbRefFetcher.fetchDBRefs(false);
5005 final AlignFrame me = this;
5006 new Thread(new Runnable()
5011 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5012 .getSequenceFetcherSingleton(me);
5013 javax.swing.SwingUtilities.invokeLater(new Runnable()
5018 String[] dbclasses = sf.getOrderedSupportedSources();
5019 // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5020 // jalview.util.QuickSort.sort(otherdb, otherdb);
5021 List<DbSourceProxy> otherdb;
5022 JMenu dfetch = new JMenu();
5023 JMenu ifetch = new JMenu();
5024 JMenuItem fetchr = null;
5025 int comp = 0, icomp = 0, mcomp = 15;
5026 String mname = null;
5028 for (String dbclass : dbclasses)
5030 otherdb = sf.getSourceProxy(dbclass);
5031 // add a single entry for this class, or submenu allowing 'fetch
5033 if (otherdb == null || otherdb.size() < 1)
5037 // List<DbSourceProxy> dbs=otherdb;
5038 // otherdb=new ArrayList<DbSourceProxy>();
5039 // for (DbSourceProxy db:dbs)
5041 // if (!db.isA(DBRefSource.ALIGNMENTDB)
5045 mname = "From " + dbclass;
5047 if (otherdb.size() == 1)
5049 final DbSourceProxy[] dassource = otherdb
5050 .toArray(new DbSourceProxy[0]);
5051 DbSourceProxy src = otherdb.get(0);
5052 fetchr = new JMenuItem(src.getDbSource());
5053 fetchr.addActionListener(new ActionListener()
5057 public void actionPerformed(ActionEvent e)
5059 new Thread(new Runnable()
5065 boolean isNucleotide = alignPanel.alignFrame
5066 .getViewport().getAlignment()
5068 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5069 alignPanel.av.getSequenceSelection(),
5070 alignPanel.alignFrame, dassource,
5071 alignPanel.alignFrame.featureSettings,
5074 .addListener(new FetchFinishedListenerI()
5077 public void finished()
5079 AlignFrame.this.setMenusForViewport();
5082 dbRefFetcher.fetchDBRefs(false);
5088 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5089 MessageManager.formatMessage(
5090 "label.fetch_retrieve_from", new Object[]
5091 { src.getDbName() })));
5097 final DbSourceProxy[] dassource = otherdb
5098 .toArray(new DbSourceProxy[0]);
5100 DbSourceProxy src = otherdb.get(0);
5101 fetchr = new JMenuItem(MessageManager
5102 .formatMessage("label.fetch_all_param", new Object[]
5103 { src.getDbSource() }));
5104 fetchr.addActionListener(new ActionListener()
5107 public void actionPerformed(ActionEvent e)
5109 new Thread(new Runnable()
5115 boolean isNucleotide = alignPanel.alignFrame
5116 .getViewport().getAlignment()
5118 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5119 alignPanel.av.getSequenceSelection(),
5120 alignPanel.alignFrame, dassource,
5121 alignPanel.alignFrame.featureSettings,
5124 .addListener(new FetchFinishedListenerI()
5127 public void finished()
5129 AlignFrame.this.setMenusForViewport();
5132 dbRefFetcher.fetchDBRefs(false);
5138 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5139 MessageManager.formatMessage(
5140 "label.fetch_retrieve_from_all_sources",
5142 { Integer.valueOf(otherdb.size())
5144 src.getDbSource(), src.getDbName() })));
5147 // and then build the rest of the individual menus
5148 ifetch = new JMenu(MessageManager.formatMessage(
5149 "label.source_from_db_source", new Object[]
5150 { src.getDbSource() }));
5152 String imname = null;
5154 for (DbSourceProxy sproxy : otherdb)
5156 String dbname = sproxy.getDbName();
5157 String sname = dbname.length() > 5
5158 ? dbname.substring(0, 5) + "..."
5160 String msname = dbname.length() > 10
5161 ? dbname.substring(0, 10) + "..."
5165 imname = MessageManager
5166 .formatMessage("label.from_msname", new Object[]
5169 fetchr = new JMenuItem(msname);
5170 final DbSourceProxy[] dassrc = { sproxy };
5171 fetchr.addActionListener(new ActionListener()
5175 public void actionPerformed(ActionEvent e)
5177 new Thread(new Runnable()
5183 boolean isNucleotide = alignPanel.alignFrame
5184 .getViewport().getAlignment()
5186 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5187 alignPanel.av.getSequenceSelection(),
5188 alignPanel.alignFrame, dassrc,
5189 alignPanel.alignFrame.featureSettings,
5192 .addListener(new FetchFinishedListenerI()
5195 public void finished()
5197 AlignFrame.this.setMenusForViewport();
5200 dbRefFetcher.fetchDBRefs(false);
5206 fetchr.setToolTipText(
5207 "<html>" + MessageManager.formatMessage(
5208 "label.fetch_retrieve_from", new Object[]
5212 if (++icomp >= mcomp || i == (otherdb.size()))
5214 ifetch.setText(MessageManager.formatMessage(
5215 "label.source_to_target", imname, sname));
5217 ifetch = new JMenu();
5225 if (comp >= mcomp || dbi >= (dbclasses.length))
5227 dfetch.setText(MessageManager.formatMessage(
5228 "label.source_to_target", mname, dbclass));
5230 dfetch = new JMenu();
5243 * Left justify the whole alignment.
5246 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5248 AlignmentI al = viewport.getAlignment();
5250 viewport.firePropertyChange("alignment", null, al);
5254 * Right justify the whole alignment.
5257 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5259 AlignmentI al = viewport.getAlignment();
5261 viewport.firePropertyChange("alignment", null, al);
5265 public void setShowSeqFeatures(boolean b)
5267 showSeqFeatures.setSelected(b);
5268 viewport.setShowSequenceFeatures(b);
5275 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5276 * awt.event.ActionEvent)
5279 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5281 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5282 alignPanel.paintAlignment(false, false);
5289 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5293 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5295 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5296 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5304 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5305 * .event.ActionEvent)
5308 protected void showGroupConservation_actionPerformed(ActionEvent e)
5310 viewport.setShowGroupConservation(showGroupConservation.getState());
5311 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5318 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5319 * .event.ActionEvent)
5322 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5324 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5325 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5332 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5333 * .event.ActionEvent)
5336 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5338 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5339 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5343 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5345 showSequenceLogo.setState(true);
5346 viewport.setShowSequenceLogo(true);
5347 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5348 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5352 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5354 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5361 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5362 * .event.ActionEvent)
5365 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5367 if (avc.makeGroupsFromSelection())
5369 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5370 alignPanel.updateAnnotation();
5371 alignPanel.paintAlignment(true, true);
5375 public void clearAlignmentSeqRep()
5377 // TODO refactor alignmentseqrep to controller
5378 if (viewport.getAlignment().hasSeqrep())
5380 viewport.getAlignment().setSeqrep(null);
5381 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5382 alignPanel.updateAnnotation();
5383 alignPanel.paintAlignment(true, true);
5388 protected void createGroup_actionPerformed(ActionEvent e)
5390 if (avc.createGroup())
5392 alignPanel.alignmentChanged();
5397 protected void unGroup_actionPerformed(ActionEvent e)
5401 alignPanel.alignmentChanged();
5406 * make the given alignmentPanel the currently selected tab
5408 * @param alignmentPanel
5410 public void setDisplayedView(AlignmentPanel alignmentPanel)
5412 if (!viewport.getSequenceSetId()
5413 .equals(alignmentPanel.av.getSequenceSetId()))
5415 throw new Error(MessageManager.getString(
5416 "error.implementation_error_cannot_show_view_alignment_frame"));
5418 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5419 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5421 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5426 * Action on selection of menu options to Show or Hide annotations.
5429 * @param forSequences
5430 * update sequence-related annotations
5431 * @param forAlignment
5432 * update non-sequence-related annotations
5435 protected void setAnnotationsVisibility(boolean visible,
5436 boolean forSequences, boolean forAlignment)
5438 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5439 .getAlignmentAnnotation();
5444 for (AlignmentAnnotation aa : anns)
5447 * don't display non-positional annotations on an alignment
5449 if (aa.annotations == null)
5453 boolean apply = (aa.sequenceRef == null && forAlignment)
5454 || (aa.sequenceRef != null && forSequences);
5457 aa.visible = visible;
5460 alignPanel.validateAnnotationDimensions(true);
5461 alignPanel.alignmentChanged();
5465 * Store selected annotation sort order for the view and repaint.
5468 protected void sortAnnotations_actionPerformed()
5470 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5472 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5473 alignPanel.paintAlignment(false, false);
5478 * @return alignment panels in this alignment frame
5480 public List<? extends AlignmentViewPanel> getAlignPanels()
5482 return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5486 * Open a new alignment window, with the cDNA associated with this (protein)
5487 * alignment, aligned as is the protein.
5489 protected void viewAsCdna_actionPerformed()
5491 // TODO no longer a menu action - refactor as required
5492 final AlignmentI alignment = getViewport().getAlignment();
5493 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5494 if (mappings == null)
5498 List<SequenceI> cdnaSeqs = new ArrayList<>();
5499 for (SequenceI aaSeq : alignment.getSequences())
5501 for (AlignedCodonFrame acf : mappings)
5503 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5507 * There is a cDNA mapping for this protein sequence - add to new
5508 * alignment. It will share the same dataset sequence as other mapped
5509 * cDNA (no new mappings need to be created).
5511 final Sequence newSeq = new Sequence(dnaSeq);
5512 newSeq.setDatasetSequence(dnaSeq);
5513 cdnaSeqs.add(newSeq);
5517 if (cdnaSeqs.size() == 0)
5519 // show a warning dialog no mapped cDNA
5522 AlignmentI cdna = new Alignment(
5523 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5524 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5525 AlignFrame.DEFAULT_HEIGHT);
5526 cdna.alignAs(alignment);
5527 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5529 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5530 AlignFrame.DEFAULT_HEIGHT);
5534 * Set visibility of dna/protein complement view (available when shown in a
5540 protected void showComplement_actionPerformed(boolean show)
5542 SplitContainerI sf = getSplitViewContainer();
5545 sf.setComplementVisible(this, show);
5550 * Generate the reverse (optionally complemented) of the selected sequences,
5551 * and add them to the alignment
5554 protected void showReverse_actionPerformed(boolean complement)
5556 AlignmentI al = null;
5559 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5560 al = dna.reverseCdna(complement);
5561 viewport.addAlignment(al, "");
5562 addHistoryItem(new EditCommand(
5563 MessageManager.getString("label.add_sequences"), Action.PASTE,
5564 al.getSequencesArray(), 0, al.getWidth(),
5565 viewport.getAlignment()));
5566 } catch (Exception ex)
5568 System.err.println(ex.getMessage());
5574 * Try to run a script in the Groovy console, having first ensured that this
5575 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5576 * be targeted at this alignment.
5579 protected void runGroovy_actionPerformed()
5581 Jalview.setCurrentAlignFrame(this);
5582 groovy.ui.Console console = Desktop.getGroovyConsole();
5583 if (console != null)
5587 console.runScript();
5588 } catch (Exception ex)
5590 System.err.println((ex.toString()));
5591 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5592 MessageManager.getString("label.couldnt_run_groovy_script"),
5593 MessageManager.getString("label.groovy_support_failed"),
5594 JvOptionPane.ERROR_MESSAGE);
5599 System.err.println("Can't run Groovy script as console not found");
5604 * Hides columns containing (or not containing) a specified feature, provided
5605 * that would not leave all columns hidden
5607 * @param featureType
5608 * @param columnsContaining
5611 public boolean hideFeatureColumns(String featureType,
5612 boolean columnsContaining)
5614 boolean notForHiding = avc.markColumnsContainingFeatures(
5615 columnsContaining, false, false, featureType);
5618 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5619 false, featureType))
5621 getViewport().hideSelectedColumns();
5629 protected void selectHighlightedColumns_actionPerformed(
5630 ActionEvent actionEvent)
5632 // include key modifier check in case user selects from menu
5633 avc.markHighlightedColumns(
5634 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5635 (actionEvent.getModifiers() & (ActionEvent.META_MASK
5636 | ActionEvent.CTRL_MASK)) != 0);
5640 * Rebuilds the Colour menu, including any user-defined colours which have
5641 * been loaded either on startup or during the session
5643 public void buildColourMenu()
5645 colourMenu.removeAll();
5647 colourMenu.add(applyToAllGroups);
5648 colourMenu.add(textColour);
5649 colourMenu.addSeparator();
5651 ColourMenuHelper.addMenuItems(colourMenu, this, viewport.getAlignment(),
5654 colourMenu.addSeparator();
5655 colourMenu.add(conservationMenuItem);
5656 colourMenu.add(modifyConservation);
5657 colourMenu.add(abovePIDThreshold);
5658 colourMenu.add(modifyPID);
5659 colourMenu.add(annotationColour);
5661 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5662 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5666 * Open a dialog (if not already open) that allows the user to select and
5667 * calculate PCA or Tree analysis
5669 protected void openTreePcaDialog()
5671 if (alignPanel.getCalculationDialog() == null)
5673 new CalculationChooser(AlignFrame.this);
5678 protected void loadVcf_actionPerformed()
5680 // TODO: JAL-3048 - No VCF support in JsJalview
5681 JalviewFileChooser chooser = new JalviewFileChooser(
5682 Cache.getProperty("LAST_DIRECTORY"));
5683 chooser.setFileView(new JalviewFileView());
5684 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5685 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5687 int value = chooser.showOpenDialog(null);
5689 if (value == JalviewFileChooser.APPROVE_OPTION)
5691 String choice = chooser.getSelectedFile().getPath();
5692 Cache.setProperty("LAST_DIRECTORY", choice);
5693 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5694 new VCFLoader(choice).loadVCF(seqs, this);
5701 class PrintThread extends Thread
5705 public PrintThread(AlignmentPanel ap)
5710 static PageFormat pf;
5715 PrinterJob printJob = PrinterJob.getPrinterJob();
5719 printJob.setPrintable(ap, pf);
5723 printJob.setPrintable(ap);
5726 if (printJob.printDialog())
5731 } catch (Exception PrintException)
5733 PrintException.printStackTrace();