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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Dimension;
27 import java.awt.GridLayout;
28 import java.awt.Rectangle;
29 import java.awt.Toolkit;
30 import java.awt.datatransfer.Clipboard;
31 import java.awt.datatransfer.DataFlavor;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.datatransfer.Transferable;
34 import java.awt.dnd.DnDConstants;
35 import java.awt.dnd.DropTargetDragEvent;
36 import java.awt.dnd.DropTargetDropEvent;
37 import java.awt.dnd.DropTargetEvent;
38 import java.awt.dnd.DropTargetListener;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.FocusAdapter;
42 import java.awt.event.FocusEvent;
43 import java.awt.event.ItemEvent;
44 import java.awt.event.ItemListener;
45 import java.awt.event.KeyAdapter;
46 import java.awt.event.KeyEvent;
47 import java.awt.event.MouseEvent;
48 import java.awt.print.PageFormat;
49 import java.awt.print.PrinterJob;
50 import java.beans.PropertyChangeEvent;
52 import java.io.FileWriter;
53 import java.io.IOException;
54 import java.io.PrintWriter;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Deque;
59 import java.util.Enumeration;
60 import java.util.Hashtable;
61 import java.util.List;
62 import java.util.Locale;
64 import java.util.Map.Entry;
65 import java.util.StringTokenizer;
66 import java.util.Vector;
68 import javax.swing.ButtonGroup;
69 import javax.swing.JCheckBoxMenuItem;
70 import javax.swing.JComboBox;
71 import javax.swing.JComponent;
72 import javax.swing.JEditorPane;
73 import javax.swing.JInternalFrame;
74 import javax.swing.JLabel;
75 import javax.swing.JLayeredPane;
76 import javax.swing.JMenu;
77 import javax.swing.JMenuItem;
78 import javax.swing.JPanel;
79 import javax.swing.JScrollPane;
80 import javax.swing.SwingUtilities;
82 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
83 import org.forester.archaeopteryx.webservices.WebservicesManager;
85 import ext.vamsas.ServiceHandle;
86 import jalview.analysis.AlignmentSorter;
87 import jalview.analysis.AlignmentUtils;
88 import jalview.analysis.CrossRef;
89 import jalview.analysis.Dna;
90 import jalview.analysis.GeneticCodeI;
91 import jalview.analysis.ParseProperties;
92 import jalview.analysis.SequenceIdMatcher;
93 import jalview.analysis.TreeModel;
94 import jalview.api.AlignExportSettingsI;
95 import jalview.api.AlignViewControllerGuiI;
96 import jalview.api.AlignViewControllerI;
97 import jalview.api.AlignViewportI;
98 import jalview.api.AlignmentViewPanel;
99 import jalview.api.FeatureSettingsControllerI;
100 import jalview.api.FeatureSettingsModelI;
101 import jalview.api.SplitContainerI;
102 import jalview.api.ViewStyleI;
103 import jalview.bin.Cache;
104 import jalview.bin.Console;
105 import jalview.bin.Jalview;
106 import jalview.commands.CommandI;
107 import jalview.commands.EditCommand;
108 import jalview.commands.EditCommand.Action;
109 import jalview.commands.OrderCommand;
110 import jalview.commands.RemoveGapColCommand;
111 import jalview.commands.RemoveGapsCommand;
112 import jalview.commands.SlideSequencesCommand;
113 import jalview.commands.TrimRegionCommand;
114 import jalview.datamodel.AlignExportSettingsAdapter;
115 import jalview.datamodel.AlignedCodonFrame;
116 import jalview.datamodel.Alignment;
117 import jalview.datamodel.AlignmentAnnotation;
118 import jalview.datamodel.AlignmentExportData;
119 import jalview.datamodel.AlignmentI;
120 import jalview.datamodel.AlignmentOrder;
121 import jalview.datamodel.AlignmentView;
122 import jalview.datamodel.ColumnSelection;
123 import jalview.datamodel.DBRefEntry;
124 import jalview.datamodel.HiddenColumns;
125 import jalview.datamodel.PDBEntry;
126 import jalview.datamodel.SeqCigar;
127 import jalview.datamodel.Sequence;
128 import jalview.datamodel.SequenceGroup;
129 import jalview.datamodel.SequenceI;
130 import jalview.ext.archaeopteryx.AptxInit;
131 import jalview.ext.forester.io.SupportedTreeFileFilter;
132 import jalview.ext.treeviewer.TreeFrameI;
133 import jalview.ext.treeviewer.TreeViewerBindingI;
134 import jalview.ext.treeviewer.TreeViewerUtils;
135 import jalview.gui.ColourMenuHelper.ColourChangeListener;
136 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
137 import jalview.io.AlignmentProperties;
138 import jalview.io.AnnotationFile;
139 import jalview.io.BackupFiles;
140 import jalview.io.BioJsHTMLOutput;
141 import jalview.io.DataSourceType;
142 import jalview.io.FileFormat;
143 import jalview.io.FileFormatI;
144 import jalview.io.FileFormats;
145 import jalview.io.FileLoader;
146 import jalview.io.FileParse;
147 import jalview.io.FormatAdapter;
148 import jalview.io.HtmlSvgOutput;
149 import jalview.io.IdentifyFile;
150 import jalview.io.JPredFile;
151 import jalview.io.JalviewFileChooser;
152 import jalview.io.JalviewFileView;
153 import jalview.io.JnetAnnotationMaker;
154 import jalview.io.NewickFile;
155 import jalview.io.ScoreMatrixFile;
156 import jalview.io.TCoffeeScoreFile;
157 import jalview.io.vcf.VCFLoader;
158 import jalview.jbgui.GAlignFrame;
159 import jalview.project.Jalview2XML;
160 import jalview.schemes.ColourSchemeI;
161 import jalview.schemes.ColourSchemes;
162 import jalview.schemes.ResidueColourScheme;
163 import jalview.schemes.TCoffeeColourScheme;
164 import jalview.util.DBRefUtils;
165 import jalview.util.HttpUtils;
166 import jalview.util.ImageMaker.TYPE;
167 import jalview.util.MessageManager;
168 import jalview.util.Platform;
169 import jalview.viewmodel.AlignmentViewport;
170 import jalview.viewmodel.ViewportRanges;
171 import jalview.ws.DBRefFetcher;
172 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
173 import jalview.ws.jws1.Discoverer;
174 import jalview.ws.jws2.Jws2Discoverer;
175 import jalview.ws.jws2.jabaws2.Jws2Instance;
176 import jalview.ws.seqfetcher.DbSourceProxy;
182 * @version $Revision$
184 @SuppressWarnings("serial")
185 public class AlignFrame extends GAlignFrame implements DropTargetListener,
186 IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
189 public static final int DEFAULT_WIDTH = 700;
191 public static final int DEFAULT_HEIGHT = 500;
194 * The currently displayed panel (selected tabbed view if more than one)
196 public AlignmentPanel alignPanel;
198 AlignViewport viewport;
200 public AlignViewControllerI avc;
202 List<AlignmentPanel> alignPanels = new ArrayList<>();
205 * Last format used to load or save alignments in this window
207 FileFormatI currentFileFormat = null;
210 * Current filename for this alignment
212 String fileName = null;
217 * Creates a new AlignFrame object with specific width and height.
223 public AlignFrame(AlignmentI al, int width, int height)
225 this(al, null, width, height);
229 * Creates a new AlignFrame object with specific width, height and
235 * @param sequenceSetId
237 public AlignFrame(AlignmentI al, int width, int height,
238 String sequenceSetId)
240 this(al, null, width, height, sequenceSetId);
244 * Creates a new AlignFrame object with specific width, height and
250 * @param sequenceSetId
253 public AlignFrame(AlignmentI al, int width, int height,
254 String sequenceSetId, String viewId)
256 this(al, null, width, height, sequenceSetId, viewId);
260 * new alignment window with hidden columns
264 * @param hiddenColumns
265 * ColumnSelection or null
267 * Width of alignment frame
271 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
274 this(al, hiddenColumns, width, height, null);
278 * Create alignment frame for al with hiddenColumns, a specific width and
279 * height, and specific sequenceId
282 * @param hiddenColumns
285 * @param sequenceSetId
288 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
289 int height, String sequenceSetId)
291 this(al, hiddenColumns, width, height, sequenceSetId, null);
295 * Create alignment frame for al with hiddenColumns, a specific width and
296 * height, and specific sequenceId
299 * @param hiddenColumns
302 * @param sequenceSetId
307 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
308 int height, String sequenceSetId, String viewId)
310 setSize(width, height);
312 if (al.getDataset() == null)
317 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
319 alignPanel = new AlignmentPanel(this, viewport);
321 addAlignmentPanel(alignPanel, true);
325 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
326 HiddenColumns hiddenColumns, int width, int height)
328 setSize(width, height);
330 if (al.getDataset() == null)
335 viewport = new AlignViewport(al, hiddenColumns);
337 if (hiddenSeqs != null && hiddenSeqs.length > 0)
339 viewport.hideSequence(hiddenSeqs);
341 alignPanel = new AlignmentPanel(this, viewport);
342 addAlignmentPanel(alignPanel, true);
347 * Make a new AlignFrame from existing alignmentPanels
354 public AlignFrame(AlignmentPanel ap)
358 addAlignmentPanel(ap, false);
363 * initalise the alignframe from the underlying viewport data and the
368 // setBackground(Color.white); // BH 2019
370 if (!Jalview.isHeadlessMode())
372 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
375 avc = new jalview.controller.AlignViewController(this, viewport,
377 if (viewport.getAlignmentConservationAnnotation() == null)
379 // BLOSUM62Colour.setEnabled(false);
380 conservationMenuItem.setEnabled(false);
381 modifyConservation.setEnabled(false);
382 // PIDColour.setEnabled(false);
383 // abovePIDThreshold.setEnabled(false);
384 // modifyPID.setEnabled(false);
387 String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
389 if (sortby.equals("Id"))
391 sortIDMenuItem_actionPerformed(null);
393 else if (sortby.equals("Pairwise Identity"))
395 sortPairwiseMenuItem_actionPerformed(null);
399 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
401 setMenusFromViewport(viewport);
402 buildSortByAnnotationScoresMenu();
403 calculateTree.addActionListener(new ActionListener()
407 public void actionPerformed(ActionEvent e)
414 if (Desktop.desktop != null)
416 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
417 if (!Platform.isJS())
419 addServiceListeners();
424 if (viewport.getWrapAlignment())
426 wrapMenuItem_actionPerformed(null);
429 if (Cache.getDefault("SHOW_OVERVIEW", false))
431 this.overviewMenuItem_actionPerformed(null);
436 final List<AlignmentViewPanel> selviews = new ArrayList<>();
437 final List<AlignmentPanel> origview = new ArrayList<>();
438 final String menuLabel = MessageManager
439 .getString("label.copy_format_from");
440 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
441 new ViewSetProvider()
445 public AlignmentPanel[] getAllAlignmentPanels()
448 origview.add(alignPanel);
449 // make an array of all alignment panels except for this one
450 List<AlignmentPanel> aps = new ArrayList<>(
451 Arrays.asList(Desktop.getAlignmentPanels(null)));
452 aps.remove(AlignFrame.this.alignPanel);
453 return aps.toArray(new AlignmentPanel[aps.size()]);
455 }, selviews, new ItemListener()
459 public void itemStateChanged(ItemEvent e)
461 if (origview.size() > 0)
463 final AlignmentPanel ap = origview.get(0);
466 * Copy the ViewStyle of the selected panel to 'this one'.
467 * Don't change value of 'scaleProteinAsCdna' unless copying
470 ViewStyleI vs = selviews.get(0).getAlignViewport()
472 boolean fromSplitFrame = selviews.get(0)
473 .getAlignViewport().getCodingComplement() != null;
476 vs.setScaleProteinAsCdna(ap.getAlignViewport()
477 .getViewStyle().isScaleProteinAsCdna());
479 ap.getAlignViewport().setViewStyle(vs);
482 * Also rescale ViewStyle of SplitFrame complement if there is
483 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
484 * the whole ViewStyle (allow cDNA protein to have different
487 AlignViewportI complement = ap.getAlignViewport()
488 .getCodingComplement();
489 if (complement != null && vs.isScaleProteinAsCdna())
491 AlignFrame af = Desktop.getAlignFrameFor(complement);
492 ((SplitFrame) af.getSplitViewContainer())
494 af.setMenusForViewport();
498 ap.setSelected(true);
499 ap.alignFrame.setMenusForViewport();
504 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
505 .indexOf("devel") > -1
506 || Cache.getDefault("VERSION", "DEVELOPMENT")
507 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
509 formatMenu.add(vsel);
511 addFocusListener(new FocusAdapter()
514 public void focusGained(FocusEvent e)
516 Jalview.setCurrentAlignFrame(AlignFrame.this);
523 * Change the filename and format for the alignment, and enable the 'reload'
524 * button functionality.
531 public void setFileName(String file, FileFormatI format)
534 setFileFormat(format);
535 reload.setEnabled(true);
539 * JavaScript will have this, maybe others. More dependable than a file name
540 * and maintains a reference to the actual bytes loaded.
544 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, evt.isShiftDown());
590 if (evt.isAltDown() || !viewport.cursorMode)
592 moveSelectedSequences(true);
594 if (viewport.cursorMode)
596 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
601 case KeyEvent.VK_LEFT:
602 if (evt.isAltDown() || !viewport.cursorMode)
604 slideSequences(false,
605 alignPanel.getSeqPanel().getKeyboardNo1());
609 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
614 case KeyEvent.VK_RIGHT:
615 if (evt.isAltDown() || !viewport.cursorMode)
617 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
621 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
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();
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 setStatus(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.getViewName() != null);
788 if (aSize == 1 && ap.av.getViewName() == null)
790 this.getContentPane().add(ap, BorderLayout.CENTER);
796 setInitialTabVisible();
799 expandViews.setEnabled(true);
800 gatherViews.setEnabled(true);
801 tabbedPane.addTab(ap.av.getViewName(), 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.getViewName(), 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 public 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 * Sets the text of the status bar. Note that setting a null or empty value
1018 * will cause the status bar to be hidden, with possibly undesirable flicker
1019 * of the screen layout.
1022 public void setStatus(String text)
1024 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1028 * Added so Castor Mapping file can obtain Jalview Version
1030 public String getVersion()
1032 return Cache.getProperty("VERSION");
1035 public FeatureRenderer getFeatureRenderer()
1037 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1041 public void fetchSequence_actionPerformed()
1043 new SequenceFetcher(this);
1047 public void addFromFile_actionPerformed(ActionEvent e)
1049 Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1053 public void reload_actionPerformed(ActionEvent e)
1055 if (fileName != null)
1057 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1058 // originating file's format
1059 // TODO: work out how to recover feature settings for correct view(s) when
1060 // file is reloaded.
1061 if (FileFormat.Jalview.equals(currentFileFormat))
1063 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1064 for (int i = 0; i < frames.length; i++)
1066 if (frames[i] instanceof AlignFrame && frames[i] != this
1067 && ((AlignFrame) frames[i]).fileName != null
1068 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1072 frames[i].setSelected(true);
1073 Desktop.instance.closeAssociatedWindows();
1074 } catch (java.beans.PropertyVetoException ex)
1080 Desktop.instance.closeAssociatedWindows();
1082 FileLoader loader = new FileLoader();
1083 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1084 ? DataSourceType.URL
1085 : DataSourceType.FILE;
1086 loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1090 Rectangle bounds = this.getBounds();
1092 FileLoader loader = new FileLoader();
1094 AlignFrame newframe = null;
1096 if (fileObject == null)
1099 DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1100 fileName) ? DataSourceType.URL : DataSourceType.FILE;
1101 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1106 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1107 DataSourceType.FILE, currentFileFormat);
1110 newframe.setBounds(bounds);
1111 if (featureSettings != null && featureSettings.isShowing())
1113 final Rectangle fspos = featureSettings.frame.getBounds();
1114 // TODO: need a 'show feature settings' function that takes bounds -
1115 // need to refactor Desktop.addFrame
1116 newframe.featureSettings_actionPerformed(null);
1117 final FeatureSettings nfs = newframe.featureSettings;
1118 SwingUtilities.invokeLater(new Runnable()
1123 nfs.frame.setBounds(fspos);
1126 this.featureSettings.close();
1127 this.featureSettings = null;
1129 this.closeMenuItem_actionPerformed(true);
1135 public void addFromText_actionPerformed(ActionEvent e)
1138 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1142 public void addFromURL_actionPerformed(ActionEvent e)
1144 Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1148 public void save_actionPerformed(ActionEvent e)
1150 if (fileName == null || (currentFileFormat == null)
1151 || HttpUtils.startsWithHttpOrHttps(fileName))
1153 saveAs_actionPerformed();
1157 saveAlignment(fileName, currentFileFormat);
1162 * Saves the alignment to a file with a name chosen by the user, if necessary
1163 * warning if a file would be overwritten
1166 public void saveAs_actionPerformed()
1168 String format = currentFileFormat == null ? null
1169 : currentFileFormat.getName();
1170 JalviewFileChooser chooser = JalviewFileChooser
1171 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1173 chooser.setFileView(new JalviewFileView());
1174 chooser.setDialogTitle(
1175 MessageManager.getString("label.save_alignment_to_file"));
1176 chooser.setToolTipText(MessageManager.getString("action.save"));
1178 int value = chooser.showSaveDialog(this);
1180 if (value != JalviewFileChooser.APPROVE_OPTION)
1184 currentFileFormat = chooser.getSelectedFormat();
1185 // todo is this (2005) test now obsolete - value is never null?
1186 while (currentFileFormat == null)
1188 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1190 .getString("label.select_file_format_before_saving"),
1191 MessageManager.getString("label.file_format_not_specified"),
1192 JvOptionPane.WARNING_MESSAGE);
1193 currentFileFormat = chooser.getSelectedFormat();
1194 value = chooser.showSaveDialog(this);
1195 if (value != JalviewFileChooser.APPROVE_OPTION)
1201 fileName = chooser.getSelectedFile().getPath();
1203 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1204 Cache.setProperty("LAST_DIRECTORY", fileName);
1205 saveAlignment(fileName, currentFileFormat);
1208 boolean lastSaveSuccessful = false;
1210 FileFormatI lastFormatSaved;
1212 String lastFilenameSaved;
1215 * Raise a dialog or status message for the last call to saveAlignment.
1217 * @return true if last call to saveAlignment(file, format) was successful.
1219 public boolean isSaveAlignmentSuccessful()
1222 if (!lastSaveSuccessful)
1224 if (!Platform.isHeadless())
1226 JvOptionPane.showInternalMessageDialog(this, MessageManager
1227 .formatMessage("label.couldnt_save_file", new Object[]
1228 { lastFilenameSaved }),
1229 MessageManager.getString("label.error_saving_file"),
1230 JvOptionPane.WARNING_MESSAGE);
1234 Console.error(MessageManager
1235 .formatMessage("label.couldnt_save_file", new Object[]
1236 { lastFilenameSaved }));
1242 setStatus(MessageManager.formatMessage(
1243 "label.successfully_saved_to_file_in_format", new Object[]
1244 { lastFilenameSaved, lastFormatSaved }));
1247 return lastSaveSuccessful;
1251 * Saves the alignment to the specified file path, in the specified format,
1252 * which may be an alignment format, or Jalview project format. If the
1253 * alignment has hidden regions, or the format is one capable of including
1254 * non-sequence data (features, annotations, groups), then the user may be
1255 * prompted to specify what to include in the output.
1260 public void saveAlignment(String file, FileFormatI format)
1262 lastSaveSuccessful = true;
1263 lastFilenameSaved = file;
1264 lastFormatSaved = format;
1266 if (FileFormat.Jalview.equals(format))
1268 String shortName = title;
1269 if (shortName.indexOf(File.separatorChar) > -1)
1271 shortName = shortName
1272 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1274 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1277 statusBar.setText(MessageManager.formatMessage(
1278 "label.successfully_saved_to_file_in_format", new Object[]
1284 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1285 Runnable cancelAction = new Runnable()
1290 lastSaveSuccessful = false;
1293 Runnable outputAction = new Runnable()
1298 // todo defer this to inside formatSequences (or later)
1299 AlignmentExportData exportData = viewport
1300 .getAlignExportData(options);
1301 String output = new FormatAdapter(alignPanel, options)
1302 .formatSequences(format, exportData.getAlignment(),
1303 exportData.getOmitHidden(),
1304 exportData.getStartEndPostions(),
1305 viewport.getAlignment().getHiddenColumns());
1308 lastSaveSuccessful = false;
1312 // create backupfiles object and get new temp filename destination
1313 boolean doBackup = BackupFiles.getEnabled();
1314 BackupFiles backupfiles = null;
1318 "ALIGNFRAME making backupfiles object for " + file);
1319 backupfiles = new BackupFiles(file);
1323 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1325 Console.trace("ALIGNFRAME setting PrintWriter");
1326 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1328 if (backupfiles != null)
1330 Console.trace("ALIGNFRAME about to write to temp file "
1331 + backupfiles.getTempFilePath());
1335 Console.trace("ALIGNFRAME about to close file");
1337 Console.trace("ALIGNFRAME closed file");
1338 AlignFrame.this.setTitle(file);
1339 statusBar.setText(MessageManager.formatMessage(
1340 "label.successfully_saved_to_file_in_format",
1342 { fileName, format.getName() }));
1343 lastSaveSuccessful = true;
1344 } catch (IOException e)
1346 lastSaveSuccessful = false;
1348 "ALIGNFRAME Something happened writing the temp file");
1349 Console.error(e.getMessage());
1350 Console.debug(Cache.getStackTraceString(e));
1351 } catch (Exception ex)
1353 lastSaveSuccessful = false;
1355 "ALIGNFRAME Something unexpected happened writing the temp file");
1356 Console.error(ex.getMessage());
1357 Console.debug(Cache.getStackTraceString(ex));
1362 backupfiles.setWriteSuccess(lastSaveSuccessful);
1363 Console.debug("ALIGNFRAME writing temp file was "
1364 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1365 // do the backup file roll and rename the temp file to actual file
1367 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1368 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1370 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1371 + (lastSaveSuccessful ? "" : "un")
1379 * show dialog with export options if applicable; else just do it
1381 if (AlignExportOptions.isNeeded(viewport, format))
1383 AlignExportOptions choices = new AlignExportOptions(
1384 alignPanel.getAlignViewport(), format, options);
1385 choices.setResponseAction(0, outputAction);
1386 choices.setResponseAction(1, cancelAction);
1387 choices.showDialog();
1396 * Outputs the alignment to textbox in the requested format, if necessary
1397 * first prompting the user for whether to include hidden regions or
1400 * @param fileFormatName
1403 protected void outputText_actionPerformed(String fileFormatName)
1405 FileFormatI fileFormat = FileFormats.getInstance()
1406 .forName(fileFormatName);
1407 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1408 Runnable outputAction = new Runnable()
1413 // todo defer this to inside formatSequences (or later)
1414 AlignmentExportData exportData = viewport
1415 .getAlignExportData(options);
1416 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1417 cap.setForInput(null);
1420 FileFormatI format = fileFormat;
1421 cap.setText(new FormatAdapter(alignPanel, options)
1422 .formatSequences(format, exportData.getAlignment(),
1423 exportData.getOmitHidden(),
1424 exportData.getStartEndPostions(),
1425 viewport.getAlignment().getHiddenColumns()));
1426 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1427 "label.alignment_output_command", new Object[]
1428 { fileFormat.getName() }), 600, 500);
1429 } catch (OutOfMemoryError oom)
1431 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1439 * show dialog with export options if applicable; else just do it
1441 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1443 AlignExportOptions choices = new AlignExportOptions(
1444 alignPanel.getAlignViewport(), fileFormat, options);
1445 choices.setResponseAction(0, outputAction);
1446 choices.showDialog();
1461 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1463 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1464 htmlSVG.exportHTML(null);
1468 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1470 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1471 bjs.exportHTML(null);
1474 public void createImageMap(File file, String image)
1476 alignPanel.makePNGImageMap(file, image);
1480 * Creates a PNG image of the alignment and writes it to the given file. If
1481 * the file is null, the user is prompted to choose a file.
1486 public void createPNG(File f)
1488 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1492 * Creates an EPS image of the alignment and writes it to the given file. If
1493 * the file is null, the user is prompted to choose a file.
1498 public void createEPS(File f)
1500 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1504 * Creates an SVG image of the alignment and writes it to the given file. If
1505 * the file is null, the user is prompted to choose a file.
1510 public void createSVG(File f)
1512 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1516 public void pageSetup_actionPerformed(ActionEvent e)
1518 PrinterJob printJob = PrinterJob.getPrinterJob();
1519 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1529 public void printMenuItem_actionPerformed(ActionEvent e)
1531 // Putting in a thread avoids Swing painting problems
1532 PrintThread thread = new PrintThread(alignPanel);
1537 public void exportFeatures_actionPerformed(ActionEvent e)
1539 new AnnotationExporter(alignPanel).exportFeatures();
1543 public void exportAnnotations_actionPerformed(ActionEvent e)
1545 new AnnotationExporter(alignPanel).exportAnnotations();
1549 public void associatedData_actionPerformed(ActionEvent e)
1551 final JalviewFileChooser chooser = new JalviewFileChooser(
1552 Cache.getProperty("LAST_DIRECTORY"));
1553 chooser.setFileView(new JalviewFileView());
1554 String tooltip = MessageManager
1555 .getString("label.load_jalview_annotations");
1556 chooser.setDialogTitle(tooltip);
1557 chooser.setToolTipText(tooltip);
1558 chooser.setResponseHandler(0, new Runnable()
1563 String choice = chooser.getSelectedFile().getPath();
1564 Cache.setProperty("LAST_DIRECTORY", choice);
1565 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1569 chooser.showOpenDialog(this);
1573 * Close the current view or all views in the alignment frame. If the frame
1574 * only contains one view then the alignment will be removed from memory.
1576 * @param closeAllTabs
1579 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1581 if (alignPanels != null && alignPanels.size() < 2)
1583 closeAllTabs = true;
1588 if (alignPanels != null)
1592 if (this.isClosed())
1594 // really close all the windows - otherwise wait till
1595 // setClosed(true) is called
1596 for (int i = 0; i < alignPanels.size(); i++)
1598 AlignmentPanel ap = alignPanels.get(i);
1605 closeView(alignPanel);
1610 if (featureSettings != null && featureSettings.isOpen())
1612 featureSettings.close();
1613 featureSettings = null;
1616 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1617 * be called recursively, with the frame now in 'closed' state
1619 this.setClosed(true);
1621 } catch (Exception ex)
1623 ex.printStackTrace();
1628 * Close the specified panel and close up tabs appropriately.
1630 * @param panelToClose
1632 public void closeView(AlignmentPanel panelToClose)
1634 int index = tabbedPane.getSelectedIndex();
1635 int closedindex = tabbedPane.indexOfComponent(panelToClose);
1636 alignPanels.remove(panelToClose);
1637 panelToClose.closePanel();
1638 panelToClose = null;
1640 tabbedPane.removeTabAt(closedindex);
1641 tabbedPane.validate();
1643 if (index > closedindex || index == tabbedPane.getTabCount())
1645 // modify currently selected tab index if necessary.
1649 this.tabSelectionChanged(index);
1655 public void updateEditMenuBar()
1658 if (viewport.getHistoryList().size() > 0)
1660 undoMenuItem.setEnabled(true);
1661 CommandI command = viewport.getHistoryList().peek();
1662 undoMenuItem.setText(MessageManager
1663 .formatMessage("label.undo_command", new Object[]
1664 { command.getDescription() }));
1668 undoMenuItem.setEnabled(false);
1669 undoMenuItem.setText(MessageManager.getString("action.undo"));
1672 if (viewport.getRedoList().size() > 0)
1674 redoMenuItem.setEnabled(true);
1676 CommandI command = viewport.getRedoList().peek();
1677 redoMenuItem.setText(MessageManager
1678 .formatMessage("label.redo_command", new Object[]
1679 { command.getDescription() }));
1683 redoMenuItem.setEnabled(false);
1684 redoMenuItem.setText(MessageManager.getString("action.redo"));
1689 public void addHistoryItem(CommandI command)
1691 if (command.getSize() > 0)
1693 viewport.addToHistoryList(command);
1694 viewport.clearRedoList();
1695 updateEditMenuBar();
1696 viewport.updateHiddenColumns();
1697 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1698 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1699 // viewport.getColumnSelection()
1700 // .getHiddenColumns().size() > 0);
1706 * @return alignment objects for all views
1708 AlignmentI[] getViewAlignments()
1710 if (alignPanels != null)
1712 AlignmentI[] als = new AlignmentI[alignPanels.size()];
1714 for (AlignmentPanel ap : alignPanels)
1716 als[i++] = ap.av.getAlignment();
1720 if (viewport != null)
1722 return new AlignmentI[] { viewport.getAlignment() };
1734 protected void undoMenuItem_actionPerformed(ActionEvent e)
1736 if (viewport.getHistoryList().isEmpty())
1740 CommandI command = viewport.getHistoryList().pop();
1741 viewport.addToRedoList(command);
1742 command.undoCommand(getViewAlignments());
1744 AlignmentViewport originalSource = getOriginatingSource(command);
1745 updateEditMenuBar();
1747 if (originalSource != null)
1749 if (originalSource != viewport)
1752 "Implementation worry: mismatch of viewport origin for undo");
1754 originalSource.updateHiddenColumns();
1755 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1757 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1758 // viewport.getColumnSelection()
1759 // .getHiddenColumns().size() > 0);
1760 originalSource.firePropertyChange("alignment", null,
1761 originalSource.getAlignment().getSequences());
1772 protected void redoMenuItem_actionPerformed(ActionEvent e)
1774 if (viewport.getRedoList().size() < 1)
1779 CommandI command = viewport.getRedoList().pop();
1780 viewport.addToHistoryList(command);
1781 command.doCommand(getViewAlignments());
1783 AlignmentViewport originalSource = getOriginatingSource(command);
1784 updateEditMenuBar();
1786 if (originalSource != null)
1789 if (originalSource != viewport)
1792 "Implementation worry: mismatch of viewport origin for redo");
1794 originalSource.updateHiddenColumns();
1795 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1797 // && viewport.getColumnSelection().getHiddenColumns() != null &&
1798 // viewport.getColumnSelection()
1799 // .getHiddenColumns().size() > 0);
1800 originalSource.firePropertyChange("alignment", null,
1801 originalSource.getAlignment().getSequences());
1805 AlignmentViewport getOriginatingSource(CommandI command)
1807 AlignmentViewport originalSource = null;
1808 // For sequence removal and addition, we need to fire
1809 // the property change event FROM the viewport where the
1810 // original alignment was altered
1811 AlignmentI al = null;
1812 if (command instanceof EditCommand)
1814 EditCommand editCommand = (EditCommand) command;
1815 al = editCommand.getAlignment();
1816 List<Component> comps = PaintRefresher.components
1817 .get(viewport.getSequenceSetId());
1819 for (Component comp : comps)
1821 if (comp instanceof AlignmentPanel)
1823 if (al == ((AlignmentPanel) comp).av.getAlignment())
1825 originalSource = ((AlignmentPanel) comp).av;
1832 if (originalSource == null)
1834 // The original view is closed, we must validate
1835 // the current view against the closed view first
1838 PaintRefresher.validateSequences(al, viewport.getAlignment());
1841 originalSource = viewport;
1844 return originalSource;
1848 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1849 * or the sequence under cursor in keyboard mode
1854 public void moveSelectedSequences(boolean up)
1856 SequenceGroup sg = viewport.getSelectionGroup();
1860 if (viewport.cursorMode)
1862 sg = new SequenceGroup();
1863 sg.addSequence(viewport.getAlignment().getSequenceAt(
1864 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1872 if (sg.getSize() < 1)
1877 // TODO: JAL-3733 - add an event to the undo buffer for this !
1879 viewport.getAlignment().moveSelectedSequencesByOne(sg,
1880 viewport.getHiddenRepSequences(), up);
1881 alignPanel.paintAlignment(true, false);
1884 synchronized void slideSequences(boolean right, int size)
1886 List<SequenceI> sg = new ArrayList<>();
1887 if (viewport.cursorMode)
1889 sg.add(viewport.getAlignment()
1890 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1892 else if (viewport.getSelectionGroup() != null
1893 && viewport.getSelectionGroup().getSize() != viewport
1894 .getAlignment().getHeight())
1896 sg = viewport.getSelectionGroup()
1897 .getSequences(viewport.getHiddenRepSequences());
1905 List<SequenceI> invertGroup = new ArrayList<>();
1907 for (SequenceI seq : viewport.getAlignment().getSequences())
1909 if (!sg.contains(seq))
1911 invertGroup.add(seq);
1915 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1917 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1918 for (int i = 0; i < invertGroup.size(); i++)
1920 seqs2[i] = invertGroup.get(i);
1923 SlideSequencesCommand ssc;
1926 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1927 viewport.getGapCharacter());
1931 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1932 viewport.getGapCharacter());
1935 int groupAdjustment = 0;
1936 if (ssc.getGapsInsertedBegin() && right)
1938 if (viewport.cursorMode)
1940 alignPanel.getSeqPanel().moveCursor(size, 0);
1944 groupAdjustment = size;
1947 else if (!ssc.getGapsInsertedBegin() && !right)
1949 if (viewport.cursorMode)
1951 alignPanel.getSeqPanel().moveCursor(-size, 0);
1955 groupAdjustment = -size;
1959 if (groupAdjustment != 0)
1961 viewport.getSelectionGroup().setStartRes(
1962 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1963 viewport.getSelectionGroup().setEndRes(
1964 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1968 * just extend the last slide command if compatible; but not if in
1969 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1971 boolean appendHistoryItem = false;
1972 Deque<CommandI> historyList = viewport.getHistoryList();
1973 boolean inSplitFrame = getSplitViewContainer() != null;
1974 if (!inSplitFrame && historyList != null && historyList.size() > 0
1975 && historyList.peek() instanceof SlideSequencesCommand)
1977 appendHistoryItem = ssc.appendSlideCommand(
1978 (SlideSequencesCommand) historyList.peek());
1981 if (!appendHistoryItem)
1983 addHistoryItem(ssc);
1996 protected void copy_actionPerformed()
1998 if (viewport.getSelectionGroup() == null)
2002 // TODO: preserve the ordering of displayed alignment annotation in any
2003 // internal paste (particularly sequence associated annotation)
2004 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2005 String[] omitHidden = null;
2007 if (viewport.hasHiddenColumns())
2009 omitHidden = viewport.getViewAsString(true);
2012 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2013 seqs, omitHidden, null);
2015 StringSelection ss = new StringSelection(output);
2019 jalview.gui.Desktop.internalCopy = true;
2020 // Its really worth setting the clipboard contents
2021 // to empty before setting the large StringSelection!!
2022 Toolkit.getDefaultToolkit().getSystemClipboard()
2023 .setContents(new StringSelection(""), null);
2025 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2027 } catch (OutOfMemoryError er)
2029 new OOMWarning("copying region", er);
2033 HiddenColumns hiddenColumns = null;
2034 if (viewport.hasHiddenColumns())
2036 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2037 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2039 // create new HiddenColumns object with copy of hidden regions
2040 // between startRes and endRes, offset by startRes
2041 hiddenColumns = new HiddenColumns(
2042 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2043 hiddenCutoff, hiddenOffset);
2046 Desktop.jalviewClipboard = new Object[] { seqs,
2047 viewport.getAlignment().getDataset(), hiddenColumns };
2048 setStatus(MessageManager.formatMessage(
2049 "label.copied_sequences_to_clipboard", new Object[]
2050 { Integer.valueOf(seqs.length).toString() }));
2060 protected void pasteNew_actionPerformed(ActionEvent e)
2072 protected void pasteThis_actionPerformed(ActionEvent e)
2078 * Paste contents of Jalview clipboard
2080 * @param newAlignment
2081 * true to paste to a new alignment, otherwise add to this.
2083 void paste(boolean newAlignment)
2085 boolean externalPaste = true;
2088 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2089 Transferable contents = c.getContents(this);
2091 if (contents == null)
2100 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2101 if (str.length() < 1)
2106 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2108 } catch (OutOfMemoryError er)
2110 new OOMWarning("Out of memory pasting sequences!!", er);
2114 SequenceI[] sequences;
2115 boolean annotationAdded = false;
2116 AlignmentI alignment = null;
2118 if (Desktop.jalviewClipboard != null)
2120 // The clipboard was filled from within Jalview, we must use the
2122 // And dataset from the copied alignment
2123 SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2124 // be doubly sure that we create *new* sequence objects.
2125 sequences = new SequenceI[newseq.length];
2126 for (int i = 0; i < newseq.length; i++)
2128 sequences[i] = new Sequence(newseq[i]);
2130 alignment = new Alignment(sequences);
2131 externalPaste = false;
2135 // parse the clipboard as an alignment.
2136 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2138 sequences = alignment.getSequencesArray();
2142 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2148 if (Desktop.jalviewClipboard != null)
2150 // dataset is inherited
2151 alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2155 // new dataset is constructed
2156 alignment.setDataset(null);
2158 alwidth = alignment.getWidth() + 1;
2162 AlignmentI pastedal = alignment; // preserve pasted alignment object
2163 // Add pasted sequences and dataset into existing alignment.
2164 alignment = viewport.getAlignment();
2165 alwidth = alignment.getWidth() + 1;
2166 // decide if we need to import sequences from an existing dataset
2167 boolean importDs = Desktop.jalviewClipboard != null
2168 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2169 // importDs==true instructs us to copy over new dataset sequences from
2170 // an existing alignment
2171 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2173 // minimum dataset set
2175 for (int i = 0; i < sequences.length; i++)
2179 newDs.addElement(null);
2181 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2183 if (importDs && ds != null)
2185 if (!newDs.contains(ds))
2187 newDs.setElementAt(ds, i);
2188 ds = new Sequence(ds);
2189 // update with new dataset sequence
2190 sequences[i].setDatasetSequence(ds);
2194 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2199 // copy and derive new dataset sequence
2200 sequences[i] = sequences[i].deriveSequence();
2201 alignment.getDataset()
2202 .addSequence(sequences[i].getDatasetSequence());
2203 // TODO: avoid creation of duplicate dataset sequences with a
2204 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2206 alignment.addSequence(sequences[i]); // merges dataset
2210 newDs.clear(); // tidy up
2212 if (alignment.getAlignmentAnnotation() != null)
2214 for (AlignmentAnnotation alan : alignment
2215 .getAlignmentAnnotation())
2217 if (alan.graphGroup > fgroup)
2219 fgroup = alan.graphGroup;
2223 if (pastedal.getAlignmentAnnotation() != null)
2225 // Add any annotation attached to alignment.
2226 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2227 for (int i = 0; i < alann.length; i++)
2229 annotationAdded = true;
2230 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2232 AlignmentAnnotation newann = new AlignmentAnnotation(
2234 if (newann.graphGroup > -1)
2236 if (newGraphGroups.size() <= newann.graphGroup
2237 || newGraphGroups.get(newann.graphGroup) == null)
2239 for (int q = newGraphGroups
2240 .size(); q <= newann.graphGroup; q++)
2242 newGraphGroups.add(q, null);
2244 newGraphGroups.set(newann.graphGroup,
2245 Integer.valueOf(++fgroup));
2247 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2251 newann.padAnnotation(alwidth);
2252 alignment.addAnnotation(newann);
2262 addHistoryItem(new EditCommand(
2263 MessageManager.getString("label.add_sequences"),
2264 Action.PASTE, sequences, 0, alignment.getWidth(),
2267 // Add any annotations attached to sequences
2268 for (int i = 0; i < sequences.length; i++)
2270 if (sequences[i].getAnnotation() != null)
2272 AlignmentAnnotation newann;
2273 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2275 annotationAdded = true;
2276 newann = sequences[i].getAnnotation()[a];
2277 newann.adjustForAlignment();
2278 newann.padAnnotation(alwidth);
2279 if (newann.graphGroup > -1)
2281 if (newann.graphGroup > -1)
2283 if (newGraphGroups.size() <= newann.graphGroup
2284 || newGraphGroups.get(newann.graphGroup) == null)
2286 for (int q = newGraphGroups
2287 .size(); q <= newann.graphGroup; q++)
2289 newGraphGroups.add(q, null);
2291 newGraphGroups.set(newann.graphGroup,
2292 Integer.valueOf(++fgroup));
2294 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2298 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2302 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2310 // propagate alignment changed.
2311 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2312 if (annotationAdded)
2314 // Duplicate sequence annotation in all views.
2315 AlignmentI[] alview = this.getViewAlignments();
2316 for (int i = 0; i < sequences.length; i++)
2318 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2323 for (int avnum = 0; avnum < alview.length; avnum++)
2325 if (alview[avnum] != alignment)
2327 // duplicate in a view other than the one with input focus
2328 int avwidth = alview[avnum].getWidth() + 1;
2329 // this relies on sann being preserved after we
2330 // modify the sequence's annotation array for each duplication
2331 for (int a = 0; a < sann.length; a++)
2333 AlignmentAnnotation newann = new AlignmentAnnotation(
2335 sequences[i].addAlignmentAnnotation(newann);
2336 newann.padAnnotation(avwidth);
2337 alview[avnum].addAnnotation(newann); // annotation was
2338 // duplicated earlier
2339 // TODO JAL-1145 graphGroups are not updated for sequence
2340 // annotation added to several views. This may cause
2342 alview[avnum].setAnnotationIndex(newann, a);
2347 buildSortByAnnotationScoresMenu();
2349 viewport.firePropertyChange("alignment", null,
2350 alignment.getSequences());
2351 if (alignPanels != null)
2353 for (AlignmentPanel ap : alignPanels)
2355 ap.validateAnnotationDimensions(false);
2360 alignPanel.validateAnnotationDimensions(false);
2366 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2368 String newtitle = new String("Copied sequences");
2370 if (Desktop.jalviewClipboard != null
2371 && Desktop.jalviewClipboard[2] != null)
2373 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2374 af.viewport.setHiddenColumns(hc);
2377 // >>>This is a fix for the moment, until a better solution is
2379 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2380 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2381 .getFeatureRenderer());
2383 // TODO: maintain provenance of an alignment, rather than just make the
2384 // title a concatenation of operations.
2387 if (title.startsWith("Copied sequences"))
2393 newtitle = newtitle.concat("- from " + title);
2398 newtitle = new String("Pasted sequences");
2401 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2406 } catch (Exception ex)
2408 ex.printStackTrace();
2409 System.out.println("Exception whilst pasting: " + ex);
2410 // could be anything being pasted in here
2416 protected void expand_newalign(ActionEvent e)
2420 AlignmentI alignment = AlignmentUtils
2421 .expandContext(getViewport().getAlignment(), -1);
2422 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2424 String newtitle = new String("Flanking alignment");
2426 if (Desktop.jalviewClipboard != null
2427 && Desktop.jalviewClipboard[2] != null)
2429 HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2430 af.viewport.setHiddenColumns(hc);
2433 // >>>This is a fix for the moment, until a better solution is
2435 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2436 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2437 .getFeatureRenderer());
2439 // TODO: maintain provenance of an alignment, rather than just make the
2440 // title a concatenation of operations.
2442 if (title.startsWith("Copied sequences"))
2448 newtitle = newtitle.concat("- from " + title);
2452 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2454 } catch (Exception ex)
2456 ex.printStackTrace();
2457 System.out.println("Exception whilst pasting: " + ex);
2458 // could be anything being pasted in here
2459 } catch (OutOfMemoryError oom)
2461 new OOMWarning("Viewing flanking region of alignment", oom);
2466 * Action Cut (delete and copy) the selected region
2469 protected void cut_actionPerformed()
2471 copy_actionPerformed();
2472 delete_actionPerformed();
2476 * Performs menu option to Delete the currently selected region
2479 protected void delete_actionPerformed()
2482 SequenceGroup sg = viewport.getSelectionGroup();
2488 Runnable okAction = new Runnable()
2493 SequenceI[] cut = sg.getSequences()
2494 .toArray(new SequenceI[sg.getSize()]);
2496 addHistoryItem(new EditCommand(
2497 MessageManager.getString("label.cut_sequences"), Action.CUT,
2498 cut, sg.getStartRes(),
2499 sg.getEndRes() - sg.getStartRes() + 1,
2500 viewport.getAlignment()));
2502 viewport.setSelectionGroup(null);
2503 viewport.sendSelection();
2504 viewport.getAlignment().deleteGroup(sg);
2506 viewport.firePropertyChange("alignment", null,
2507 viewport.getAlignment().getSequences());
2508 if (viewport.getAlignment().getHeight() < 1)
2512 AlignFrame.this.setClosed(true);
2513 } catch (Exception ex)
2521 * If the cut affects all sequences, prompt for confirmation
2523 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2525 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2526 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2527 if (wholeHeight && wholeWidth)
2529 JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2530 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2531 Object[] options = new Object[] {
2532 MessageManager.getString("action.ok"),
2533 MessageManager.getString("action.cancel") };
2534 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2535 MessageManager.getString("label.delete_all"),
2536 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2537 options, options[0]);
2552 protected void deleteGroups_actionPerformed(ActionEvent e)
2554 if (avc.deleteGroups())
2556 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2557 alignPanel.updateAnnotation();
2558 alignPanel.paintAlignment(true, true);
2569 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2571 SequenceGroup sg = new SequenceGroup(
2572 viewport.getAlignment().getSequences());
2574 sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2575 viewport.setSelectionGroup(sg);
2576 viewport.isSelectionGroupChanged(true);
2577 viewport.sendSelection();
2578 // JAL-2034 - should delegate to
2579 // alignPanel to decide if overview needs
2581 alignPanel.paintAlignment(false, false);
2582 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2592 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2594 if (viewport.cursorMode)
2596 alignPanel.getSeqPanel().keyboardNo1 = null;
2597 alignPanel.getSeqPanel().keyboardNo2 = null;
2599 viewport.setSelectionGroup(null);
2600 viewport.getColumnSelection().clear();
2601 viewport.setSearchResults(null);
2602 alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2603 // JAL-2034 - should delegate to
2604 // alignPanel to decide if overview needs
2606 alignPanel.paintAlignment(false, false);
2607 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2608 viewport.sendSelection();
2618 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2620 SequenceGroup sg = viewport.getSelectionGroup();
2624 selectAllSequenceMenuItem_actionPerformed(null);
2629 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2631 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2633 // JAL-2034 - should delegate to
2634 // alignPanel to decide if overview needs
2637 alignPanel.paintAlignment(true, false);
2638 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2639 viewport.sendSelection();
2643 public void invertColSel_actionPerformed(ActionEvent e)
2645 viewport.invertColumnSelection();
2646 alignPanel.paintAlignment(true, false);
2647 viewport.sendSelection();
2657 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2659 trimAlignment(true);
2669 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2671 trimAlignment(false);
2674 void trimAlignment(boolean trimLeft)
2676 ColumnSelection colSel = viewport.getColumnSelection();
2679 if (!colSel.isEmpty())
2683 column = colSel.getMin();
2687 column = colSel.getMax();
2691 if (viewport.getSelectionGroup() != null)
2693 seqs = viewport.getSelectionGroup()
2694 .getSequencesAsArray(viewport.getHiddenRepSequences());
2698 seqs = viewport.getAlignment().getSequencesArray();
2701 TrimRegionCommand trimRegion;
2704 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2705 column, viewport.getAlignment());
2706 viewport.getRanges().setStartRes(0);
2710 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2711 column, viewport.getAlignment());
2714 setStatus(MessageManager.formatMessage("label.removed_columns",
2716 { Integer.valueOf(trimRegion.getSize()).toString() }));
2718 addHistoryItem(trimRegion);
2720 for (SequenceGroup sg : viewport.getAlignment().getGroups())
2722 if ((trimLeft && !sg.adjustForRemoveLeft(column))
2723 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2725 viewport.getAlignment().deleteGroup(sg);
2729 viewport.firePropertyChange("alignment", null,
2730 viewport.getAlignment().getSequences());
2741 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2743 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2746 if (viewport.getSelectionGroup() != null)
2748 seqs = viewport.getSelectionGroup()
2749 .getSequencesAsArray(viewport.getHiddenRepSequences());
2750 start = viewport.getSelectionGroup().getStartRes();
2751 end = viewport.getSelectionGroup().getEndRes();
2755 seqs = viewport.getAlignment().getSequencesArray();
2758 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2759 "Remove Gapped Columns", seqs, start, end,
2760 viewport.getAlignment());
2762 addHistoryItem(removeGapCols);
2764 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2766 { Integer.valueOf(removeGapCols.getSize()).toString() }));
2768 // This is to maintain viewport position on first residue
2769 // of first sequence
2770 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2771 ViewportRanges ranges = viewport.getRanges();
2772 int startRes = seq.findPosition(ranges.getStartRes());
2773 // ShiftList shifts;
2774 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2775 // edit.alColumnChanges=shifts.getInverse();
2776 // if (viewport.hasHiddenColumns)
2777 // viewport.getColumnSelection().compensateForEdits(shifts);
2778 ranges.setStartRes(seq.findIndex(startRes) - 1);
2779 viewport.firePropertyChange("alignment", null,
2780 viewport.getAlignment().getSequences());
2791 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2793 int start = 0, end = viewport.getAlignment().getWidth() - 1;
2796 if (viewport.getSelectionGroup() != null)
2798 seqs = viewport.getSelectionGroup()
2799 .getSequencesAsArray(viewport.getHiddenRepSequences());
2800 start = viewport.getSelectionGroup().getStartRes();
2801 end = viewport.getSelectionGroup().getEndRes();
2805 seqs = viewport.getAlignment().getSequencesArray();
2808 // This is to maintain viewport position on first residue
2809 // of first sequence
2810 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2811 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2813 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2814 viewport.getAlignment()));
2816 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2818 viewport.firePropertyChange("alignment", null,
2819 viewport.getAlignment().getSequences());
2830 public void padGapsMenuitem_actionPerformed(ActionEvent e)
2832 viewport.setPadGaps(padGapsMenuitem.isSelected());
2833 viewport.firePropertyChange("alignment", null,
2834 viewport.getAlignment().getSequences());
2838 * Opens a Finder dialog
2843 public void findMenuItem_actionPerformed(ActionEvent e)
2845 new Finder(alignPanel, false, null);
2849 * Create a new view of the current alignment.
2852 public void newView_actionPerformed(ActionEvent e)
2854 newView(null, true);
2858 * Creates and shows a new view of the current alignment.
2861 * title of newly created view; if null, one will be generated
2862 * @param copyAnnotation
2863 * if true then duplicate all annnotation, groups and settings
2864 * @return new alignment panel, already displayed.
2866 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2869 * Create a new AlignmentPanel (with its own, new Viewport)
2871 AlignmentPanel newap = new jalview.project.Jalview2XML()
2872 .copyAlignPanel(alignPanel);
2873 if (!copyAnnotation)
2876 * remove all groups and annotation except for the automatic stuff
2878 newap.av.getAlignment().deleteAllGroups();
2879 newap.av.getAlignment().deleteAllAnnotations(false);
2882 newap.av.setGatherViewsHere(false);
2884 if (viewport.getViewName() == null)
2886 viewport.setViewName(
2887 MessageManager.getString("label.view_name_original"));
2891 * Views share the same edits undo and redo stacks
2893 newap.av.setHistoryList(viewport.getHistoryList());
2894 newap.av.setRedoList(viewport.getRedoList());
2897 * copy any visualisation settings that are not saved in the project
2899 newap.av.setColourAppliesToAllGroups(
2900 viewport.getColourAppliesToAllGroups());
2903 * Views share the same mappings; need to deregister any new mappings
2904 * created by copyAlignPanel, and register the new reference to the shared
2907 newap.av.replaceMappings(viewport.getAlignment());
2910 * start up cDNA consensus (if applicable) now mappings are in place
2912 if (newap.av.initComplementConsensus())
2914 newap.refresh(true); // adjust layout of annotations
2917 newap.av.setViewName(getNewViewName(viewTitle));
2919 addAlignmentPanel(newap, true);
2920 newap.alignmentChanged();
2922 if (alignPanels.size() == 2)
2924 viewport.setGatherViewsHere(true);
2926 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2931 * Make a new name for the view, ensuring it is unique within the current
2932 * sequenceSetId. (This used to be essential for Jalview Project archives, but
2933 * these now use viewId. Unique view names are still desirable for usability.)
2938 protected String getNewViewName(String viewTitle)
2940 int index = Desktop.getViewCount(viewport.getSequenceSetId());
2941 boolean addFirstIndex = false;
2942 if (viewTitle == null || viewTitle.trim().length() == 0)
2944 viewTitle = MessageManager.getString("action.view");
2945 addFirstIndex = true;
2949 index = 1;// we count from 1 if given a specific name
2951 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2953 List<Component> comps = PaintRefresher.components
2954 .get(viewport.getSequenceSetId());
2956 List<String> existingNames = getExistingViewNames(comps);
2958 while (existingNames.contains(newViewName))
2960 newViewName = viewTitle + " " + (++index);
2966 * Returns a list of distinct view names found in the given list of
2967 * components. View names are held on the viewport of an AlignmentPanel.
2972 protected List<String> getExistingViewNames(List<Component> comps)
2974 List<String> existingNames = new ArrayList<>();
2975 for (Component comp : comps)
2977 if (comp instanceof AlignmentPanel)
2979 AlignmentPanel ap = (AlignmentPanel) comp;
2980 if (!existingNames.contains(ap.av.getViewName()))
2982 existingNames.add(ap.av.getViewName());
2986 return existingNames;
2990 * Explode tabbed views into separate windows.
2993 public void expandViews_actionPerformed(ActionEvent e)
2995 Desktop.explodeViews(this);
2999 * Gather views in separate windows back into a tabbed presentation.
3002 public void gatherViews_actionPerformed(ActionEvent e)
3004 Desktop.instance.gatherViews(this);
3014 public void font_actionPerformed(ActionEvent e)
3016 new FontChooser(alignPanel);
3026 protected void seqLimit_actionPerformed(ActionEvent e)
3028 viewport.setShowJVSuffix(seqLimits.isSelected());
3030 alignPanel.getIdPanel().getIdCanvas()
3031 .setPreferredSize(alignPanel.calculateIdWidth());
3032 alignPanel.paintAlignment(true, false);
3036 public void idRightAlign_actionPerformed(ActionEvent e)
3038 viewport.setRightAlignIds(idRightAlign.isSelected());
3039 alignPanel.paintAlignment(false, false);
3043 public void centreColumnLabels_actionPerformed(ActionEvent e)
3045 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3046 alignPanel.paintAlignment(false, false);
3052 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3055 protected void followHighlight_actionPerformed()
3058 * Set the 'follow' flag on the Viewport (and scroll to position if now
3061 final boolean state = this.followHighlightMenuItem.getState();
3062 viewport.setFollowHighlight(state);
3065 alignPanel.scrollToPosition(viewport.getSearchResults());
3076 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3078 viewport.setColourText(colourTextMenuItem.isSelected());
3079 alignPanel.paintAlignment(false, false);
3089 public void wrapMenuItem_actionPerformed(ActionEvent e)
3091 scaleAbove.setVisible(wrapMenuItem.isSelected());
3092 scaleLeft.setVisible(wrapMenuItem.isSelected());
3093 scaleRight.setVisible(wrapMenuItem.isSelected());
3094 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3095 alignPanel.updateLayout();
3099 public void showAllSeqs_actionPerformed(ActionEvent e)
3101 viewport.showAllHiddenSeqs();
3105 public void showAllColumns_actionPerformed(ActionEvent e)
3107 viewport.showAllHiddenColumns();
3108 alignPanel.paintAlignment(true, true);
3109 viewport.sendSelection();
3113 public void hideSelSequences_actionPerformed(ActionEvent e)
3115 viewport.hideAllSelectedSeqs();
3119 * called by key handler and the hide all/show all menu items
3124 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3127 boolean hide = false;
3128 SequenceGroup sg = viewport.getSelectionGroup();
3129 if (!toggleSeqs && !toggleCols)
3131 // Hide everything by the current selection - this is a hack - we do the
3132 // invert and then hide
3133 // first check that there will be visible columns after the invert.
3134 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3135 && sg.getStartRes() <= sg.getEndRes()))
3137 // now invert the sequence set, if required - empty selection implies
3138 // that no hiding is required.
3141 invertSequenceMenuItem_actionPerformed(null);
3142 sg = viewport.getSelectionGroup();
3146 viewport.expandColSelection(sg, true);
3147 // finally invert the column selection and get the new sequence
3149 invertColSel_actionPerformed(null);
3156 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3158 hideSelSequences_actionPerformed(null);
3161 else if (!(toggleCols && viewport.hasSelectedColumns()))
3163 showAllSeqs_actionPerformed(null);
3169 if (viewport.hasSelectedColumns())
3171 hideSelColumns_actionPerformed(null);
3174 viewport.setSelectionGroup(sg);
3179 showAllColumns_actionPerformed(null);
3188 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3189 * event.ActionEvent)
3192 public void hideAllButSelection_actionPerformed(ActionEvent e)
3194 toggleHiddenRegions(false, false);
3195 viewport.sendSelection();
3202 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3206 public void hideAllSelection_actionPerformed(ActionEvent e)
3208 SequenceGroup sg = viewport.getSelectionGroup();
3209 viewport.expandColSelection(sg, false);
3210 viewport.hideAllSelectedSeqs();
3211 viewport.hideSelectedColumns();
3212 alignPanel.updateLayout();
3213 alignPanel.paintAlignment(true, true);
3214 viewport.sendSelection();
3221 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3225 public void showAllhidden_actionPerformed(ActionEvent e)
3227 viewport.showAllHiddenColumns();
3228 viewport.showAllHiddenSeqs();
3229 alignPanel.paintAlignment(true, true);
3230 viewport.sendSelection();
3234 public void hideSelColumns_actionPerformed(ActionEvent e)
3236 viewport.hideSelectedColumns();
3237 alignPanel.updateLayout();
3238 alignPanel.paintAlignment(true, true);
3239 viewport.sendSelection();
3243 public void hiddenMarkers_actionPerformed(ActionEvent e)
3245 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3256 protected void scaleAbove_actionPerformed(ActionEvent e)
3258 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3259 alignPanel.updateLayout();
3260 alignPanel.paintAlignment(true, false);
3270 protected void scaleLeft_actionPerformed(ActionEvent e)
3272 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3273 alignPanel.updateLayout();
3274 alignPanel.paintAlignment(true, false);
3284 protected void scaleRight_actionPerformed(ActionEvent e)
3286 viewport.setScaleRightWrapped(scaleRight.isSelected());
3287 alignPanel.updateLayout();
3288 alignPanel.paintAlignment(true, false);
3298 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3300 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3301 alignPanel.paintAlignment(false, false);
3311 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3313 viewport.setShowText(viewTextMenuItem.isSelected());
3314 alignPanel.paintAlignment(false, false);
3324 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3326 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3327 alignPanel.paintAlignment(false, false);
3330 public FeatureSettings featureSettings;
3333 public FeatureSettingsControllerI getFeatureSettingsUI()
3335 return featureSettings;
3339 public void featureSettings_actionPerformed(ActionEvent e)
3341 showFeatureSettingsUI();
3345 public FeatureSettingsControllerI showFeatureSettingsUI()
3347 if (featureSettings != null)
3349 featureSettings.closeOldSettings();
3350 featureSettings = null;
3352 if (!showSeqFeatures.isSelected())
3354 // make sure features are actually displayed
3355 showSeqFeatures.setSelected(true);
3356 showSeqFeatures_actionPerformed(null);
3358 featureSettings = new FeatureSettings(this);
3359 return featureSettings;
3363 * Set or clear 'Show Sequence Features'
3369 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3371 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3372 alignPanel.paintAlignment(true, true);
3376 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3377 * the annotations panel as a whole.
3379 * The options to show/hide all annotations should be enabled when the panel
3380 * is shown, and disabled when the panel is hidden.
3385 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3387 final boolean setVisible = annotationPanelMenuItem.isSelected();
3388 viewport.setShowAnnotation(setVisible);
3389 this.showAllSeqAnnotations.setEnabled(setVisible);
3390 this.hideAllSeqAnnotations.setEnabled(setVisible);
3391 this.showAllAlAnnotations.setEnabled(setVisible);
3392 this.hideAllAlAnnotations.setEnabled(setVisible);
3393 alignPanel.updateLayout();
3397 public void alignmentProperties()
3400 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3403 String content = MessageManager.formatMessage("label.html_content",
3405 { contents.toString() });
3408 if (Platform.isJS())
3410 JLabel textLabel = new JLabel();
3411 textLabel.setText(content);
3412 textLabel.setBackground(Color.WHITE);
3414 pane = new JPanel(new BorderLayout());
3415 ((JPanel) pane).setOpaque(true);
3416 pane.setBackground(Color.WHITE);
3417 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3426 JEditorPane editPane = new JEditorPane("text/html", "");
3427 editPane.setEditable(false);
3428 editPane.setText(content);
3432 JInternalFrame frame = new JInternalFrame();
3434 frame.getContentPane().add(new JScrollPane(pane));
3436 Desktop.addInternalFrame(frame, MessageManager
3437 .formatMessage("label.alignment_properties", new Object[]
3438 { getTitle() }), 500, 400);
3448 public void overviewMenuItem_actionPerformed(ActionEvent e)
3450 if (alignPanel.overviewPanel != null)
3455 JInternalFrame frame = new JInternalFrame();
3456 final OverviewPanel overview = new OverviewPanel(alignPanel);
3457 frame.setContentPane(overview);
3458 Desktop.addInternalFrame(frame, MessageManager
3459 .formatMessage("label.overview_params", new Object[]
3460 { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3463 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3464 frame.addInternalFrameListener(
3465 new javax.swing.event.InternalFrameAdapter()
3468 public void internalFrameClosed(
3469 javax.swing.event.InternalFrameEvent evt)
3472 alignPanel.setOverviewPanel(null);
3475 if (getKeyListeners().length > 0)
3477 frame.addKeyListener(getKeyListeners()[0]);
3480 alignPanel.setOverviewPanel(overview);
3484 public void textColour_actionPerformed()
3486 new TextColourChooser().chooseColour(alignPanel, null);
3490 * public void covariationColour_actionPerformed() {
3492 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3496 public void annotationColour_actionPerformed()
3498 new AnnotationColourChooser(viewport, alignPanel);
3502 public void annotationColumn_actionPerformed(ActionEvent e)
3504 new AnnotationColumnChooser(viewport, alignPanel);
3508 * Action on the user checking or unchecking the option to apply the selected
3509 * colour scheme to all groups. If unchecked, groups may have their own
3510 * independent colour schemes.
3515 public void applyToAllGroups_actionPerformed(boolean selected)
3517 viewport.setColourAppliesToAllGroups(selected);
3521 * Action on user selecting a colour from the colour menu
3524 * the name (not the menu item label!) of the colour scheme
3527 public void changeColour_actionPerformed(String name)
3530 * 'User Defined' opens a panel to configure or load a
3531 * user-defined colour scheme
3533 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3535 new UserDefinedColours(alignPanel);
3540 * otherwise set the chosen colour scheme (or null for 'None')
3542 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3543 viewport, viewport.getAlignment(),
3544 viewport.getHiddenRepSequences());
3549 * Actions on setting or changing the alignment colour scheme
3554 public void changeColour(ColourSchemeI cs)
3556 // TODO: pull up to controller method
3557 ColourMenuHelper.setColourSelected(colourMenu, cs);
3559 viewport.setGlobalColourScheme(cs);
3561 alignPanel.paintAlignment(true, true);
3565 * Show the PID threshold slider panel
3568 protected void modifyPID_actionPerformed()
3570 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3571 alignPanel.getViewName());
3572 SliderPanel.showPIDSlider();
3576 * Show the Conservation slider panel
3579 protected void modifyConservation_actionPerformed()
3581 SliderPanel.setConservationSlider(alignPanel,
3582 viewport.getResidueShading(), alignPanel.getViewName());
3583 SliderPanel.showConservationSlider();
3587 * Action on selecting or deselecting (Colour) By Conservation
3590 public void conservationMenuItem_actionPerformed(boolean selected)
3592 modifyConservation.setEnabled(selected);
3593 viewport.setConservationSelected(selected);
3594 viewport.getResidueShading().setConservationApplied(selected);
3596 changeColour(viewport.getGlobalColourScheme());
3599 modifyConservation_actionPerformed();
3603 SliderPanel.hideConservationSlider();
3608 * Action on selecting or deselecting (Colour) Above PID Threshold
3611 public void abovePIDThreshold_actionPerformed(boolean selected)
3613 modifyPID.setEnabled(selected);
3614 viewport.setAbovePIDThreshold(selected);
3617 viewport.getResidueShading().setThreshold(0,
3618 viewport.isIgnoreGapsConsensus());
3621 changeColour(viewport.getGlobalColourScheme());
3624 modifyPID_actionPerformed();
3628 SliderPanel.hidePIDSlider();
3639 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3641 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3642 AlignmentSorter.sortByPID(viewport.getAlignment(),
3643 viewport.getAlignment().getSequenceAt(0));
3644 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3645 viewport.getAlignment()));
3646 alignPanel.paintAlignment(true, false);
3656 public void sortIDMenuItem_actionPerformed(ActionEvent e)
3658 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3659 AlignmentSorter.sortByID(viewport.getAlignment());
3661 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3662 alignPanel.paintAlignment(true, false);
3672 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3674 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3675 AlignmentSorter.sortByLength(viewport.getAlignment());
3676 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3677 viewport.getAlignment()));
3678 alignPanel.paintAlignment(true, false);
3688 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3690 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3691 AlignmentSorter.sortByGroup(viewport.getAlignment());
3692 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3693 viewport.getAlignment()));
3695 alignPanel.paintAlignment(true, false);
3705 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3707 new RedundancyPanel(alignPanel, this);
3717 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3719 if ((viewport.getSelectionGroup() == null)
3720 || (viewport.getSelectionGroup().getSize() < 2))
3722 JvOptionPane.showInternalMessageDialog(this,
3723 MessageManager.getString(
3724 "label.you_must_select_least_two_sequences"),
3725 MessageManager.getString("label.invalid_selection"),
3726 JvOptionPane.WARNING_MESSAGE);
3730 JInternalFrame frame = new JInternalFrame();
3731 frame.setContentPane(new PairwiseAlignPanel(viewport));
3732 Desktop.addInternalFrame(frame,
3733 MessageManager.getString("action.pairwise_alignment"), 600,
3739 public void autoCalculate_actionPerformed(ActionEvent e)
3741 viewport.autoCalculateConsensus = autoCalculate.isSelected();
3742 if (viewport.autoCalculateConsensus)
3744 viewport.firePropertyChange("alignment", null,
3745 viewport.getAlignment().getSequences());
3750 public void sortByTreeOption_actionPerformed(ActionEvent e)
3752 viewport.sortByTree = sortByTree.isSelected();
3756 protected void listenToViewSelections_actionPerformed(ActionEvent e)
3758 viewport.followSelection = listenToViewSelections.isSelected();
3762 * Constructs a tree panel and adds it to the desktop
3771 void newTreePanel(TreeModel tree, String treeAlgo,
3772 String substitutionMatrix)
3774 String frameTitle = "";
3777 boolean onSelection = false;
3778 if (viewport.getSelectionGroup() != null
3779 && viewport.getSelectionGroup().getSize() > 0)
3781 SequenceGroup sg = viewport.getSelectionGroup();
3783 /* Decide if the selection is a column region */
3784 for (SequenceI _s : sg.getSequences()) // port this to Archaeopteryx?
3786 if (_s.getLength() < sg.getEndRes())
3788 JvOptionPane.showMessageDialog(Desktop.desktop,
3789 MessageManager.getString(
3790 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3791 MessageManager.getString(
3792 "label.sequences_selection_not_aligned"),
3793 JvOptionPane.WARNING_MESSAGE);
3802 if (viewport.getAlignment().getHeight() < 2)
3808 tp = new TreePanel(alignPanel, tree, treeAlgo, substitutionMatrix);
3809 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3811 frameTitle += " from ";
3813 if (viewport.getViewName() != null)
3815 frameTitle += viewport.getViewName() + " of ";
3818 frameTitle += this.title;
3820 Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3831 public void addSortByOrderMenuItem(String title,
3832 final AlignmentOrder order)
3834 final JMenuItem item = new JMenuItem(MessageManager
3835 .formatMessage("action.by_title_param", new Object[]
3838 item.addActionListener(new java.awt.event.ActionListener()
3841 public void actionPerformed(ActionEvent e)
3843 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3845 // TODO: JBPNote - have to map order entries to curent SequenceI
3847 AlignmentSorter.sortBy(viewport.getAlignment(), order);
3849 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3850 viewport.getAlignment()));
3852 alignPanel.paintAlignment(true, false);
3858 * Add a new sort by annotation score menu item
3861 * the menu to add the option to
3863 * the label used to retrieve scores for each sequence on the
3866 public void addSortByAnnotScoreMenuItem(JMenu sort,
3867 final String scoreLabel)
3869 final JMenuItem item = new JMenuItem(scoreLabel);
3871 item.addActionListener(new java.awt.event.ActionListener()
3874 public void actionPerformed(ActionEvent e)
3876 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3877 AlignmentSorter.sortByAnnotationScore(scoreLabel,
3878 viewport.getAlignment());// ,viewport.getSelectionGroup());
3879 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3880 viewport.getAlignment()));
3881 alignPanel.paintAlignment(true, false);
3887 * last hash for alignment's annotation array - used to minimise cost of
3890 protected int _annotationScoreVectorHash;
3893 * search the alignment and rebuild the sort by annotation score submenu the
3894 * last alignment annotation vector hash is stored to minimize cost of
3895 * rebuilding in subsequence calls.
3899 public void buildSortByAnnotationScoresMenu()
3901 if (viewport.getAlignment().getAlignmentAnnotation() == null)
3906 if (viewport.getAlignment().getAlignmentAnnotation()
3907 .hashCode() != _annotationScoreVectorHash)
3909 sortByAnnotScore.removeAll();
3910 // almost certainly a quicker way to do this - but we keep it simple
3911 Hashtable<String, String> scoreSorts = new Hashtable<>();
3912 AlignmentAnnotation aann[];
3913 for (SequenceI sqa : viewport.getAlignment().getSequences())
3915 aann = sqa.getAnnotation();
3916 for (int i = 0; aann != null && i < aann.length; i++)
3918 if (aann[i].hasScore() && aann[i].sequenceRef != null)
3920 scoreSorts.put(aann[i].label, aann[i].label);
3924 Enumeration<String> labels = scoreSorts.keys();
3925 while (labels.hasMoreElements())
3927 addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3929 sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3932 _annotationScoreVectorHash = viewport.getAlignment()
3933 .getAlignmentAnnotation().hashCode();
3939 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3940 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3941 * call. Listeners are added to remove the menu item when the treePanel is
3942 * closed, and adjust the tree leaf to sequence mapping when the alignment is
3946 public void buildTreeSortMenu()
3948 sortByTreeMenu.removeAll();
3950 List<Component> comps = PaintRefresher.components
3951 .get(viewport.getSequenceSetId());
3952 List<TreePanel> treePanels = new ArrayList<>();
3954 Map<TreeFrameI, TreeViewerBindingI> aptxFrames = TreeViewerUtils
3955 .getActiveTreeViews();
3957 for (Component comp : comps)
3960 if (comp instanceof TreePanel)
3962 treePanels.add((TreePanel) comp);
3967 if (treePanels.isEmpty() && aptxFrames.isEmpty())
3969 sortByTreeMenu.setVisible(false);
3973 sortByTreeMenu.setVisible(true);
3975 for (Entry<TreeFrameI, TreeViewerBindingI> aptxFrameWithBinding : aptxFrames
3978 TreeFrameI aptxFrame = aptxFrameWithBinding.getKey();
3979 TreeViewerBindingI binding = aptxFrameWithBinding.getValue();
3981 // future support for multiple tabs
3982 // for (org.forester.archaeopteryx.TreePanel aptxTree : aptxFrame
3983 // .getMainPanel().getTreePanels())
3985 final JMenuItem item = new JMenuItem(
3986 aptxFrame.getTree().getTreeName());
3988 item.addActionListener(new ActionListener()
3992 public void actionPerformed(ActionEvent e)
3994 binding.sortByTree_actionPerformed(); // redundant here??
3995 addHistoryItem(binding.sortAlignmentIn(alignPanel));
3999 sortByTreeMenu.add(item);
4011 for (final TreePanel tp : treePanels)
4013 final JMenuItem item = new JMenuItem(tp.getTitle());
4014 item.addActionListener(new java.awt.event.ActionListener()
4017 public void actionPerformed(ActionEvent e)
4019 tp.sortByTree_actionPerformed();
4020 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4025 sortByTreeMenu.add(item);
4029 public boolean sortBy(AlignmentOrder alorder, String undoname)
4031 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4032 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4033 if (undoname != null)
4035 addHistoryItem(new OrderCommand(undoname, oldOrder,
4036 viewport.getAlignment()));
4038 alignPanel.paintAlignment(true, false);
4043 * Work out whether the whole set of sequences or just the selected set will
4044 * be submitted for multiple alignment.
4047 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4049 // Now, check we have enough sequences
4050 AlignmentView msa = null;
4052 if ((viewport.getSelectionGroup() != null)
4053 && (viewport.getSelectionGroup().getSize() > 1))
4055 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4056 // some common interface!
4058 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4059 * SequenceI[sz = seqs.getSize(false)];
4061 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4062 * seqs.getSequenceAt(i); }
4064 msa = viewport.getAlignmentView(true);
4066 else if (viewport.getSelectionGroup() != null
4067 && viewport.getSelectionGroup().getSize() == 1)
4069 int option = JvOptionPane.showConfirmDialog(this,
4070 MessageManager.getString("warn.oneseq_msainput_selection"),
4071 MessageManager.getString("label.invalid_selection"),
4072 JvOptionPane.OK_CANCEL_OPTION);
4073 if (option == JvOptionPane.OK_OPTION)
4075 msa = viewport.getAlignmentView(false);
4080 msa = viewport.getAlignmentView(false);
4086 * Decides what is submitted to a secondary structure prediction service: the
4087 * first sequence in the alignment, or in the current selection, or, if the
4088 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4089 * region or the whole alignment. (where the first sequence in the set is the
4090 * one that the prediction will be for).
4092 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4094 AlignmentView seqs = null;
4096 if ((viewport.getSelectionGroup() != null)
4097 && (viewport.getSelectionGroup().getSize() > 0))
4099 seqs = viewport.getAlignmentView(true);
4103 seqs = viewport.getAlignmentView(false);
4105 // limit sequences - JBPNote in future - could spawn multiple prediction
4107 // TODO: viewport.getAlignment().isAligned is a global state - the local
4108 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4109 if (!viewport.getAlignment().isAligned(false))
4111 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4112 // TODO: if seqs.getSequences().length>1 then should really have warned
4126 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4132 protected void loadTreeUrlItem_actionPerformed(ActionEvent e)
4138 protected void loadTreeBaseStudy_actionPerformed(ActionEvent e)
4140 chooseTreeDb(0, null);
4145 protected void loadTreeBase_actionPerformed(ActionEvent e)
4147 chooseTreeDb(1, null);
4151 protected void loadTreePfam_actionPerformed(ActionEvent e)
4154 // only DBRefs of first sequence are checked for matching DB for now,
4155 // iterating through them all seems excessive
4156 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
4158 for (DBRefEntry pfamRef : DBRefUtils
4159 .searchRefsForSource(seq.getDBRefs(), "pfam"))
4161 if (pfamRef.getAccessionId().startsWith("PF"))
4163 dbId = pfamRef.getAccessionId().replaceAll("[A-Za-z]", "");
4167 chooseTreeDb(2, dbId);
4171 protected void loadTreeFam_actionPerformed(ActionEvent e)
4173 chooseTreeDb(3, null);
4178 protected void loadTreeOfLife_actionPerformed(ActionEvent e)
4180 chooseTreeDb(4, null);
4188 public void chooseTreeFile()
4190 // Pick the tree file
4191 JalviewFileChooser chooser = new JalviewFileChooser(
4192 Cache.getProperty("LAST_DIRECTORY"));
4193 chooser.setFileView(new JalviewFileView());
4194 chooser.setDialogTitle(
4195 MessageManager.getString("label.select_tree_file")); // modify
4196 chooser.setToolTipText(
4197 MessageManager.getString("label.load_tree_for_sequence_set"));
4198 for (SupportedTreeFileFilter treeFormat : SupportedTreeFileFilter
4201 chooser.setFileFilter(treeFormat.getTreeFilter());
4203 final AlignFrame us=this;
4204 chooser.setResponseHandler(0, new Runnable()
4209 String filePath = chooser.getSelectedFile().getPath();
4210 Cache.setProperty("LAST_DIRECTORY", filePath);
4213 NewickFile fin = null; // old tree
4216 AptxInit.createInstancesFromFile(filePath, viewport);
4218 // fin = new NewickFile(filePath, DataSourceType.FILE);
4219 // viewport.setCurrentTree(viewport.getAlignPanel().alignFrame
4220 // .showNewickTree(fin, filePath).getTree());
4222 } catch (Exception ex)
4224 JvOptionPane.showMessageDialog(us, ex.getMessage(),
4225 MessageManager.getString("label.problem_reading_tree_file"),
4226 JvOptionPane.WARNING_MESSAGE);
4227 ex.printStackTrace();
4231 chooser.showOpenDialog(this);
4235 * Break up and move to TreeParser?
4237 public void chooseTreeUrl()
4240 JLabel label = new JLabel(
4241 MessageManager.getString("label.tree_url_example"));
4242 // add "example" button
4243 final JComboBox<String> history = new JComboBox<>();
4245 JPanel panel = new JPanel(new GridLayout(2, 1));
4248 history.setPreferredSize(new Dimension(400, 20));
4249 history.setEditable(true);
4250 history.addItem("http://www.");
4252 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
4256 if (historyItems != null)
4258 st = new StringTokenizer(historyItems, "\t");
4260 while (st.hasMoreTokens())
4262 history.addItem(st.nextToken());
4266 int reply = JvOptionPane.showInternalConfirmDialog(this, panel,
4267 MessageManager.getString("label.load_tree_url"),
4268 JvOptionPane.OK_CANCEL_OPTION);
4270 if (reply == JvOptionPane.OK_OPTION)
4273 String urlString = history.getSelectedItem().toString();
4278 FileFormatI format = null;
4280 format = new IdentifyFile().identify(urlString, DataSourceType.URL);
4281 // add actual use for the format identification (jalview .jar files)
4282 treeUrl = new URL(urlString);
4283 AptxInit.createInstancesFromUrl(treeUrl, viewport);
4285 } catch (IOException | RuntimeException e)
4287 JvOptionPane.showMessageDialog(this, MessageManager.formatMessage(
4288 "exception.failed_to_read_data_from_source", new String[]
4290 MessageManager.getString("label.url_not_found"),
4291 JvOptionPane.ERROR_MESSAGE);
4292 e.printStackTrace();
4302 * Disgustingly hardcoded atm.
4304 * @param databaseIndex
4306 public void chooseTreeDb(int databaseIndex, String defaultIdentifier)
4308 final WebservicesManager webservices_manager = WebservicesManager
4310 final PhylogeniesWebserviceClient client = webservices_manager
4311 .getAvailablePhylogeniesWebserviceClient(databaseIndex);
4312 String identifier = JvOptionPane
4313 .showInternalInputDialog(Desktop.desktop,
4314 client.getInstructions() + "\n(Reference: "
4315 + client.getReference() + ")",
4316 client.getDescription(), JvOptionPane.QUESTION_MESSAGE,
4317 null, null, defaultIdentifier)
4320 AptxInit.createInstancesFromDb(client, identifier, viewport);
4323 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4325 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4328 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4329 int h, int x, int y)
4331 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4335 * Add a treeviewer for the tree extracted from a Newick file object to the
4336 * current alignment view
4343 * Associated alignment input data (or null)
4352 * @return TreePanel handle
4354 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4355 AlignmentView input, int w, int h, int x, int y)
4357 TreePanel tp = null;
4363 if (nf.getTree() != null)
4365 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4371 tp.setLocation(x, y);
4374 Desktop.addInternalFrame(tp, treeTitle, w, h);
4376 } catch (Exception ex)
4378 ex.printStackTrace();
4384 private boolean buildingMenu = false;
4386 public void BuildTreeDbMenu()
4391 * Generates menu items and listener event actions for web service clients
4394 public void BuildWebServiceMenu()
4396 while (buildingMenu)
4400 System.err.println("Waiting for building menu to finish.");
4402 } catch (Exception e)
4406 final AlignFrame me = this;
4407 buildingMenu = true;
4408 new Thread(new Runnable()
4413 final List<JMenuItem> legacyItems = new ArrayList<>();
4416 // System.err.println("Building ws menu again "
4417 // + Thread.currentThread());
4418 // TODO: add support for context dependent disabling of services based
4420 // alignment and current selection
4421 // TODO: add additional serviceHandle parameter to specify abstract
4423 // class independently of AbstractName
4424 // TODO: add in rediscovery GUI function to restart discoverer
4425 // TODO: group services by location as well as function and/or
4427 // object broker mechanism.
4428 final Vector<JMenu> wsmenu = new Vector<>();
4429 final IProgressIndicator af = me;
4432 * do not i18n these strings - they are hard-coded in class
4433 * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4434 * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4436 final JMenu msawsmenu = new JMenu("Alignment");
4437 final JMenu secstrmenu = new JMenu(
4438 "Secondary Structure Prediction");
4439 final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4440 final JMenu analymenu = new JMenu("Analysis");
4441 final JMenu dismenu = new JMenu("Protein Disorder");
4442 final JMenu phylogenmenu = new JMenu("Phylogenetic inference");
4444 // JAL-940 - only show secondary structure prediction services from
4445 // the legacy server
4446 if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4448 Discoverer.services != null && (Discoverer.services.size() > 0))
4450 // TODO: refactor to allow list of AbstractName/Handler bindings to
4452 // stored or retrieved from elsewhere
4453 // No MSAWS used any more:
4454 // Vector msaws = null; // (Vector)
4455 // Discoverer.services.get("MsaWS");
4456 Vector<ServiceHandle> secstrpr = Discoverer.services
4458 if (secstrpr != null)
4460 // Add any secondary structure prediction services
4461 for (int i = 0, j = secstrpr.size(); i < j; i++)
4463 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4464 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4465 .getServiceClient(sh);
4466 int p = secstrmenu.getItemCount();
4467 impl.attachWSMenuEntry(secstrmenu, me);
4468 int q = secstrmenu.getItemCount();
4469 for (int litm = p; litm < q; litm++)
4471 legacyItems.add(secstrmenu.getItem(litm));
4477 // Add all submenus in the order they should appear on the web
4479 wsmenu.add(msawsmenu);
4480 wsmenu.add(secstrmenu);
4481 wsmenu.add(dismenu);
4482 wsmenu.add(analymenu);
4483 wsmenu.add(phylogenmenu);
4484 // No search services yet
4485 // wsmenu.add(seqsrchmenu);
4487 javax.swing.SwingUtilities.invokeLater(new Runnable()
4494 webService.removeAll();
4495 // first, add discovered services onto the webservices menu
4496 if (wsmenu.size() > 0)
4498 for (int i = 0, j = wsmenu.size(); i < j; i++)
4500 webService.add(wsmenu.get(i));
4505 webService.add(me.webServiceNoServices);
4507 // TODO: move into separate menu builder class.
4509 // logic for 2.11.1.4 is
4510 // always look to see if there is a discover. if there isn't
4511 // we can't show any Jws2 services
4512 // if there are services available, show them - regardless of
4513 // the 'show JWS2 preference'
4514 // if the discoverer is running then say so
4515 // otherwise offer to trigger discovery if 'show JWS2' is not
4517 Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4518 if (jws2servs != null)
4520 if (jws2servs.hasServices())
4522 jws2servs.attachWSMenuEntry(webService, me);
4523 for (Jws2Instance sv : jws2servs.getServices())
4525 if (sv.description.toLowerCase(Locale.ROOT)
4528 for (JMenuItem jmi : legacyItems)
4530 jmi.setVisible(false);
4536 if (jws2servs.isRunning())
4538 JMenuItem tm = new JMenuItem(
4539 "Still discovering JABA Services");
4540 tm.setEnabled(false);
4543 else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4545 JMenuItem enableJws2 = new JMenuItem(
4546 "Discover Web Services");
4547 enableJws2.setToolTipText(
4548 "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4549 enableJws2.setEnabled(true);
4550 enableJws2.addActionListener(new ActionListener()
4554 public void actionPerformed(ActionEvent e)
4556 // start service discoverer, but ignore preference
4557 Desktop.instance.startServiceDiscovery(false,
4561 webService.add(enableJws2);
4565 build_urlServiceMenu(me.webService);
4566 build_fetchdbmenu(webService);
4567 for (JMenu item : wsmenu)
4569 if (item.getItemCount() == 0)
4571 item.setEnabled(false);
4575 item.setEnabled(true);
4578 } catch (Exception e)
4581 "Exception during web service menu building process.",
4586 } catch (Exception e)
4589 buildingMenu = false;
4591 }, "BuildWebService").start();
4596 * construct any groupURL type service menu entries.
4600 protected void build_urlServiceMenu(JMenu webService)
4602 // TODO: remove this code when 2.7 is released
4603 // DEBUG - alignmentView
4605 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4606 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4608 * @Override public void actionPerformed(ActionEvent e) {
4609 * jalview.datamodel.AlignmentView
4610 * .testSelectionViews(af.viewport.getAlignment(),
4611 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4613 * }); webService.add(testAlView);
4615 // TODO: refactor to RestClient discoverer and merge menu entries for
4616 // rest-style services with other types of analysis/calculation service
4617 // SHmmr test client - still being implemented.
4618 // DEBUG - alignmentView
4620 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4623 client.attachWSMenuEntry(
4624 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4630 * Searches the alignment sequences for xRefs and builds the Show
4631 * Cross-References menu (formerly called Show Products), with database
4632 * sources for which cross-references are found (protein sources for a
4633 * nucleotide alignment and vice versa)
4635 * @return true if Show Cross-references menu should be enabled
4637 public boolean canShowProducts()
4639 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4640 AlignmentI dataset = viewport.getAlignment().getDataset();
4642 showProducts.removeAll();
4643 final boolean dna = viewport.getAlignment().isNucleotide();
4645 if (seqs == null || seqs.length == 0)
4647 // nothing to see here.
4651 boolean showp = false;
4654 List<String> ptypes = new CrossRef(seqs, dataset)
4655 .findXrefSourcesForSequences(dna);
4657 for (final String source : ptypes)
4660 final AlignFrame af = this;
4661 JMenuItem xtype = new JMenuItem(source);
4662 xtype.addActionListener(new ActionListener()
4665 public void actionPerformed(ActionEvent e)
4667 showProductsFor(af.viewport.getSequenceSelection(), dna,
4671 showProducts.add(xtype);
4673 showProducts.setVisible(showp);
4674 showProducts.setEnabled(showp);
4675 } catch (Exception e)
4678 "canShowProducts threw an exception - please report to help@jalview.org",
4686 * Finds and displays cross-references for the selected sequences (protein
4687 * products for nucleotide sequences, dna coding sequences for peptides).
4690 * the sequences to show cross-references for
4692 * true if from a nucleotide alignment (so showing proteins)
4694 * the database to show cross-references for
4696 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4697 final String source)
4699 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this),
4705 * Construct and display a new frame containing the translation of this
4706 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4709 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4711 AlignmentI al = null;
4714 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4716 al = dna.translateCdna(codeTable);
4717 } catch (Exception ex)
4719 Console.error("Exception during translation. Please report this !",
4721 final String msg = MessageManager.getString(
4722 "label.error_when_translating_sequences_submit_bug_report");
4723 final String errorTitle = MessageManager
4724 .getString("label.implementation_error")
4725 + MessageManager.getString("label.translation_failed");
4726 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4727 JvOptionPane.ERROR_MESSAGE);
4730 if (al == null || al.getHeight() == 0)
4732 final String msg = MessageManager.getString(
4733 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4734 final String errorTitle = MessageManager
4735 .getString("label.translation_failed");
4736 JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4737 JvOptionPane.WARNING_MESSAGE);
4741 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4742 af.setFileFormat(this.currentFileFormat);
4743 final String newTitle = MessageManager
4744 .formatMessage("label.translation_of_params", new Object[]
4745 { this.getTitle(), codeTable.getId() });
4746 af.setTitle(newTitle);
4747 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4749 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4750 viewport.openSplitFrame(af, new Alignment(seqs));
4754 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4761 * Set the file format
4765 public void setFileFormat(FileFormatI format)
4767 this.currentFileFormat = format;
4771 * Try to load a features file onto the alignment.
4774 * contents or path to retrieve file or a File object
4776 * access mode of file (see jalview.io.AlignFile)
4777 * @return true if features file was parsed correctly.
4779 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4782 return avc.parseFeaturesFile(file, sourceType,
4783 Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4788 public void refreshFeatureUI(boolean enableIfNecessary)
4790 // note - currently this is only still here rather than in the controller
4791 // because of the featureSettings hard reference that is yet to be
4793 if (enableIfNecessary)
4795 viewport.setShowSequenceFeatures(true);
4796 showSeqFeatures.setSelected(true);
4802 public void dragEnter(DropTargetDragEvent evt)
4807 public void dragExit(DropTargetEvent evt)
4812 public void dragOver(DropTargetDragEvent evt)
4817 public void dropActionChanged(DropTargetDragEvent evt)
4822 public void drop(DropTargetDropEvent evt)
4824 // JAL-1552 - acceptDrop required before getTransferable call for
4825 // Java's Transferable for native dnd
4826 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4827 Transferable t = evt.getTransferable();
4829 final AlignFrame thisaf = this;
4830 final List<Object> files = new ArrayList<>();
4831 List<DataSourceType> protocols = new ArrayList<>();
4835 Desktop.transferFromDropTarget(files, protocols, evt, t);
4836 } catch (Exception e)
4838 e.printStackTrace();
4842 new Thread(new Runnable()
4849 // check to see if any of these files have names matching sequences
4852 SequenceIdMatcher idm = new SequenceIdMatcher(
4853 viewport.getAlignment().getSequencesArray());
4855 * Object[] { String,SequenceI}
4857 ArrayList<Object[]> filesmatched = new ArrayList<>();
4858 ArrayList<Object> filesnotmatched = new ArrayList<>();
4859 for (int i = 0; i < files.size(); i++)
4862 Object file = files.get(i);
4863 String fileName = file.toString();
4865 DataSourceType protocol = (file instanceof File
4866 ? DataSourceType.FILE
4867 : FormatAdapter.checkProtocol(fileName));
4868 if (protocol == DataSourceType.FILE)
4871 if (file instanceof File)
4874 Platform.cacheFileData(fl);
4878 fl = new File(fileName);
4880 pdbfn = fl.getName();
4882 else if (protocol == DataSourceType.URL)
4884 URL url = new URL(fileName);
4885 pdbfn = url.getFile();
4887 if (pdbfn.length() > 0)
4889 // attempt to find a match in the alignment
4890 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4891 int l = 0, c = pdbfn.indexOf(".");
4892 while (mtch == null && c != -1)
4897 } while ((c = pdbfn.indexOf(".", l)) > l);
4900 pdbfn = pdbfn.substring(0, l);
4902 mtch = idm.findAllIdMatches(pdbfn);
4909 type = new IdentifyFile().identify(file, protocol);
4910 } catch (Exception ex)
4914 if (type != null && type.isStructureFile())
4916 filesmatched.add(new Object[] { file, protocol, mtch });
4920 // File wasn't named like one of the sequences or wasn't a PDB
4922 filesnotmatched.add(file);
4926 if (filesmatched.size() > 0)
4928 boolean autoAssociate = Cache
4929 .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4932 String msg = MessageManager.formatMessage(
4933 "label.automatically_associate_structure_files_with_sequences_same_name",
4935 { Integer.valueOf(filesmatched.size())
4937 String ttl = MessageManager.getString(
4938 "label.automatically_associate_structure_files_by_name");
4939 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4940 ttl, JvOptionPane.YES_NO_OPTION);
4941 autoAssociate = choice == JvOptionPane.YES_OPTION;
4945 for (Object[] fm : filesmatched)
4947 // try and associate
4948 // TODO: may want to set a standard ID naming formalism for
4949 // associating PDB files which have no IDs.
4950 for (SequenceI toassoc : (SequenceI[]) fm[2])
4952 PDBEntry pe = new AssociatePdbFileWithSeq()
4953 .associatePdbWithSeq(fm[0].toString(),
4954 (DataSourceType) fm[1], toassoc, false,
4958 System.err.println("Associated file : "
4959 + (fm[0].toString()) + " with "
4960 + toassoc.getDisplayId(true));
4964 // TODO: do we need to update overview ? only if features are
4966 alignPanel.paintAlignment(true, false);
4972 * add declined structures as sequences
4974 for (Object[] o : filesmatched)
4976 filesnotmatched.add(o[0]);
4980 if (filesnotmatched.size() > 0)
4982 if (assocfiles > 0 && (Cache.getDefault(
4983 "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4984 || JvOptionPane.showConfirmDialog(thisaf,
4985 "<html>" + MessageManager.formatMessage(
4986 "label.ignore_unmatched_dropped_files_info",
4989 filesnotmatched.size())
4992 MessageManager.getString(
4993 "label.ignore_unmatched_dropped_files"),
4994 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4998 for (Object fn : filesnotmatched)
5000 loadJalviewDataFile(fn, null, null, null);
5004 } catch (Exception ex)
5006 ex.printStackTrace();
5009 }, "DropFile").start();
5014 * Attempt to load a "dropped" file or URL string, by testing in turn for
5016 * <li>an Annotation file</li>
5017 * <li>a JNet file</li>
5018 * <li>a features file</li>
5019 * <li>else try to interpret as an alignment file</li>
5023 * either a filename or a URL string.
5025 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5026 FileFormatI format, SequenceI assocSeq)
5028 // BH 2018 was String file
5031 if (sourceType == null)
5033 sourceType = FormatAdapter.checkProtocol(file);
5035 // if the file isn't identified, or not positively identified as some
5036 // other filetype (PFAM is default unidentified alignment file type) then
5037 // try to parse as annotation.
5038 boolean isAnnotation = (format == null
5039 || FileFormat.Pfam.equals(format))
5040 ? new AnnotationFile().annotateAlignmentView(viewport,
5046 // first see if its a T-COFFEE score file
5047 TCoffeeScoreFile tcf = null;
5050 tcf = new TCoffeeScoreFile(file, sourceType);
5053 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5057 new TCoffeeColourScheme(viewport.getAlignment()));
5058 isAnnotation = true;
5059 setStatus(MessageManager.getString(
5060 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5064 // some problem - if no warning its probable that the ID matching
5065 // process didn't work
5066 JvOptionPane.showMessageDialog(Desktop.desktop,
5067 tcf.getWarningMessage() == null
5068 ? MessageManager.getString(
5069 "label.check_file_matches_sequence_ids_alignment")
5070 : tcf.getWarningMessage(),
5071 MessageManager.getString(
5072 "label.problem_reading_tcoffee_score_file"),
5073 JvOptionPane.WARNING_MESSAGE);
5080 } catch (Exception x)
5083 "Exception when processing data source as T-COFFEE score file",
5089 // try to see if its a JNet 'concise' style annotation file *before*
5091 // try to parse it as a features file
5094 format = new IdentifyFile().identify(file, sourceType);
5096 if (FileFormat.ScoreMatrix == format)
5098 ScoreMatrixFile sm = new ScoreMatrixFile(
5099 new FileParse(file, sourceType));
5101 // todo: i18n this message
5102 setStatus(MessageManager.formatMessage(
5103 "label.successfully_loaded_matrix",
5104 sm.getMatrixName()));
5106 else if (FileFormat.Jnet.equals(format))
5108 JPredFile predictions = new JPredFile(file, sourceType);
5109 new JnetAnnotationMaker();
5110 JnetAnnotationMaker.add_annotation(predictions,
5111 viewport.getAlignment(), 0, false);
5112 viewport.getAlignment().setupJPredAlignment();
5113 isAnnotation = true;
5115 // else if (IdentifyFile.FeaturesFile.equals(format))
5116 else if (FileFormat.Features.equals(format))
5118 if (parseFeaturesFile(file, sourceType))
5120 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5121 if (splitFrame != null)
5123 splitFrame.repaint();
5127 alignPanel.paintAlignment(true, true);
5133 new FileLoader().LoadFile(viewport, file, sourceType, format);
5140 alignPanel.adjustAnnotationHeight();
5141 viewport.updateSequenceIdColours();
5142 buildSortByAnnotationScoresMenu();
5143 alignPanel.paintAlignment(true, true);
5145 } catch (Exception ex)
5147 ex.printStackTrace();
5148 } catch (OutOfMemoryError oom)
5153 } catch (Exception x)
5158 + (sourceType != null
5159 ? (sourceType == DataSourceType.PASTE
5161 : "using " + sourceType + " from "
5165 ? "(parsing as '" + format + "' file)"
5167 oom, Desktop.desktop);
5172 * Method invoked by the ChangeListener on the tabbed pane, in other words
5173 * when a different tabbed pane is selected by the user or programmatically.
5176 public void tabSelectionChanged(int index)
5180 alignPanel = alignPanels.get(index);
5181 viewport = alignPanel.av;
5182 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5183 setMenusFromViewport(viewport);
5184 if (featureSettings != null && featureSettings.isOpen()
5185 && featureSettings.fr.getViewport() != viewport)
5187 if (viewport.isShowSequenceFeatures())
5189 // refresh the featureSettings to reflect UI change
5190 showFeatureSettingsUI();
5194 // close feature settings for this view.
5195 featureSettings.close();
5202 * 'focus' any colour slider that is open to the selected viewport
5204 if (viewport.getConservationSelected())
5206 SliderPanel.setConservationSlider(alignPanel,
5207 viewport.getResidueShading(), alignPanel.getViewName());
5211 SliderPanel.hideConservationSlider();
5213 if (viewport.getAbovePIDThreshold())
5215 SliderPanel.setPIDSliderSource(alignPanel,
5216 viewport.getResidueShading(), alignPanel.getViewName());
5220 SliderPanel.hidePIDSlider();
5224 * If there is a frame linked to this one in a SplitPane, switch it to the
5225 * same view tab index. No infinite recursion of calls should happen, since
5226 * tabSelectionChanged() should not get invoked on setting the selected
5227 * index to an unchanged value. Guard against setting an invalid index
5228 * before the new view peer tab has been created.
5230 final AlignViewportI peer = viewport.getCodingComplement();
5233 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5234 .getAlignPanel().alignFrame;
5235 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5237 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5243 * On right mouse click on view tab, prompt for and set new view name.
5246 public void tabbedPane_mousePressed(MouseEvent e)
5248 if (e.isPopupTrigger())
5250 String msg = MessageManager.getString("label.enter_view_name");
5251 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5252 String reply = JvOptionPane.showInputDialog(msg, ttl);
5256 viewport.setViewName(reply);
5257 // TODO warn if reply is in getExistingViewNames()?
5258 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5263 public AlignViewport getCurrentView()
5269 * Open the dialog for regex description parsing.
5272 protected void extractScores_actionPerformed(ActionEvent e)
5274 ParseProperties pp = new jalview.analysis.ParseProperties(
5275 viewport.getAlignment());
5276 // TODO: verify regex and introduce GUI dialog for version 2.5
5277 // if (pp.getScoresFromDescription("col", "score column ",
5278 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5280 if (pp.getScoresFromDescription("description column",
5281 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5283 buildSortByAnnotationScoresMenu();
5291 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5295 protected void showDbRefs_actionPerformed(ActionEvent e)
5297 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5303 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5307 protected void showNpFeats_actionPerformed(ActionEvent e)
5309 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5313 * find the viewport amongst the tabs in this alignment frame and close that
5318 public boolean closeView(AlignViewportI av)
5322 this.closeMenuItem_actionPerformed(false);
5325 Component[] comp = tabbedPane.getComponents();
5326 for (int i = 0; comp != null && i < comp.length; i++)
5328 if (comp[i] instanceof AlignmentPanel)
5330 if (((AlignmentPanel) comp[i]).av == av)
5333 closeView((AlignmentPanel) comp[i]);
5341 protected void build_fetchdbmenu(JMenu webService)
5343 // Temporary hack - DBRef Fetcher always top level ws entry.
5344 // TODO We probably want to store a sequence database checklist in
5345 // preferences and have checkboxes.. rather than individual sources selected
5347 final JMenu rfetch = new JMenu(
5348 MessageManager.getString("action.fetch_db_references"));
5349 rfetch.setToolTipText(MessageManager.getString(
5350 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5351 webService.add(rfetch);
5353 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5354 MessageManager.getString("option.trim_retrieved_seqs"));
5355 trimrs.setToolTipText(
5356 MessageManager.getString("label.trim_retrieved_sequences"));
5358 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5359 trimrs.addActionListener(new ActionListener()
5362 public void actionPerformed(ActionEvent e)
5364 trimrs.setSelected(trimrs.isSelected());
5365 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5366 Boolean.valueOf(trimrs.isSelected()).toString());
5370 JMenuItem fetchr = new JMenuItem(
5371 MessageManager.getString("label.standard_databases"));
5372 fetchr.setToolTipText(
5373 MessageManager.getString("label.fetch_embl_uniprot"));
5374 fetchr.addActionListener(new ActionListener()
5378 public void actionPerformed(ActionEvent e)
5380 new Thread(new Runnable()
5385 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5386 .getAlignment().isNucleotide();
5387 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5388 alignPanel.av.getSequenceSelection(),
5389 alignPanel.alignFrame, null,
5390 alignPanel.alignFrame.featureSettings, isNucleotide);
5391 dbRefFetcher.addListener(new FetchFinishedListenerI()
5394 public void finished()
5397 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5398 .getFeatureSettingsModels())
5401 alignPanel.av.mergeFeaturesStyle(srcSettings);
5403 AlignFrame.this.setMenusForViewport();
5406 dbRefFetcher.fetchDBRefs(false);
5408 }, "BuildFetchDBMenu").start();
5414 new Thread(new Runnable()
5419 final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5420 .getSequenceFetcherSingleton();
5421 javax.swing.SwingUtilities.invokeLater(new Runnable()
5426 String[] dbclasses = sf.getNonAlignmentSources();
5427 List<DbSourceProxy> otherdb;
5428 JMenu dfetch = new JMenu();
5429 JMenu ifetch = new JMenu();
5430 JMenuItem fetchr = null;
5431 int comp = 0, icomp = 0, mcomp = 15;
5432 String mname = null;
5434 for (String dbclass : dbclasses)
5436 otherdb = sf.getSourceProxy(dbclass);
5437 // add a single entry for this class, or submenu allowing 'fetch
5439 if (otherdb == null || otherdb.size() < 1)
5445 mname = "From " + dbclass;
5447 if (otherdb.size() == 1)
5449 final DbSourceProxy[] dassource = otherdb
5450 .toArray(new DbSourceProxy[0]);
5451 DbSourceProxy src = otherdb.get(0);
5452 fetchr = new JMenuItem(src.getDbSource());
5453 fetchr.addActionListener(new ActionListener()
5457 public void actionPerformed(ActionEvent e)
5459 new Thread(new Runnable()
5465 boolean isNucleotide = alignPanel.alignFrame
5466 .getViewport().getAlignment()
5468 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5469 alignPanel.av.getSequenceSelection(),
5470 alignPanel.alignFrame, dassource,
5471 alignPanel.alignFrame.featureSettings,
5474 .addListener(new FetchFinishedListenerI()
5477 public void finished()
5479 FeatureSettingsModelI srcSettings = dassource[0]
5480 .getFeatureColourScheme();
5481 alignPanel.av.mergeFeaturesStyle(
5483 AlignFrame.this.setMenusForViewport();
5486 dbRefFetcher.fetchDBRefs(false);
5492 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5493 MessageManager.formatMessage(
5494 "label.fetch_retrieve_from", new Object[]
5495 { src.getDbName() })));
5501 final DbSourceProxy[] dassource = otherdb
5502 .toArray(new DbSourceProxy[0]);
5504 DbSourceProxy src = otherdb.get(0);
5505 fetchr = new JMenuItem(MessageManager
5506 .formatMessage("label.fetch_all_param", new Object[]
5507 { src.getDbSource() }));
5508 fetchr.addActionListener(new ActionListener()
5511 public void actionPerformed(ActionEvent e)
5513 new Thread(new Runnable()
5519 boolean isNucleotide = alignPanel.alignFrame
5520 .getViewport().getAlignment()
5522 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5523 alignPanel.av.getSequenceSelection(),
5524 alignPanel.alignFrame, dassource,
5525 alignPanel.alignFrame.featureSettings,
5528 .addListener(new FetchFinishedListenerI()
5531 public void finished()
5533 AlignFrame.this.setMenusForViewport();
5536 dbRefFetcher.fetchDBRefs(false);
5542 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5543 MessageManager.formatMessage(
5544 "label.fetch_retrieve_from_all_sources",
5546 { Integer.valueOf(otherdb.size())
5548 src.getDbSource(), src.getDbName() })));
5551 // and then build the rest of the individual menus
5552 ifetch = new JMenu(MessageManager.formatMessage(
5553 "label.source_from_db_source", new Object[]
5554 { src.getDbSource() }));
5556 String imname = null;
5558 for (DbSourceProxy sproxy : otherdb)
5560 String dbname = sproxy.getDbName();
5561 String sname = dbname.length() > 5
5562 ? dbname.substring(0, 5) + "..."
5564 String msname = dbname.length() > 10
5565 ? dbname.substring(0, 10) + "..."
5569 imname = MessageManager
5570 .formatMessage("label.from_msname", new Object[]
5573 fetchr = new JMenuItem(msname);
5574 final DbSourceProxy[] dassrc = { sproxy };
5575 fetchr.addActionListener(new ActionListener()
5579 public void actionPerformed(ActionEvent e)
5581 new Thread(new Runnable()
5587 boolean isNucleotide = alignPanel.alignFrame
5588 .getViewport().getAlignment()
5590 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5591 alignPanel.av.getSequenceSelection(),
5592 alignPanel.alignFrame, dassrc,
5593 alignPanel.alignFrame.featureSettings,
5596 .addListener(new FetchFinishedListenerI()
5599 public void finished()
5601 AlignFrame.this.setMenusForViewport();
5604 dbRefFetcher.fetchDBRefs(false);
5610 fetchr.setToolTipText(
5611 "<html>" + MessageManager.formatMessage(
5612 "label.fetch_retrieve_from", new Object[]
5616 if (++icomp >= mcomp || i == (otherdb.size()))
5618 ifetch.setText(MessageManager.formatMessage(
5619 "label.source_to_target", imname, sname));
5621 ifetch = new JMenu();
5629 if (comp >= mcomp || dbi >= (dbclasses.length))
5631 dfetch.setText(MessageManager.formatMessage(
5632 "label.source_to_target", mname, dbclass));
5634 dfetch = new JMenu();
5647 * Left justify the whole alignment.
5650 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5652 AlignmentI al = viewport.getAlignment();
5654 viewport.firePropertyChange("alignment", null, al);
5658 * Right justify the whole alignment.
5661 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5663 AlignmentI al = viewport.getAlignment();
5665 viewport.firePropertyChange("alignment", null, al);
5669 public void setShowSeqFeatures(boolean b)
5671 showSeqFeatures.setSelected(b);
5672 viewport.setShowSequenceFeatures(b);
5679 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5680 * awt.event.ActionEvent)
5683 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5685 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5686 alignPanel.paintAlignment(false, false);
5693 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5697 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5699 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5700 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5708 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5709 * .event.ActionEvent)
5712 protected void showGroupConservation_actionPerformed(ActionEvent e)
5714 viewport.setShowGroupConservation(showGroupConservation.getState());
5715 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5722 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5723 * .event.ActionEvent)
5726 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5728 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5729 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5736 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5737 * .event.ActionEvent)
5740 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5742 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5743 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5747 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5749 showSequenceLogo.setState(true);
5750 viewport.setShowSequenceLogo(true);
5751 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5752 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5756 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5758 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5765 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5766 * .event.ActionEvent)
5769 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5771 if (avc.makeGroupsFromSelection())
5773 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5774 alignPanel.updateAnnotation();
5775 alignPanel.paintAlignment(true,
5776 viewport.needToUpdateStructureViews());
5780 public void clearAlignmentSeqRep()
5782 // TODO refactor alignmentseqrep to controller
5783 if (viewport.getAlignment().hasSeqrep())
5785 viewport.getAlignment().setSeqrep(null);
5786 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5787 alignPanel.updateAnnotation();
5788 alignPanel.paintAlignment(true, true);
5793 protected void createGroup_actionPerformed(ActionEvent e)
5795 if (avc.createGroup())
5797 if (applyAutoAnnotationSettings.isSelected())
5799 alignPanel.updateAnnotation(true, false);
5801 alignPanel.alignmentChanged();
5806 protected void unGroup_actionPerformed(ActionEvent e)
5810 alignPanel.alignmentChanged();
5815 * make the given alignmentPanel the currently selected tab
5817 * @param alignmentPanel
5819 public void setDisplayedView(AlignmentPanel alignmentPanel)
5821 if (!viewport.getSequenceSetId()
5822 .equals(alignmentPanel.av.getSequenceSetId()))
5824 throw new Error(MessageManager.getString(
5825 "error.implementation_error_cannot_show_view_alignment_frame"));
5827 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5828 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5830 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5835 * Action on selection of menu options to Show or Hide annotations.
5838 * @param forSequences
5839 * update sequence-related annotations
5840 * @param forAlignment
5841 * update non-sequence-related annotations
5844 protected void setAnnotationsVisibility(boolean visible,
5845 boolean forSequences, boolean forAlignment)
5847 AlignmentAnnotation[] anns = alignPanel.getAlignment()
5848 .getAlignmentAnnotation();
5853 for (AlignmentAnnotation aa : anns)
5856 * don't display non-positional annotations on an alignment
5858 if (aa.annotations == null)
5862 boolean apply = (aa.sequenceRef == null && forAlignment)
5863 || (aa.sequenceRef != null && forSequences);
5866 aa.visible = visible;
5869 alignPanel.validateAnnotationDimensions(true);
5870 alignPanel.alignmentChanged();
5874 * Store selected annotation sort order for the view and repaint.
5877 protected void sortAnnotations_actionPerformed()
5879 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5881 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5882 alignPanel.paintAlignment(false, false);
5887 * @return alignment panels in this alignment frame
5889 public List<? extends AlignmentViewPanel> getAlignPanels()
5891 // alignPanels is never null
5892 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5897 * Open a new alignment window, with the cDNA associated with this (protein)
5898 * alignment, aligned as is the protein.
5900 protected void viewAsCdna_actionPerformed()
5902 // TODO no longer a menu action - refactor as required
5903 final AlignmentI alignment = getViewport().getAlignment();
5904 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5905 if (mappings == null)
5909 List<SequenceI> cdnaSeqs = new ArrayList<>();
5910 for (SequenceI aaSeq : alignment.getSequences())
5912 for (AlignedCodonFrame acf : mappings)
5914 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5918 * There is a cDNA mapping for this protein sequence - add to new
5919 * alignment. It will share the same dataset sequence as other mapped
5920 * cDNA (no new mappings need to be created).
5922 final Sequence newSeq = new Sequence(dnaSeq);
5923 newSeq.setDatasetSequence(dnaSeq);
5924 cdnaSeqs.add(newSeq);
5928 if (cdnaSeqs.size() == 0)
5930 // show a warning dialog no mapped cDNA
5933 AlignmentI cdna = new Alignment(
5934 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5935 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5936 AlignFrame.DEFAULT_HEIGHT);
5937 cdna.alignAs(alignment);
5938 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5940 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5941 AlignFrame.DEFAULT_HEIGHT);
5945 * Set visibility of dna/protein complement view (available when shown in a
5951 protected void showComplement_actionPerformed(boolean show)
5953 SplitContainerI sf = getSplitViewContainer();
5956 sf.setComplementVisible(this, show);
5961 * Generate the reverse (optionally complemented) of the selected sequences,
5962 * and add them to the alignment
5965 protected void showReverse_actionPerformed(boolean complement)
5967 AlignmentI al = null;
5970 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5971 al = dna.reverseCdna(complement);
5972 viewport.addAlignment(al, "");
5973 addHistoryItem(new EditCommand(
5974 MessageManager.getString("label.add_sequences"), Action.PASTE,
5975 al.getSequencesArray(), 0, al.getWidth(),
5976 viewport.getAlignment()));
5977 } catch (Exception ex)
5979 System.err.println(ex.getMessage());
5985 * Try to run a script in the Groovy console, having first ensured that this
5986 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5987 * be targeted at this alignment.
5990 protected void runGroovy_actionPerformed()
5992 Jalview.setCurrentAlignFrame(this);
5993 groovy.ui.Console console = Desktop.getGroovyConsole();
5994 if (console != null)
5998 console.runScript();
5999 } catch (Exception ex)
6001 System.err.println((ex.toString()));
6002 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
6003 MessageManager.getString("label.couldnt_run_groovy_script"),
6004 MessageManager.getString("label.groovy_support_failed"),
6005 JvOptionPane.ERROR_MESSAGE);
6010 System.err.println("Can't run Groovy script as console not found");
6015 * Hides columns containing (or not containing) a specified feature, provided
6016 * that would not leave all columns hidden
6018 * @param featureType
6019 * @param columnsContaining
6022 public boolean hideFeatureColumns(String featureType,
6023 boolean columnsContaining)
6025 boolean notForHiding = avc.markColumnsContainingFeatures(
6026 columnsContaining, false, false, featureType);
6029 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6030 false, featureType))
6032 getViewport().hideSelectedColumns();
6040 protected void selectHighlightedColumns_actionPerformed(
6041 ActionEvent actionEvent)
6043 // include key modifier check in case user selects from menu
6044 avc.markHighlightedColumns(
6045 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6046 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6047 | ActionEvent.CTRL_MASK)) != 0);
6051 * Rebuilds the Colour menu, including any user-defined colours which have
6052 * been loaded either on startup or during the session
6054 public void buildColourMenu()
6056 colourMenu.removeAll();
6058 colourMenu.add(applyToAllGroups);
6059 colourMenu.add(textColour);
6060 colourMenu.addSeparator();
6062 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6063 viewport.getAlignment(), false);
6065 colourMenu.add(annotationColour);
6066 bg.add(annotationColour);
6067 colourMenu.addSeparator();
6068 colourMenu.add(conservationMenuItem);
6069 colourMenu.add(modifyConservation);
6070 colourMenu.add(abovePIDThreshold);
6071 colourMenu.add(modifyPID);
6073 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6074 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6078 * Open a dialog (if not already open) that allows the user to select and
6079 * calculate PCA or Tree analysis
6081 protected void openTreePcaDialog()
6083 if (alignPanel.getCalculationDialog() == null)
6085 new CalculationChooser(AlignFrame.this);
6090 protected void loadVcf_actionPerformed()
6092 JalviewFileChooser chooser = new JalviewFileChooser(
6093 Cache.getProperty("LAST_DIRECTORY"));
6094 chooser.setFileView(new JalviewFileView());
6095 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6096 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6097 final AlignFrame us = this;
6098 chooser.setResponseHandler(0, new Runnable()
6103 String choice = chooser.getSelectedFile().getPath();
6104 Cache.setProperty("LAST_DIRECTORY", choice);
6105 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6106 new VCFLoader(choice).loadVCF(seqs, us);
6109 chooser.showOpenDialog(null);
6113 private Rectangle lastFeatureSettingsBounds = null;
6116 public void setFeatureSettingsGeometry(Rectangle bounds)
6118 lastFeatureSettingsBounds = bounds;
6122 public Rectangle getFeatureSettingsGeometry()
6124 return lastFeatureSettingsBounds;
6128 class PrintThread extends Thread
6132 public PrintThread(AlignmentPanel ap)
6137 static PageFormat pf;
6142 PrinterJob printJob = PrinterJob.getPrinterJob();
6146 printJob.setPrintable(ap, pf);
6150 printJob.setPrintable(ap);
6153 if (printJob.printDialog())
6158 } catch (Exception PrintException)
6160 PrintException.printStackTrace();