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.util.Locale;
25 import java.io.IOException;
26 import java.util.HashSet;
29 import javax.swing.JFileChooser;
30 import javax.swing.JOptionPane;
31 import java.awt.BorderLayout;
32 import java.awt.Color;
33 import java.awt.Component;
34 import java.awt.Dimension;
35 import java.awt.Rectangle;
36 import java.awt.Toolkit;
37 import java.awt.datatransfer.Clipboard;
38 import java.awt.datatransfer.DataFlavor;
39 import java.awt.datatransfer.StringSelection;
40 import java.awt.datatransfer.Transferable;
41 import java.awt.dnd.DnDConstants;
42 import java.awt.dnd.DropTargetDragEvent;
43 import java.awt.dnd.DropTargetDropEvent;
44 import java.awt.dnd.DropTargetEvent;
45 import java.awt.dnd.DropTargetListener;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.event.FocusAdapter;
49 import java.awt.event.FocusEvent;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.awt.event.KeyAdapter;
53 import java.awt.event.KeyEvent;
54 import java.awt.event.MouseEvent;
55 import java.awt.print.PageFormat;
56 import java.awt.print.PrinterJob;
57 import java.beans.PropertyChangeEvent;
58 import java.beans.PropertyChangeListener;
60 import java.io.FileWriter;
61 import java.io.PrintWriter;
63 import java.util.ArrayList;
64 import java.util.Arrays;
65 import java.util.Collection;
66 import java.util.Deque;
67 import java.util.Enumeration;
68 import java.util.Hashtable;
69 import java.util.List;
70 import java.util.Vector;
72 import javax.swing.ButtonGroup;
73 import javax.swing.JCheckBoxMenuItem;
74 import javax.swing.JComponent;
75 import javax.swing.JEditorPane;
76 import javax.swing.JInternalFrame;
77 import javax.swing.JLabel;
78 import javax.swing.JLayeredPane;
79 import javax.swing.JMenu;
80 import javax.swing.JMenuItem;
81 import javax.swing.JPanel;
82 import javax.swing.JScrollPane;
83 import javax.swing.SwingUtilities;
84 import javax.swing.event.InternalFrameAdapter;
85 import javax.swing.event.InternalFrameEvent;
87 import ext.vamsas.ServiceHandle;
88 import jalview.analysis.AlignmentSorter;
89 import jalview.analysis.AlignmentUtils;
90 import jalview.analysis.CrossRef;
91 import jalview.analysis.Dna;
92 import jalview.analysis.GeneticCodeI;
93 import jalview.analysis.ParseProperties;
94 import jalview.analysis.SequenceIdMatcher;
95 import jalview.api.AlignExportSettingsI;
96 import jalview.api.AlignViewControllerGuiI;
97 import jalview.api.AlignViewControllerI;
98 import jalview.api.AlignViewportI;
99 import jalview.api.AlignmentViewPanel;
100 import jalview.api.FeatureSettingsControllerI;
101 import jalview.api.FeatureSettingsModelI;
102 import jalview.api.SplitContainerI;
103 import jalview.api.ViewStyleI;
104 import jalview.api.analysis.SimilarityParamsI;
105 import jalview.bin.Cache;
106 import jalview.bin.Console;
107 import jalview.bin.Jalview;
108 import jalview.commands.CommandI;
109 import jalview.commands.EditCommand;
110 import jalview.commands.EditCommand.Action;
111 import jalview.commands.OrderCommand;
112 import jalview.commands.RemoveGapColCommand;
113 import jalview.commands.RemoveGapsCommand;
114 import jalview.commands.SlideSequencesCommand;
115 import jalview.commands.TrimRegionCommand;
116 import jalview.datamodel.AlignExportSettingsAdapter;
117 import jalview.datamodel.AlignedCodonFrame;
118 import jalview.datamodel.Alignment;
119 import jalview.datamodel.AlignmentAnnotation;
120 import jalview.datamodel.AlignmentExportData;
121 import jalview.datamodel.AlignmentI;
122 import jalview.datamodel.AlignmentOrder;
123 import jalview.datamodel.AlignmentView;
124 import jalview.datamodel.ColumnSelection;
125 import jalview.datamodel.HiddenColumns;
126 import jalview.datamodel.PDBEntry;
127 import jalview.datamodel.SeqCigar;
128 import jalview.datamodel.Sequence;
129 import jalview.datamodel.SequenceGroup;
130 import jalview.datamodel.SequenceI;
131 import jalview.gui.ColourMenuHelper.ColourChangeListener;
132 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
133 import jalview.hmmer.HMMAlign;
134 import jalview.hmmer.HMMBuild;
135 import jalview.hmmer.HMMERParamStore;
136 import jalview.hmmer.HMMERPreset;
137 import jalview.hmmer.HMMSearch;
138 import jalview.hmmer.HmmerCommand;
139 import jalview.hmmer.JackHMMER;
140 import jalview.io.AlignmentProperties;
141 import jalview.io.AnnotationFile;
142 import jalview.io.BackupFiles;
143 import jalview.io.BioJsHTMLOutput;
144 import jalview.io.DataSourceType;
145 import jalview.io.FileFormat;
146 import jalview.io.FileFormatI;
147 import jalview.io.FileFormats;
148 import jalview.io.FileLoader;
149 import jalview.io.FileParse;
150 import jalview.io.FormatAdapter;
151 import jalview.io.HtmlSvgOutput;
152 import jalview.io.IdentifyFile;
153 import jalview.io.JPredFile;
154 import jalview.io.JalviewFileChooser;
155 import jalview.io.JalviewFileView;
156 import jalview.io.JnetAnnotationMaker;
157 import jalview.io.NewickFile;
158 import jalview.io.ScoreMatrixFile;
159 import jalview.io.TCoffeeScoreFile;
160 import jalview.io.vcf.VCFLoader;
161 import jalview.jbgui.GAlignFrame;
162 import jalview.project.Jalview2XML;
163 import jalview.schemes.ColourSchemeI;
164 import jalview.schemes.ColourSchemes;
165 import jalview.schemes.ResidueColourScheme;
166 import jalview.schemes.TCoffeeColourScheme;
167 import jalview.util.HttpUtils;
168 import jalview.util.ImageMaker.TYPE;
169 import jalview.util.MessageManager;
170 import jalview.util.Platform;
171 import jalview.viewmodel.AlignmentViewport;
172 import jalview.viewmodel.ViewportRanges;
173 import jalview.ws.DBRefFetcher;
174 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
175 import jalview.ws.ServiceChangeListener;
176 import jalview.ws.WSDiscovererI;
177 import jalview.ws.api.ServiceWithParameters;
178 import jalview.ws.jws1.Discoverer;
179 import jalview.ws.jws2.Jws2Discoverer;
180 import jalview.ws.jws2.PreferredServiceRegistry;
181 import jalview.ws.params.ArgumentI;
182 import jalview.ws.params.ParamDatastoreI;
183 import jalview.ws.params.WsParamSetI;
184 import jalview.ws.seqfetcher.DbSourceProxy;
185 import jalview.ws2.client.api.WebServiceDiscovererI;
186 import jalview.ws2.client.ebi.JobDispatcherWSDiscoverer;
187 import jalview.ws2.client.jpred4.JPred4WSDiscoverer;
188 import jalview.ws2.client.slivka.SlivkaWSDiscoverer;
189 import jalview.ws2.gui.WebServicesMenuManager;
191 import java.io.IOException;
192 import java.util.HashSet;
193 import java.util.Set;
195 import javax.swing.JFileChooser;
196 import javax.swing.JOptionPane;
198 import java.awt.BorderLayout;
199 import java.awt.Color;
200 import java.awt.Component;
201 import java.awt.Dimension;
202 import java.awt.Rectangle;
203 import java.awt.Toolkit;
204 import java.awt.datatransfer.Clipboard;
205 import java.awt.datatransfer.DataFlavor;
206 import java.awt.datatransfer.StringSelection;
207 import java.awt.datatransfer.Transferable;
208 import java.awt.dnd.DnDConstants;
209 import java.awt.dnd.DropTargetDragEvent;
210 import java.awt.dnd.DropTargetDropEvent;
211 import java.awt.dnd.DropTargetEvent;
212 import java.awt.dnd.DropTargetListener;
213 import java.awt.event.ActionEvent;
214 import java.awt.event.ActionListener;
215 import java.awt.event.FocusAdapter;
216 import java.awt.event.FocusEvent;
217 import java.awt.event.ItemEvent;
218 import java.awt.event.ItemListener;
219 import java.awt.event.KeyAdapter;
220 import java.awt.event.KeyEvent;
221 import java.awt.event.MouseEvent;
222 import java.awt.print.PageFormat;
223 import java.awt.print.PrinterJob;
224 import java.beans.PropertyChangeEvent;
225 import java.beans.PropertyChangeListener;
227 import java.io.FileWriter;
228 import java.io.PrintWriter;
230 import java.util.ArrayList;
231 import java.util.Arrays;
232 import java.util.Collection;
233 import java.util.Deque;
234 import java.util.Enumeration;
235 import java.util.Hashtable;
236 import java.util.List;
237 import java.util.Vector;
239 import javax.swing.ButtonGroup;
240 import javax.swing.JCheckBoxMenuItem;
241 import javax.swing.JComponent;
242 import javax.swing.JEditorPane;
243 import javax.swing.JInternalFrame;
244 import javax.swing.JLabel;
245 import javax.swing.JLayeredPane;
246 import javax.swing.JMenu;
247 import javax.swing.JMenuItem;
248 import javax.swing.JPanel;
249 import javax.swing.JScrollPane;
250 import javax.swing.SwingUtilities;
251 import javax.swing.event.InternalFrameAdapter;
252 import javax.swing.event.InternalFrameEvent;
254 import ext.vamsas.ServiceHandle;
260 * @version $Revision$
262 @SuppressWarnings("serial")
263 public class AlignFrame extends GAlignFrame
264 implements DropTargetListener, IProgressIndicator,
265 AlignViewControllerGuiI, ColourChangeListener, ServiceChangeListener
268 public static int frameCount;
269 public static final int DEFAULT_WIDTH = 700;
271 public static final int DEFAULT_HEIGHT = 500;
274 * The currently displayed panel (selected tabbed view if more than one)
276 public AlignmentPanel alignPanel;
278 AlignViewport viewport;
280 public AlignViewControllerI avc;
282 List<AlignmentPanel> alignPanels = new ArrayList<>();
285 * Last format used to load or save alignments in this window
287 FileFormatI currentFileFormat = null;
290 * Current filename for this alignment
292 String fileName = null;
295 * TODO: remove reference to 'FileObject' in AlignFrame - not correct mapping
301 private DataSourceType protocol ;
303 * Creates a new AlignFrame object with specific width and height.
309 public AlignFrame(AlignmentI al, int width, int height)
311 this(al, null, width, height);
315 * Creates a new AlignFrame object with specific width, height and
321 * @param sequenceSetId
323 public AlignFrame(AlignmentI al, int width, int height,
324 String sequenceSetId)
326 this(al, null, width, height, sequenceSetId);
330 * Creates a new AlignFrame object with specific width, height and
336 * @param sequenceSetId
339 public AlignFrame(AlignmentI al, int width, int height,
340 String sequenceSetId, String viewId)
342 this(al, null, width, height, sequenceSetId, viewId);
346 * new alignment window with hidden columns
350 * @param hiddenColumns
351 * ColumnSelection or null
353 * Width of alignment frame
357 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
360 this(al, hiddenColumns, width, height, null);
364 * Create alignment frame for al with hiddenColumns, a specific width and
365 * height, and specific sequenceId
368 * @param hiddenColumns
371 * @param sequenceSetId
374 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
375 int height, String sequenceSetId)
377 this(al, hiddenColumns, width, height, sequenceSetId, null);
381 * Create alignment frame for al with hiddenColumns, a specific width and
382 * height, and specific sequenceId
385 * @param hiddenColumns
388 * @param sequenceSetId
393 public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
394 int height, String sequenceSetId, String viewId)
397 setSize(width, height);
399 if (al.getDataset() == null)
404 viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
406 // JalviewJS needs to distinguish a new panel from an old one in init()
407 // alignPanel = new AlignmentPanel(this, viewport);
408 // addAlignmentPanel(alignPanel, true);
412 public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
413 HiddenColumns hiddenColumns, int width, int height)
415 setSize(width, height);
417 if (al.getDataset() == null)
422 viewport = new AlignViewport(al, hiddenColumns);
424 if (hiddenSeqs != null && hiddenSeqs.length > 0)
426 viewport.hideSequence(hiddenSeqs);
428 // alignPanel = new AlignmentPanel(this, viewport);
429 // addAlignmentPanel(alignPanel, true);
434 * Make a new AlignFrame from existing alignmentPanels
441 public AlignFrame(AlignmentPanel ap)
445 // addAlignmentPanel(ap, false);
450 * initalise the alignframe from the underlying viewport data and the
455 boolean newPanel = (alignPanel == null);
456 viewport.setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
461 // need to set this up front if NOANNOTATION is
462 // used in conjunction with SHOWOVERVIEW.
464 // I have not determined if this is appropriate for
465 // Jalview/Java, as it means we are setting this flag
466 // for all subsequent AlignFrames. For now, at least,
467 // I am setting it to be JalviewJS-only.
469 boolean showAnnotation = Jalview.getInstance().getShowAnnotation();
470 viewport.setShowAnnotation(showAnnotation);
472 alignPanel = new AlignmentPanel(this, viewport);
474 addAlignmentPanel(alignPanel, newPanel);
475 // setBackground(Color.white); // BH 2019
477 if (!Jalview.isHeadlessMode())
479 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
481 statusPanel.setVisible(Jalview.getInstance().getShowStatus());
482 alignFrameMenuBar.setVisible(Jalview.getInstance().getAllowMenuBar());
485 avc = new jalview.controller.AlignViewController(this, viewport,
487 if (viewport.getAlignmentConservationAnnotation() == null)
489 // BLOSUM62Colour.setEnabled(false);
490 conservationMenuItem.setEnabled(false);
491 modifyConservation.setEnabled(false);
492 // PIDColour.setEnabled(false);
493 // abovePIDThreshold.setEnabled(false);
494 // modifyPID.setEnabled(false);
497 String sortby = Cache.getDefault(Preferences.SORT_ALIGNMENT,
500 if (sortby.equals("Id"))
502 sortIDMenuItem_actionPerformed(null);
504 else if (sortby.equals("Pairwise Identity"))
506 sortPairwiseMenuItem_actionPerformed(null);
511 // this.alignPanel.av
512 // .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
514 setMenusFromViewport(viewport);
515 buildSortByAnnotationScoresMenu();
516 calculateTree.addActionListener(new ActionListener()
520 public void actionPerformed(ActionEvent e)
527 if (Desktop.getDesktopPane() != null)
529 this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
530 addServiceListeners();
531 if (!Platform.isJS())
537 if (viewport.getWrapAlignment())
539 wrapMenuItem_actionPerformed(null);
542 if (Cache.getDefault(Preferences.SHOW_OVERVIEW, false))
544 this.overviewMenuItem_actionPerformed(null);
549 final List<AlignmentViewPanel> selviews = new ArrayList<>();
550 final List<AlignmentPanel> origview = new ArrayList<>();
551 final String menuLabel = MessageManager
552 .getString("label.copy_format_from");
553 ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
554 new ViewSetProvider()
558 public AlignmentPanel[] getAllAlignmentPanels()
561 origview.add(alignPanel);
562 // make an array of all alignment panels except for this one
563 List<AlignmentPanel> aps = new ArrayList<>(
564 Arrays.asList(Desktop.getAlignmentPanels(null)));
565 aps.remove(AlignFrame.this.alignPanel);
566 return aps.toArray(new AlignmentPanel[aps.size()]);
568 }, selviews, new ItemListener()
572 public void itemStateChanged(ItemEvent e)
574 if (origview.size() > 0)
576 final AlignmentPanel ap = origview.get(0);
579 * Copy the ViewStyle of the selected panel to 'this one'.
580 * Don't change value of 'scaleProteinAsCdna' unless copying
583 ViewStyleI vs = selviews.get(0).getAlignViewport()
585 boolean fromSplitFrame = selviews.get(0)
586 .getAlignViewport().getCodingComplement() != null;
589 vs.setScaleProteinAsCdna(ap.getAlignViewport()
590 .getViewStyle().isScaleProteinAsCdna());
592 ap.getAlignViewport().setViewStyle(vs);
595 * Also rescale ViewStyle of SplitFrame complement if there is
596 * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
597 * the whole ViewStyle (allow cDNA protein to have different
600 AlignViewportI complement = ap.getAlignViewport()
601 .getCodingComplement();
602 if (complement != null && vs.isScaleProteinAsCdna())
604 AlignFrame af = Desktop.getAlignFrameFor(complement);
605 ((SplitFrame) af.getSplitViewContainer())
607 af.setMenusForViewport();
611 ap.setSelected(true);
612 ap.alignFrame.setMenusForViewport();
617 if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
618 .indexOf("devel") > -1
619 || Cache.getDefault("VERSION", "DEVELOPMENT")
620 .toLowerCase(Locale.ROOT).indexOf("test") > -1)
622 formatMenu.add(vsel);
624 addFocusListener(new FocusAdapter()
627 public void focusGained(FocusEvent e)
629 Jalview.setCurrentAlignFrame(AlignFrame.this);
636 * Change the filename and format for the alignment, and enable the 'reload'
637 * button functionality.
645 public void setFileName(String file, FileFormatI format)
648 setFileFormat(format);
649 reload.setEnabled(true);
655 * @param file from SwingJS; may contain bytes -- for reload
656 * @param protocol from SwingJS; may be RELATIVE_URL
659 public void setFile(String fileName, File file, DataSourceType protocol, FileFormatI format)
661 this.fileName = fileName;
662 this.fileObject = file;
663 this.protocol = protocol;
664 setFileFormat(format);
665 reload.setEnabled(true);
669 * JavaScript will have this, maybe others. More dependable than a file name
670 * and maintains a reference to the actual bytes loaded.
674 public void setFileObject(File file)
676 this.fileObject = file;
680 * Add a KeyListener with handlers for various KeyPressed and KeyReleased
683 void addKeyListener()
685 addKeyListener(new KeyAdapter()
688 public void keyPressed(KeyEvent evt)
690 if (viewport.cursorMode
691 && ((evt.getKeyCode() >= KeyEvent.VK_0
692 && evt.getKeyCode() <= KeyEvent.VK_9)
693 || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
694 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
695 && Character.isDigit(evt.getKeyChar()))
697 alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
700 switch (evt.getKeyCode())
703 case KeyEvent.VK_ESCAPE: // escape key
704 // alignPanel.deselectAllSequences();
705 alignPanel.deselectAllSequences();
709 case KeyEvent.VK_DOWN:
710 if (evt.isAltDown() || !viewport.cursorMode)
712 moveSelectedSequences(false);
714 if (viewport.cursorMode)
716 alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
721 if (evt.isAltDown() || !viewport.cursorMode)
723 moveSelectedSequences(true);
725 if (viewport.cursorMode)
727 alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
732 case KeyEvent.VK_LEFT:
733 if (evt.isAltDown() || !viewport.cursorMode)
735 slideSequences(false,
736 alignPanel.getSeqPanel().getKeyboardNo1());
740 alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
745 case KeyEvent.VK_RIGHT:
746 if (evt.isAltDown() || !viewport.cursorMode)
748 slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
752 alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
756 case KeyEvent.VK_SPACE:
757 if (viewport.cursorMode)
759 alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
760 || evt.isShiftDown() || evt.isAltDown());
764 // case KeyEvent.VK_A:
765 // if (viewport.cursorMode)
767 // alignPanel.seqPanel.insertNucAtCursor(false,"A");
768 // //System.out.println("A");
772 * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
773 * System.out.println("closing bracket"); } break;
775 case KeyEvent.VK_DELETE:
776 case KeyEvent.VK_BACK_SPACE:
777 if (!viewport.cursorMode)
779 cut_actionPerformed();
783 alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
784 || evt.isShiftDown() || evt.isAltDown());
790 if (viewport.cursorMode)
792 alignPanel.getSeqPanel().setCursorRow();
796 if (viewport.cursorMode && !evt.isControlDown())
798 alignPanel.getSeqPanel().setCursorColumn();
802 if (viewport.cursorMode)
804 alignPanel.getSeqPanel().setCursorPosition();
808 case KeyEvent.VK_ENTER:
809 case KeyEvent.VK_COMMA:
810 if (viewport.cursorMode)
812 alignPanel.getSeqPanel().setCursorRowAndColumn();
817 if (viewport.cursorMode)
819 alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
823 if (viewport.cursorMode)
825 alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
830 viewport.cursorMode = !viewport.cursorMode;
831 setStatus(MessageManager
832 .formatMessage("label.keyboard_editing_mode", new String[]
833 { (viewport.cursorMode ? "on" : "off") }));
834 if (viewport.cursorMode)
836 ViewportRanges ranges = viewport.getRanges();
837 alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
839 alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
842 alignPanel.getSeqPanel().seqCanvas.repaint();
848 Help.showHelpWindow();
849 } catch (Exception ex)
851 ex.printStackTrace();
856 boolean toggleSeqs = !evt.isControlDown();
857 boolean toggleCols = !evt.isShiftDown();
858 toggleHiddenRegions(toggleSeqs, toggleCols);
863 boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
864 boolean modifyExisting = true; // always modify, don't clear
865 // evt.isShiftDown();
866 boolean invertHighlighted = evt.isAltDown();
867 avc.markHighlightedColumns(invertHighlighted, modifyExisting,
871 case KeyEvent.VK_PAGE_UP:
872 viewport.getRanges().pageUp();
874 case KeyEvent.VK_PAGE_DOWN:
875 viewport.getRanges().pageDown();
881 public void keyReleased(KeyEvent evt)
883 switch (evt.getKeyCode())
885 case KeyEvent.VK_LEFT:
886 if (evt.isAltDown() || !viewport.cursorMode)
888 viewport.notifyAlignment();
892 case KeyEvent.VK_RIGHT:
893 if (evt.isAltDown() || !viewport.cursorMode)
895 viewport.notifyAlignment();
903 public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
905 ap.alignFrame = this;
906 avc = new jalview.controller.AlignViewController(this, viewport,
911 PaintRefresher.Register(ap, ap.av.getSequenceSetId());
913 int aSize = alignPanels.size();
915 tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
917 if (aSize == 1 && ap.av.getViewName() == null)
919 this.getContentPane().add(ap, BorderLayout.CENTER);
925 setInitialTabVisible();
928 expandViews.setEnabled(true);
929 gatherViews.setEnabled(true);
930 tabbedPane.addTab(ap.av.getViewName(), ap);
932 ap.setVisible(false);
937 if (ap.av.isPadGaps())
939 ap.av.getAlignment().padGaps();
941 if (Jalview.getInstance().getStartCalculations())
943 ap.av.updateConservation(ap);
944 ap.av.updateConsensus(ap);
945 ap.av.updateStrucConsensus(ap);
946 ap.av.initInformationWorker(ap);
951 public void setInitialTabVisible()
953 expandViews.setEnabled(true);
954 gatherViews.setEnabled(true);
955 tabbedPane.setVisible(true);
956 AlignmentPanel first = alignPanels.get(0);
957 tabbedPane.addTab(first.av.getViewName(), first);
958 this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
961 public AlignViewport getViewport()
967 public void servicesChanged(WSDiscovererI discoverer,
968 Collection<? extends ServiceWithParameters> services)
970 buildWebServicesMenu();
973 private WebServiceDiscovererI.ServicesChangeListener slivkaServiceChangeListener =
974 (discoverer, services) -> {
975 // run when slivka services change
976 var menu = AlignFrame.this.slivkaMenu;
977 menu.setServices(discoverer);
978 menu.setInProgress(discoverer.isRunning());
979 menu.setNoServices(services.isEmpty() && discoverer.isDone());
982 private WebServiceDiscovererI.ServicesChangeListener ebiServiceChangeListener =
983 (discoverer, services) -> {
984 // run when ebi services change
985 var menu = AlignFrame.this.ebiMenu;
986 menu.setServices(discoverer);
987 menu.setInProgress(discoverer.isRunning());
988 menu.setNoServices(services.isEmpty() && discoverer.isDone());
991 private WebServiceDiscovererI.ServicesChangeListener jpred4ServiceChangeListener =
992 (discoverer, services) -> {
993 // run when jpred4 services change
994 var menu = AlignFrame.this.jpred4Menu;
995 menu.setServices(discoverer);
996 menu.setInProgress(discoverer.isRunning());
997 menu.setNoServices(services.isEmpty() && discoverer.isDone());
1000 /* Set up intrinsic listeners for dynamically generated GUI bits. */
1001 private void addServiceListeners()
1003 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
1005 WebServiceDiscovererI discoverer = SlivkaWSDiscoverer.getInstance();
1006 discoverer.addServicesChangeListener(slivkaServiceChangeListener);
1008 if (Cache.getDefault("SHOW_EBI_SERVICES", true))
1010 JobDispatcherWSDiscoverer.getInstance().addServicesChangeListener(ebiServiceChangeListener);
1012 if (Cache.getDefault("SHOW_JPRED4_SERVICES", true))
1014 JPred4WSDiscoverer.getInstance().addServicesChangeListener(jpred4ServiceChangeListener);
1016 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
1018 WSDiscovererI discoverer = Jws2Discoverer.getInstance();
1019 discoverer.addServiceChangeListener(this);
1021 // legacy event listener for compatibility with jws1
1022 PropertyChangeListener legacyListener = (changeEvent) -> {
1023 buildWebServicesMenu();
1025 Desktop.getInstance().addJalviewPropertyChangeListener("services",legacyListener);
1027 addInternalFrameListener(new InternalFrameAdapter() {
1029 public void internalFrameClosed(InternalFrameEvent e) {
1030 System.out.println("deregistering discoverer listener");
1031 SlivkaWSDiscoverer.getInstance().removeServicesChangeListener(slivkaServiceChangeListener);
1032 JPred4WSDiscoverer.getInstance().removeServicesChangeListener(jpred4ServiceChangeListener);
1033 Jws2Discoverer.getInstance().removeServiceChangeListener(AlignFrame.this);
1034 Desktop.getInstance().removeJalviewPropertyChangeListener("services", legacyListener);
1035 closeMenuItem_actionPerformed(true);
1038 buildWebServicesMenu();
1042 * Configure menu items that vary according to whether the alignment is
1043 * nucleotide or protein
1045 public void setGUINucleotide()
1047 AlignmentI al = getViewport().getAlignment();
1048 boolean nucleotide = al.isNucleotide();
1050 loadVcf.setVisible(nucleotide);
1051 showTranslation.setVisible(nucleotide);
1052 showReverse.setVisible(nucleotide);
1053 showReverseComplement.setVisible(nucleotide);
1054 conservationMenuItem.setEnabled(!nucleotide);
1056 .setEnabled(!nucleotide && conservationMenuItem.isSelected());
1057 showGroupConservation.setEnabled(!nucleotide);
1059 showComplementMenuItem
1060 .setText(nucleotide ? MessageManager.getString("label.protein")
1061 : MessageManager.getString("label.nucleotide"));
1065 * set up menus for the current viewport. This may be called after any
1066 * operation that affects the data in the current view (selection changed,
1067 * etc) to update the menus to reflect the new state.
1070 public void setMenusForViewport()
1072 setMenusFromViewport(viewport);
1076 * Need to call this method when tabs are selected for multiple views, or when
1077 * loading from Jalview2XML.java
1082 public void setMenusFromViewport(AlignViewport av)
1084 padGapsMenuitem.setSelected(av.isPadGaps());
1085 colourTextMenuItem.setSelected(av.isShowColourText());
1086 abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
1087 modifyPID.setEnabled(abovePIDThreshold.isSelected());
1088 conservationMenuItem.setSelected(av.getConservationSelected());
1089 modifyConservation.setEnabled(conservationMenuItem.isSelected());
1090 seqLimits.setSelected(av.getShowJVSuffix());
1091 idRightAlign.setSelected(av.isRightAlignIds());
1092 centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
1093 renderGapsMenuItem.setSelected(av.isRenderGaps());
1094 wrapMenuItem.setSelected(av.getWrapAlignment());
1095 scaleAbove.setVisible(av.getWrapAlignment());
1096 scaleLeft.setVisible(av.getWrapAlignment());
1097 scaleRight.setVisible(av.getWrapAlignment());
1098 annotationPanelMenuItem.setState(av.isShowAnnotation());
1099 // Show/hide annotations only enabled if annotation panel is shown
1100 syncAnnotationMenuItems(av.isShowAnnotation());
1101 viewBoxesMenuItem.setSelected(av.getShowBoxes());
1102 viewTextMenuItem.setSelected(av.getShowText());
1103 showNonconservedMenuItem.setSelected(av.getShowUnconserved());
1104 showGroupConsensus.setSelected(av.isShowGroupConsensus());
1105 showGroupConservation.setSelected(av.isShowGroupConservation());
1106 showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
1107 showSequenceLogo.setSelected(av.isShowSequenceLogo());
1108 normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
1109 showInformationHistogram.setSelected(av.isShowInformationHistogram());
1110 showHMMSequenceLogo.setSelected(av.isShowHMMSequenceLogo());
1111 normaliseHMMSequenceLogo.setSelected(av.isNormaliseHMMSequenceLogo());
1113 ColourMenuHelper.setColourSelected(colourMenu,
1114 av.getGlobalColourScheme());
1116 showSeqFeatures.setSelected(av.isShowSequenceFeatures());
1117 hiddenMarkers.setState(av.getShowHiddenMarkers());
1118 applyToAllGroups.setState(av.getColourAppliesToAllGroups());
1119 showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
1120 showDbRefsMenuitem.setSelected(av.isShowDBRefs());
1122 .setSelected(av.getAutoCalculateConsensusAndConservation());
1123 sortByTree.setSelected(av.sortByTree);
1124 listenToViewSelections.setSelected(av.followSelection);
1126 showProducts.setEnabled(canShowProducts());
1127 setGroovyEnabled(Desktop.getGroovyConsole() != null);
1129 updateEditMenuBar();
1133 * Set the enabled state of the 'Run Groovy' option in the Calculate menu
1137 public void setGroovyEnabled(boolean b)
1139 runGroovy.setEnabled(b);
1142 private IProgressIndicator progressBar;
1147 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1150 public void setProgressBar(String message, long id)
1152 progressBar.setProgressBar(message, id);
1156 public void addProgressBar(long id, String message)
1158 progressBar.addProgressBar(id, message);
1162 public void removeProgressBar(long id)
1164 progressBar.removeProgressBar(id);
1168 public void registerHandler(final long id,
1169 final IProgressIndicatorHandler handler)
1171 progressBar.registerHandler(id, handler);
1176 * @return true if any progress bars are still active
1179 public boolean operationInProgress()
1181 return progressBar.operationInProgress();
1185 * Sets the text of the status bar. Note that setting a null or empty value
1186 * will cause the status bar to be hidden, with possibly undesirable flicker
1187 * of the screen layout.
1190 public void setStatus(String text)
1192 statusBar.setText(text == null || text.isEmpty() ? " " : text);
1196 * Added so Castor Mapping file can obtain Jalview Version
1198 public String getVersion()
1200 return Cache.getProperty("VERSION");
1203 public FeatureRenderer getFeatureRenderer()
1205 return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1209 public void fetchSequence_actionPerformed()
1211 new SequenceFetcher(this);
1215 public void addFromFile_actionPerformed(ActionEvent e)
1217 Desktop.getInstance().inputLocalFileMenuItem_actionPerformed(viewport);
1221 public void hmmBuild_actionPerformed(boolean withDefaults)
1223 if (!alignmentIsSufficient(1))
1229 * get default parameters, and optionally show a dialog
1230 * to allow them to be modified
1232 ParamDatastoreI store = HMMERParamStore.forBuild(viewport);
1233 List<ArgumentI> args = store.getServiceParameters();
1237 WsParamSetI set = new HMMERPreset();
1238 WsJobParameters params = new WsJobParameters(store, set, args);
1239 params.showRunDialog().thenAccept((startJob) -> {
1242 var args2 = params.getJobParams();
1243 new Thread(new HMMBuild(this, args2)).start();
1249 new Thread(new HMMBuild(this, args)).start();
1254 public void hmmAlign_actionPerformed(boolean withDefaults)
1256 if (!(checkForHMM() && alignmentIsSufficient(2)))
1262 * get default parameters, and optionally show a dialog
1263 * to allow them to be modified
1265 ParamDatastoreI store = HMMERParamStore.forAlign(viewport);
1266 List<ArgumentI> args = store.getServiceParameters();
1270 WsParamSetI set = new HMMERPreset();
1271 WsJobParameters params = new WsJobParameters(store, set, args);
1272 params.showRunDialog().thenAccept((startJob) -> {
1275 var args2 = params.getJobParams();
1276 new Thread(new HMMAlign(this, args2)).start();
1282 new Thread(new HMMAlign(this, args)).start();
1287 public void hmmSearch_actionPerformed(boolean withDefaults)
1295 * get default parameters, and (if requested) show
1296 * dialog to allow modification
1298 ParamDatastoreI store = HMMERParamStore.forSearch(viewport);
1299 List<ArgumentI> args = store.getServiceParameters();
1303 WsParamSetI set = new HMMERPreset();
1304 WsJobParameters params = new WsJobParameters(store, set, args);
1305 params.showRunDialog().thenAccept((startJob) -> {
1308 var args2 = params.getJobParams();
1309 new Thread(new HMMSearch(this, args2)).start();
1310 alignPanel.repaint();
1316 new Thread(new HMMSearch(this, args)).start();
1317 alignPanel.repaint();
1322 public void jackhmmer_actionPerformed(boolean withDefaults)
1326 * get default parameters, and (if requested) show
1327 * dialog to allow modification
1330 ParamDatastoreI store = HMMERParamStore.forJackhmmer(viewport);
1331 List<ArgumentI> args = store.getServiceParameters();
1335 WsParamSetI set = new HMMERPreset();
1336 WsJobParameters params = new WsJobParameters(store, set, args);
1337 params.showRunDialog().thenAccept((startJob) -> {
1340 var args2 = params.getJobParams();
1341 new Thread(new JackHMMER(this, args2)).start();
1342 alignPanel.repaint();
1348 new Thread(new JackHMMER(this, args)).start();
1349 alignPanel.repaint();
1354 * Checks if the alignment has at least one hidden Markov model, if not shows
1355 * a dialog advising to run hmmbuild or load an HMM profile
1359 private boolean checkForHMM()
1361 if (viewport.getAlignment().getHmmSequences().isEmpty())
1363 JOptionPane.showMessageDialog(this,
1364 MessageManager.getString("warn.no_hmm"));
1371 protected void filterByEValue_actionPerformed()
1373 viewport.filterByEvalue(inputDouble("Enter E-Value Cutoff"));
1377 protected void filterByScore_actionPerformed()
1379 viewport.filterByScore(inputDouble("Enter Bit Score Threshold"));
1382 private double inputDouble(String message)
1386 while (d == null || d <= 0)
1388 str = JOptionPane.showInputDialog(this.alignPanel, message);
1391 d = Double.valueOf(str);
1392 } catch (NumberFormatException e)
1400 * Checks if the alignment contains the required number of sequences.
1405 public boolean alignmentIsSufficient(int required)
1407 if (getViewport().getSequenceSelection().length < required)
1409 JOptionPane.showMessageDialog(this,
1410 MessageManager.getString("label.not_enough_sequences"));
1417 * Opens a file browser and adds the selected file, if in Fasta, Stockholm or
1418 * Pfam format, to the list held under preference key "HMMSEARCH_DBS" (as a
1419 * comma-separated list)
1422 public void addDatabase_actionPerformed() throws IOException
1424 if (Cache.getProperty(Preferences.HMMSEARCH_DBS) == null)
1426 Cache.setProperty(Preferences.HMMSEARCH_DBS, "");
1429 String path = openFileChooser(false);
1430 if (path != null && new File(path).exists())
1432 IdentifyFile identifier = new IdentifyFile();
1433 FileFormatI format = identifier.identify(path, DataSourceType.FILE);
1434 if (format == FileFormat.Fasta || format == FileFormat.Stockholm
1435 || format == FileFormat.Pfam)
1437 String currentDbPaths = Cache
1438 .getProperty(Preferences.HMMSEARCH_DBS);
1439 currentDbPaths += Preferences.COMMA + path;
1440 Cache.setProperty(Preferences.HMMSEARCH_DBS, currentDbPaths);
1444 JOptionPane.showMessageDialog(this,
1445 MessageManager.getString("warn.invalid_format"));
1451 * Opens a file chooser, optionally restricted to selecting folders
1452 * (directories) only. Answers the path to the selected file or folder, or
1453 * null if none is chosen.
1458 protected String openFileChooser(boolean forFolder)
1460 // TODO duplicates GPreferences method - relocate to JalviewFileChooser?
1461 String choice = null;
1462 JFileChooser chooser = new JFileChooser();
1465 chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1467 chooser.setDialogTitle(
1468 MessageManager.getString("label.open_local_file"));
1469 chooser.setToolTipText(MessageManager.getString("action.open"));
1471 int value = chooser.showOpenDialog(this);
1473 if (value == JFileChooser.APPROVE_OPTION)
1475 choice = chooser.getSelectedFile().getPath();
1481 public void reload_actionPerformed(ActionEvent e)
1483 if (fileName == null && fileObject == null)
1487 // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1488 // originating file's format
1489 // TODO: work out how to recover feature settings for correct view(s) when
1490 // file is reloaded.
1491 if (FileFormat.Jalview.equals(currentFileFormat))
1493 JInternalFrame[] frames = Desktop.getDesktopPane().getAllFrames();
1494 for (int i = 0; i < frames.length; i++)
1496 if (frames[i] instanceof AlignFrame && frames[i] != this
1497 && ((AlignFrame) frames[i]).fileName != null
1498 && ((AlignFrame) frames[i]).fileName.equals(fileName))
1502 frames[i].setSelected(true);
1503 Desktop.getInstance().closeAssociatedWindows();
1504 } catch (java.beans.PropertyVetoException ex)
1510 Desktop.getInstance().closeAssociatedWindows();
1512 FileLoader loader = new FileLoader();
1513 loader.LoadFile(viewport, (fileObject == null ? fileName : fileObject), protocol, currentFileFormat);
1517 Rectangle bounds = this.getBounds();
1519 FileLoader loader = new FileLoader();
1521 AlignFrame newframe = null;
1523 if (fileObject == null)
1525 newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1530 newframe = loader.LoadFileWaitTillLoaded(fileObject,
1531 DataSourceType.FILE, currentFileFormat);
1534 newframe.setBounds(bounds);
1535 if (featureSettings != null && featureSettings.isShowing())
1537 final Rectangle fspos = featureSettings.frame.getBounds();
1538 // TODO: need a 'show feature settings' function that takes bounds -
1539 // need to refactor Desktop.addFrame
1540 newframe.featureSettings_actionPerformed(null);
1541 final FeatureSettings nfs = newframe.featureSettings;
1542 SwingUtilities.invokeLater(new Runnable()
1547 nfs.frame.setBounds(fspos);
1550 this.featureSettings.close();
1551 this.featureSettings = null;
1553 this.closeMenuItem_actionPerformed(true);
1558 public void addFromText_actionPerformed(ActionEvent e)
1560 Desktop.getInstance()
1561 .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1565 public void addFromURL_actionPerformed(ActionEvent e)
1567 Desktop.getInstance().inputURLMenuItem_actionPerformed(viewport);
1571 public void save_actionPerformed(ActionEvent e)
1573 if (fileName == null || (currentFileFormat == null)
1574 || HttpUtils.startsWithHttpOrHttps(fileName))
1576 saveAs_actionPerformed();
1580 saveAlignment(fileName, currentFileFormat);
1585 * Saves the alignment to a file with a name chosen by the user, if necessary
1586 * warning if a file would be overwritten
1589 public void saveAs_actionPerformed()
1591 String format = currentFileFormat == null ? null
1592 : currentFileFormat.getName();
1593 JalviewFileChooser chooser = JalviewFileChooser
1594 .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1596 chooser.setFileView(new JalviewFileView());
1597 chooser.setDialogTitle(
1598 MessageManager.getString("label.save_alignment_to_file"));
1599 chooser.setToolTipText(MessageManager.getString("action.save"));
1601 int value = chooser.showSaveDialog(this);
1603 if (value != JalviewFileChooser.APPROVE_OPTION)
1607 currentFileFormat = chooser.getSelectedFormat();
1608 // todo is this (2005) test now obsolete - value is never null?
1609 while (currentFileFormat == null)
1611 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
1613 .getString("label.select_file_format_before_saving"),
1614 MessageManager.getString("label.file_format_not_specified"),
1615 JvOptionPane.WARNING_MESSAGE);
1616 currentFileFormat = chooser.getSelectedFormat();
1617 value = chooser.showSaveDialog(this);
1618 if (value != JalviewFileChooser.APPROVE_OPTION)
1624 fileName = chooser.getSelectedFile().getPath();
1626 Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1627 Cache.setProperty("LAST_DIRECTORY", fileName);
1628 saveAlignment(fileName, currentFileFormat);
1631 boolean lastSaveSuccessful = false;
1633 FileFormatI lastFormatSaved;
1635 String lastFilenameSaved;
1638 * Raise a dialog or status message for the last call to saveAlignment.
1640 * @return true if last call to saveAlignment(file, format) was successful.
1642 public boolean isSaveAlignmentSuccessful()
1645 if (!lastSaveSuccessful)
1647 if (!Platform.isHeadless())
1649 JvOptionPane.showInternalMessageDialog(this, MessageManager
1650 .formatMessage("label.couldnt_save_file", new Object[]
1651 { lastFilenameSaved }),
1652 MessageManager.getString("label.error_saving_file"),
1653 JvOptionPane.WARNING_MESSAGE);
1657 Console.error(MessageManager
1658 .formatMessage("label.couldnt_save_file", new Object[]
1659 { lastFilenameSaved }));
1665 setStatus(MessageManager.formatMessage(
1666 "label.successfully_saved_to_file_in_format", new Object[]
1667 { lastFilenameSaved, lastFormatSaved }));
1670 return lastSaveSuccessful;
1674 * Saves the alignment to the specified file path, in the specified format,
1675 * which may be an alignment format, or Jalview project format. If the
1676 * alignment has hidden regions, or the format is one capable of including
1677 * non-sequence data (features, annotations, groups), then the user may be
1678 * prompted to specify what to include in the output.
1683 public void saveAlignment(String file, FileFormatI format)
1685 lastSaveSuccessful = true;
1686 lastFilenameSaved = file;
1687 lastFormatSaved = format;
1689 if (FileFormat.Jalview.equals(format))
1691 String shortName = title;
1692 if (shortName.indexOf(File.separatorChar) > -1)
1694 shortName = shortName
1695 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1697 lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1700 statusBar.setText(MessageManager.formatMessage(
1701 "label.successfully_saved_to_file_in_format", new Object[]
1702 { fileName, format }));
1707 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1708 Runnable cancelAction = new Runnable()
1713 lastSaveSuccessful = false;
1716 Runnable outputAction = new Runnable()
1721 // todo defer this to inside formatSequences (or later)
1722 AlignmentExportData exportData = viewport
1723 .getAlignExportData(options);
1724 String output = new FormatAdapter(alignPanel, options)
1725 .formatSequences(format, exportData.getAlignment(),
1726 exportData.getOmitHidden(),
1727 exportData.getStartEndPostions(),
1728 viewport.getAlignment().getHiddenColumns());
1731 lastSaveSuccessful = false;
1735 // create backupfiles object and get new temp filename destination
1736 boolean doBackup = BackupFiles.getEnabled();
1737 BackupFiles backupfiles = null;
1741 "ALIGNFRAME making backupfiles object for " + file);
1742 backupfiles = new BackupFiles(file);
1746 String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1748 Console.trace("ALIGNFRAME setting PrintWriter");
1749 PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1751 if (backupfiles != null)
1753 Console.trace("ALIGNFRAME about to write to temp file "
1754 + backupfiles.getTempFilePath());
1758 Console.trace("ALIGNFRAME about to close file");
1760 Console.trace("ALIGNFRAME closed file");
1761 AlignFrame.this.setTitle(file);
1762 statusBar.setText(MessageManager.formatMessage(
1763 "label.successfully_saved_to_file_in_format",
1765 { fileName, format.getName() }));
1766 lastSaveSuccessful = true;
1767 } catch (IOException e)
1769 lastSaveSuccessful = false;
1771 "ALIGNFRAME Something happened writing the temp file");
1772 Console.error(e.getMessage());
1773 Console.debug(Cache.getStackTraceString(e));
1774 } catch (Exception ex)
1776 lastSaveSuccessful = false;
1778 "ALIGNFRAME Something unexpected happened writing the temp file");
1779 Console.error(ex.getMessage());
1780 Console.debug(Cache.getStackTraceString(ex));
1785 backupfiles.setWriteSuccess(lastSaveSuccessful);
1786 Console.debug("ALIGNFRAME writing temp file was "
1787 + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1788 // do the backup file roll and rename the temp file to actual file
1790 "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1791 lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1793 "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1794 + (lastSaveSuccessful ? "" : "un")
1802 * show dialog with export options if applicable; else just do it
1804 if (AlignExportOptions.isNeeded(viewport, format))
1806 AlignExportOptions choices = new AlignExportOptions(
1807 alignPanel.getAlignViewport(), format, options);
1808 choices.setResponseAction(0, outputAction);
1809 choices.setResponseAction(1, cancelAction);
1810 choices.showDialog();
1819 * Outputs the alignment to textbox in the requested format, if necessary
1820 * first prompting the user for whether to include hidden regions or
1823 * @param fileFormatName
1826 protected void outputText_actionPerformed(String fileFormatName)
1828 FileFormatI fileFormat = FileFormats.getInstance()
1829 .forName(fileFormatName);
1830 AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1831 Runnable outputAction = new Runnable()
1836 // todo defer this to inside formatSequences (or later)
1837 AlignmentExportData exportData = viewport
1838 .getAlignExportData(options);
1839 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1840 cap.setForInput(null);
1843 FileFormatI format = fileFormat;
1844 cap.setText(new FormatAdapter(alignPanel, options)
1845 .formatSequences(format, exportData.getAlignment(),
1846 exportData.getOmitHidden(),
1847 exportData.getStartEndPostions(),
1848 viewport.getAlignment().getHiddenColumns()));
1849 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1850 "label.alignment_output_command", new Object[]
1851 { fileFormat.getName() }), 600, 500);
1852 } catch (OutOfMemoryError oom)
1854 new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1862 * show dialog with export options if applicable; else just do it
1864 if (AlignExportOptions.isNeeded(viewport, fileFormat))
1866 AlignExportOptions choices = new AlignExportOptions(
1867 alignPanel.getAlignViewport(), fileFormat, options);
1868 choices.setResponseAction(0, outputAction);
1869 choices.showDialog();
1884 protected void htmlMenuItem_actionPerformed(ActionEvent e)
1886 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1887 htmlSVG.exportHTML(null);
1891 public void bioJSMenuItem_actionPerformed(ActionEvent e)
1893 BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1894 bjs.exportHTML(null);
1898 public void createImageMap(File file, String image)
1900 alignPanel.makePNGImageMap(file, image);
1904 * Creates a PNG image of the alignment and writes it to the given file. If
1905 * the file is null, the user is prompted to choose a file.
1910 public void createPNG(File f)
1912 alignPanel.makeAlignmentImage(TYPE.PNG, f);
1916 * Creates an EPS image of the alignment and writes it to the given file. If
1917 * the file is null, the user is prompted to choose a file.
1922 public void createEPS(File f)
1924 alignPanel.makeAlignmentImage(TYPE.EPS, f);
1928 * Creates an SVG image of the alignment and writes it to the given file. If
1929 * the file is null, the user is prompted to choose a file.
1934 public void createSVG(File f)
1936 alignPanel.makeAlignmentImage(TYPE.SVG, f);
1940 public void pageSetup_actionPerformed(ActionEvent e)
1942 PrinterJob printJob = PrinterJob.getPrinterJob();
1943 PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1953 public void printMenuItem_actionPerformed(ActionEvent e)
1955 // Putting in a thread avoids Swing painting problems
1956 PrintThread thread = new PrintThread(alignPanel);
1961 public void exportFeatures_actionPerformed(ActionEvent e)
1963 new AnnotationExporter(alignPanel).exportFeatures();
1967 public void exportAnnotations_actionPerformed(ActionEvent e)
1969 new AnnotationExporter(alignPanel).exportAnnotations();
1973 public void associatedData_actionPerformed(ActionEvent e)
1974 throws IOException, InterruptedException
1976 final JalviewFileChooser chooser = new JalviewFileChooser(
1977 Cache.getProperty("LAST_DIRECTORY"));
1978 chooser.setFileView(new JalviewFileView());
1979 String tooltip = MessageManager
1980 .getString("label.load_jalview_annotations");
1981 chooser.setDialogTitle(tooltip);
1982 chooser.setToolTipText(tooltip);
1983 chooser.setResponseHandler(0, new Runnable()
1988 String choice = chooser.getSelectedFile().getPath();
1989 Cache.setProperty("LAST_DIRECTORY", choice);
1990 loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1994 chooser.showOpenDialog(this);
1998 * Close the current view or all views in the alignment frame. If the frame
1999 * only contains one view then the alignment will be removed from memory.
2001 * @param closeAllTabs
2004 public void closeMenuItem_actionPerformed(boolean closeAllTabs)
2006 if (alignPanels != null && alignPanels.size() < 2)
2008 closeAllTabs = true;
2013 if (alignPanels != null)
2017 if (this.isClosed())
2019 // really close all the windows - otherwise wait till
2020 // setClosed(true) is called
2021 for (int i = 0; i < alignPanels.size(); i++)
2023 AlignmentPanel ap = alignPanels.get(i);
2030 closeView(alignPanel);
2035 if (featureSettings != null && featureSettings.isOpen())
2037 featureSettings.close();
2038 featureSettings = null;
2041 * this will raise an INTERNAL_FRAME_CLOSED event and this method will
2042 * be called recursively, with the frame now in 'closed' state
2044 this.setClosed(true);
2046 } catch (Exception ex)
2048 ex.printStackTrace();
2053 * Close the specified panel and close up tabs appropriately.
2055 * @param panelToClose
2057 public void closeView(AlignmentPanel panelToClose)
2059 int index = tabbedPane.getSelectedIndex();
2060 int closedindex = tabbedPane.indexOfComponent(panelToClose);
2061 alignPanels.remove(panelToClose);
2062 panelToClose.closePanel();
2063 panelToClose = null;
2065 tabbedPane.removeTabAt(closedindex);
2066 tabbedPane.validate();
2068 if (index > closedindex || index == tabbedPane.getTabCount())
2070 // modify currently selected tab index if necessary.
2074 this.tabSelectionChanged(index);
2080 void updateEditMenuBar()
2083 if (viewport.getHistoryList().size() > 0)
2085 undoMenuItem.setEnabled(true);
2086 CommandI command = viewport.getHistoryList().peek();
2087 undoMenuItem.setText(MessageManager
2088 .formatMessage("label.undo_command", new Object[]
2089 { command.getDescription() }));
2093 undoMenuItem.setEnabled(false);
2094 undoMenuItem.setText(MessageManager.getString("action.undo"));
2097 if (viewport.getRedoList().size() > 0)
2099 redoMenuItem.setEnabled(true);
2101 CommandI command = viewport.getRedoList().peek();
2102 redoMenuItem.setText(MessageManager
2103 .formatMessage("label.redo_command", new Object[]
2104 { command.getDescription() }));
2108 redoMenuItem.setEnabled(false);
2109 redoMenuItem.setText(MessageManager.getString("action.redo"));
2114 public void addHistoryItem(CommandI command)
2116 if (command.getSize() > 0)
2118 viewport.addToHistoryList(command);
2119 viewport.clearRedoList();
2120 updateEditMenuBar();
2121 viewport.updateHiddenColumns();
2122 // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
2123 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2124 // viewport.getColumnSelection()
2125 // .getHiddenColumns().size() > 0);
2131 * @return alignment objects for all views
2133 AlignmentI[] getViewAlignments()
2135 if (alignPanels != null)
2137 AlignmentI[] als = new AlignmentI[alignPanels.size()];
2139 for (AlignmentPanel ap : alignPanels)
2141 als[i++] = ap.av.getAlignment();
2145 if (viewport != null)
2147 return new AlignmentI[] { viewport.getAlignment() };
2159 protected void undoMenuItem_actionPerformed(ActionEvent e)
2161 if (viewport.getHistoryList().isEmpty())
2165 CommandI command = viewport.getHistoryList().pop();
2166 viewport.addToRedoList(command);
2167 command.undoCommand(getViewAlignments());
2169 AlignmentViewport originalSource = getOriginatingSource(command);
2170 updateEditMenuBar();
2172 if (originalSource != null)
2174 if (originalSource != viewport)
2177 "Implementation worry: mismatch of viewport origin for undo");
2179 originalSource.updateHiddenColumns();
2180 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2182 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2183 // viewport.getColumnSelection()
2184 // .getHiddenColumns().size() > 0);
2185 originalSource.notifyAlignment();
2196 protected void redoMenuItem_actionPerformed(ActionEvent e)
2198 if (viewport.getRedoList().size() < 1)
2203 CommandI command = viewport.getRedoList().pop();
2204 viewport.addToHistoryList(command);
2205 command.doCommand(getViewAlignments());
2207 AlignmentViewport originalSource = getOriginatingSource(command);
2208 updateEditMenuBar();
2210 if (originalSource != null)
2213 if (originalSource != viewport)
2216 "Implementation worry: mismatch of viewport origin for redo");
2218 originalSource.updateHiddenColumns();
2219 // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
2221 // && viewport.getColumnSelection().getHiddenColumns() != null &&
2222 // viewport.getColumnSelection()
2223 // .getHiddenColumns().size() > 0);
2224 originalSource.notifyAlignment();
2228 AlignmentViewport getOriginatingSource(CommandI command)
2230 AlignmentViewport originalSource = null;
2231 // For sequence removal and addition, we need to fire
2232 // the property change event FROM the viewport where the
2233 // original alignment was altered
2234 AlignmentI al = null;
2235 if (command instanceof EditCommand)
2237 EditCommand editCommand = (EditCommand) command;
2238 al = editCommand.getAlignment();
2239 List<Component> comps = PaintRefresher.components
2240 .get(viewport.getSequenceSetId());
2242 for (Component comp : comps)
2244 if (comp instanceof AlignmentPanel)
2246 if (al == ((AlignmentPanel) comp).av.getAlignment())
2248 originalSource = ((AlignmentPanel) comp).av;
2255 if (originalSource == null)
2257 // The original view is closed, we must validate
2258 // the current view against the closed view first
2261 PaintRefresher.validateSequences(al, viewport.getAlignment());
2264 originalSource = viewport;
2267 return originalSource;
2271 * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
2272 * or the sequence under cursor in keyboard mode
2277 public void moveSelectedSequences(boolean up)
2279 SequenceGroup sg = viewport.getSelectionGroup();
2283 if (viewport.cursorMode)
2285 sg = new SequenceGroup();
2286 sg.addSequence(viewport.getAlignment().getSequenceAt(
2287 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
2295 if (sg.getSize() < 1)
2300 // TODO: JAL-3733 - add an event to the undo buffer for this !
2302 viewport.getAlignment().moveSelectedSequencesByOne(sg,
2303 viewport.getHiddenRepSequences(), up);
2304 alignPanel.paintAlignment(true, false);
2307 synchronized void slideSequences(boolean right, int size)
2309 List<SequenceI> sg = new ArrayList<>();
2310 if (viewport.cursorMode)
2312 sg.add(viewport.getAlignment()
2313 .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
2315 else if (viewport.getSelectionGroup() != null
2316 && viewport.getSelectionGroup().getSize() != viewport
2317 .getAlignment().getHeight())
2319 sg = viewport.getSelectionGroup()
2320 .getSequences(viewport.getHiddenRepSequences());
2328 List<SequenceI> invertGroup = new ArrayList<>();
2330 for (SequenceI seq : viewport.getAlignment().getSequences())
2332 if (!sg.contains(seq))
2334 invertGroup.add(seq);
2338 SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
2340 SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
2341 for (int i = 0; i < invertGroup.size(); i++)
2343 seqs2[i] = invertGroup.get(i);
2346 SlideSequencesCommand ssc;
2349 ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
2350 viewport.getGapCharacter());
2354 ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
2355 viewport.getGapCharacter());
2358 int groupAdjustment = 0;
2359 if (ssc.getGapsInsertedBegin() && right)
2361 if (viewport.cursorMode)
2363 alignPanel.getSeqPanel().moveCursor(size, 0);
2367 groupAdjustment = size;
2370 else if (!ssc.getGapsInsertedBegin() && !right)
2372 if (viewport.cursorMode)
2374 alignPanel.getSeqPanel().moveCursor(-size, 0);
2378 groupAdjustment = -size;
2382 if (groupAdjustment != 0)
2384 viewport.getSelectionGroup().setStartRes(
2385 viewport.getSelectionGroup().getStartRes() + groupAdjustment);
2386 viewport.getSelectionGroup().setEndRes(
2387 viewport.getSelectionGroup().getEndRes() + groupAdjustment);
2391 * just extend the last slide command if compatible; but not if in
2392 * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
2394 boolean appendHistoryItem = false;
2395 Deque<CommandI> historyList = viewport.getHistoryList();
2396 boolean inSplitFrame = getSplitViewContainer() != null;
2397 if (!inSplitFrame && historyList != null && historyList.size() > 0
2398 && historyList.peek() instanceof SlideSequencesCommand)
2400 appendHistoryItem = ssc.appendSlideCommand(
2401 (SlideSequencesCommand) historyList.peek());
2404 if (!appendHistoryItem)
2406 addHistoryItem(ssc);
2419 protected void copy_actionPerformed()
2421 if (viewport.getSelectionGroup() == null)
2425 // TODO: preserve the ordering of displayed alignment annotation in any
2426 // internal paste (particularly sequence associated annotation)
2427 SequenceI[] seqs = viewport.getSelectionAsNewSequence();
2428 String[] omitHidden = null;
2430 if (viewport.hasHiddenColumns())
2432 omitHidden = viewport.getViewAsString(true);
2435 String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2436 seqs, omitHidden, null);
2438 StringSelection ss = new StringSelection(output);
2440 Desktop d = Desktop.getInstance();
2443 d.internalCopy = true;
2444 // Its really worth setting the clipboard contents
2445 // to empty before setting the large StringSelection!!
2446 Toolkit.getDefaultToolkit().getSystemClipboard()
2447 .setContents(new StringSelection(""), null);
2449 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2451 } catch (OutOfMemoryError er)
2453 new OOMWarning("copying region", er);
2457 HiddenColumns hiddenColumns = null;
2458 if (viewport.hasHiddenColumns())
2460 int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2461 int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2463 // create new HiddenColumns object with copy of hidden regions
2464 // between startRes and endRes, offset by startRes
2465 hiddenColumns = new HiddenColumns(
2466 viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2467 hiddenCutoff, hiddenOffset);
2470 d.jalviewClipboard = new Object[] { seqs,
2471 viewport.getAlignment().getDataset(), hiddenColumns };
2472 setStatus(MessageManager.formatMessage(
2473 "label.copied_sequences_to_clipboard", new Object[]
2474 { Integer.valueOf(seqs.length).toString() }));
2482 * @throws InterruptedException
2483 * @throws IOException
2486 protected void pasteNew_actionPerformed(ActionEvent e)
2487 throws IOException, InterruptedException
2497 * @throws InterruptedException
2498 * @throws IOException
2501 protected void pasteThis_actionPerformed(ActionEvent e)
2502 throws IOException, InterruptedException
2508 * Paste contents of Jalview clipboard
2510 * @param newAlignment
2511 * true to paste to a new alignment, otherwise add to this.
2512 * @throws InterruptedException
2513 * @throws IOException
2515 void paste(boolean newAlignment) throws IOException, InterruptedException
2517 boolean externalPaste = true;
2520 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2521 Transferable contents = c.getContents(this);
2523 if (contents == null)
2532 str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2533 if (str.length() < 1)
2538 format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2540 } catch (OutOfMemoryError er)
2542 new OOMWarning("Out of memory pasting sequences!!", er);
2546 SequenceI[] sequences;
2547 boolean annotationAdded = false;
2548 AlignmentI alignment = null;
2550 Desktop d = Desktop.getInstance();
2552 if (d.jalviewClipboard != null)
2554 // The clipboard was filled from within Jalview, we must use the
2556 // And dataset from the copied alignment
2557 SequenceI[] newseq = (SequenceI[]) d.jalviewClipboard[0];
2558 // be doubly sure that we create *new* sequence objects.
2559 sequences = new SequenceI[newseq.length];
2560 for (int i = 0; i < newseq.length; i++)
2562 sequences[i] = new Sequence(newseq[i]);
2564 alignment = new Alignment(sequences);
2565 externalPaste = false;
2569 // parse the clipboard as an alignment.
2570 alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2572 sequences = alignment.getSequencesArray();
2576 ArrayList<Integer> newGraphGroups = new ArrayList<>();
2582 if (d.jalviewClipboard != null)
2584 // dataset is inherited
2585 alignment.setDataset((Alignment) d.jalviewClipboard[1]);
2589 // new dataset is constructed
2590 alignment.setDataset(null);
2592 alwidth = alignment.getWidth() + 1;
2596 AlignmentI pastedal = alignment; // preserve pasted alignment object
2597 // Add pasted sequences and dataset into existing alignment.
2598 alignment = viewport.getAlignment();
2599 alwidth = alignment.getWidth() + 1;
2600 // decide if we need to import sequences from an existing dataset
2601 boolean importDs = d.jalviewClipboard != null
2602 && d.jalviewClipboard[1] != alignment.getDataset();
2603 // importDs==true instructs us to copy over new dataset sequences from
2604 // an existing alignment
2605 Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2607 // minimum dataset set
2609 for (int i = 0; i < sequences.length; i++)
2613 newDs.addElement(null);
2615 SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2617 if (importDs && ds != null)
2619 if (!newDs.contains(ds))
2621 newDs.setElementAt(ds, i);
2622 ds = new Sequence(ds);
2623 // update with new dataset sequence
2624 sequences[i].setDatasetSequence(ds);
2628 ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2633 // copy and derive new dataset sequence
2634 sequences[i] = sequences[i].deriveSequence();
2635 alignment.getDataset()
2636 .addSequence(sequences[i].getDatasetSequence());
2637 // TODO: avoid creation of duplicate dataset sequences with a
2638 // 'contains' method using SequenceI.equals()/SequenceI.contains()
2640 alignment.addSequence(sequences[i]); // merges dataset
2644 newDs.clear(); // tidy up
2646 if (alignment.getAlignmentAnnotation() != null)
2648 for (AlignmentAnnotation alan : alignment
2649 .getAlignmentAnnotation())
2651 if (alan.graphGroup > fgroup)
2653 fgroup = alan.graphGroup;
2657 if (pastedal.getAlignmentAnnotation() != null)
2659 // Add any annotation attached to alignment.
2660 AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2661 for (int i = 0; i < alann.length; i++)
2663 annotationAdded = true;
2664 if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2666 AlignmentAnnotation newann = new AlignmentAnnotation(
2668 if (newann.graphGroup > -1)
2670 if (newGraphGroups.size() <= newann.graphGroup
2671 || newGraphGroups.get(newann.graphGroup) == null)
2673 for (int q = newGraphGroups
2674 .size(); q <= newann.graphGroup; q++)
2676 newGraphGroups.add(q, null);
2678 newGraphGroups.set(newann.graphGroup,
2679 Integer.valueOf(++fgroup));
2681 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2685 newann.padAnnotation(alwidth);
2686 alignment.addAnnotation(newann);
2696 addHistoryItem(new EditCommand(
2697 MessageManager.getString("label.add_sequences"),
2698 Action.PASTE, sequences, 0, alignment.getWidth(),
2701 // Add any annotations attached to sequences
2702 for (int i = 0; i < sequences.length; i++)
2704 if (sequences[i].getAnnotation() != null)
2706 AlignmentAnnotation newann;
2707 for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2709 annotationAdded = true;
2710 newann = sequences[i].getAnnotation()[a];
2711 newann.adjustForAlignment();
2712 newann.padAnnotation(alwidth);
2713 if (newann.graphGroup > -1)
2715 if (newann.graphGroup > -1)
2717 if (newGraphGroups.size() <= newann.graphGroup
2718 || newGraphGroups.get(newann.graphGroup) == null)
2720 for (int q = newGraphGroups
2721 .size(); q <= newann.graphGroup; q++)
2723 newGraphGroups.add(q, null);
2725 newGraphGroups.set(newann.graphGroup,
2726 Integer.valueOf(++fgroup));
2728 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2732 alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2736 alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2744 // propagate alignment changed.
2745 viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2746 if (annotationAdded)
2748 // Duplicate sequence annotation in all views.
2749 AlignmentI[] alview = this.getViewAlignments();
2750 for (int i = 0; i < sequences.length; i++)
2752 AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2757 for (int avnum = 0; avnum < alview.length; avnum++)
2759 if (alview[avnum] != alignment)
2761 // duplicate in a view other than the one with input focus
2762 int avwidth = alview[avnum].getWidth() + 1;
2763 // this relies on sann being preserved after we
2764 // modify the sequence's annotation array for each duplication
2765 for (int a = 0; a < sann.length; a++)
2767 AlignmentAnnotation newann = new AlignmentAnnotation(
2769 sequences[i].addAlignmentAnnotation(newann);
2770 newann.padAnnotation(avwidth);
2771 alview[avnum].addAnnotation(newann); // annotation was
2772 // duplicated earlier
2773 // TODO JAL-1145 graphGroups are not updated for sequence
2774 // annotation added to several views. This may cause
2776 alview[avnum].setAnnotationIndex(newann, a);
2781 buildSortByAnnotationScoresMenu();
2783 viewport.notifyAlignment();
2784 if (alignPanels != null)
2786 for (AlignmentPanel ap : alignPanels)
2788 ap.validateAnnotationDimensions(false);
2793 alignPanel.validateAnnotationDimensions(false);
2799 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2801 String newtitle = new String("Copied sequences");
2803 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2805 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2806 af.viewport.setHiddenColumns(hc);
2809 // >>>This is a fix for the moment, until a better solution is
2811 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2812 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2813 .getFeatureRenderer());
2815 // TODO: maintain provenance of an alignment, rather than just make the
2816 // title a concatenation of operations.
2819 if (title.startsWith("Copied sequences"))
2825 newtitle = newtitle.concat("- from " + title);
2830 newtitle = new String("Pasted sequences");
2833 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2838 } catch (Exception ex)
2840 ex.printStackTrace();
2841 System.out.println("Exception whilst pasting: " + ex);
2842 // could be anything being pasted in here
2848 protected void expand_newalign(ActionEvent e)
2852 AlignmentI alignment = AlignmentUtils
2853 .expandContext(getViewport().getAlignment(), -1);
2854 AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2856 String newtitle = new String("Flanking alignment");
2858 Desktop d = Desktop.getInstance();
2859 if (d.jalviewClipboard != null && d.jalviewClipboard[2] != null)
2861 HiddenColumns hc = (HiddenColumns) d.jalviewClipboard[2];
2862 af.viewport.setHiddenColumns(hc);
2865 // >>>This is a fix for the moment, until a better solution is
2867 af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2868 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2869 .getFeatureRenderer());
2871 // TODO: maintain provenance of an alignment, rather than just make the
2872 // title a concatenation of operations.
2874 if (title.startsWith("Copied sequences"))
2880 newtitle = newtitle.concat("- from " + title);
2884 Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2886 } catch (Exception ex)
2888 ex.printStackTrace();
2889 System.out.println("Exception whilst pasting: " + ex);
2890 // could be anything being pasted in here
2891 } catch (OutOfMemoryError oom)
2893 new OOMWarning("Viewing flanking region of alignment", oom);
2898 * Action Cut (delete and copy) the selected region
2901 protected void cut_actionPerformed()
2903 copy_actionPerformed();
2904 delete_actionPerformed();
2908 * Performs menu option to Delete the currently selected region
2911 protected void delete_actionPerformed()
2914 SequenceGroup sg = viewport.getSelectionGroup();
2920 Runnable okAction = new Runnable()
2925 SequenceI[] cut = sg.getSequences()
2926 .toArray(new SequenceI[sg.getSize()]);
2928 addHistoryItem(new EditCommand(
2929 MessageManager.getString("label.cut_sequences"), Action.CUT,
2930 cut, sg.getStartRes(),
2931 sg.getEndRes() - sg.getStartRes() + 1,
2932 viewport.getAlignment()));
2934 viewport.setSelectionGroup(null);
2935 viewport.sendSelection();
2936 viewport.getAlignment().deleteGroup(sg);
2938 viewport.notifyAlignment();
2939 if (viewport.getAlignment().getHeight() < 1)
2943 AlignFrame.this.setClosed(true);
2944 } catch (Exception ex)
2954 * If the cut affects all sequences, prompt for confirmation
2956 boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2958 boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2959 + 1) == viewport.getAlignment().getWidth()) ? true : false;
2960 if (wholeHeight && wholeWidth)
2962 JvOptionPane dialog = JvOptionPane
2963 .newOptionDialog(Desktop.getDesktopPane());
2964 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2965 Object[] options = new Object[] {
2966 MessageManager.getString("action.ok"),
2967 MessageManager.getString("action.cancel") };
2968 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2969 MessageManager.getString("label.delete_all"),
2970 JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2971 options, options[0]);
2986 protected void deleteGroups_actionPerformed(ActionEvent e)
2988 if (avc.deleteGroups())
2990 updateAll(viewport.getSequenceSetId());
2994 private void updateAll(String id)
2998 // this will force a non-fast repaint of both the IdPanel and SeqPanel
2999 alignPanel.getIdPanel().getIdCanvas().setNoFastPaint();
3000 alignPanel.getSeqPanel().seqCanvas.setNoFastPaint();
3001 alignPanel.repaint();
3006 PaintRefresher.Refresh(this, id);
3007 alignPanel.paintAlignment(true, true);
3009 alignPanel.updateAnnotation();
3019 public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3021 alignPanel.selectAllSequences();
3031 public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
3033 alignPanel.deselectAllSequences();
3043 public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
3045 SequenceGroup sg = viewport.getSelectionGroup();
3049 alignPanel.selectAllSequences();
3054 for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
3056 sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
3058 // JAL-2034 - should delegate to
3059 // alignPanel to decide if overview needs
3062 alignPanel.paintAlignment(true, false);
3063 PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
3064 viewport.sendSelection();
3068 public void invertColSel_actionPerformed(ActionEvent e)
3070 viewport.invertColumnSelection();
3071 alignPanel.paintAlignment(true, false);
3072 viewport.sendSelection();
3082 public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
3084 trimAlignment(true);
3094 public void remove2RightMenuItem_actionPerformed(ActionEvent e)
3096 trimAlignment(false);
3099 void trimAlignment(boolean trimLeft)
3101 ColumnSelection colSel = viewport.getColumnSelection();
3104 if (!colSel.isEmpty())
3108 column = colSel.getMin();
3112 column = colSel.getMax();
3116 if (viewport.getSelectionGroup() != null)
3118 seqs = viewport.getSelectionGroup()
3119 .getSequencesAsArray(viewport.getHiddenRepSequences());
3123 seqs = viewport.getAlignment().getSequencesArray();
3126 TrimRegionCommand trimRegion;
3129 trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
3130 column, viewport.getAlignment());
3131 viewport.getRanges().setStartRes(0);
3135 trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
3136 column, viewport.getAlignment());
3139 setStatus(MessageManager.formatMessage("label.removed_columns",
3141 { Integer.valueOf(trimRegion.getSize()).toString() }));
3143 addHistoryItem(trimRegion);
3145 for (SequenceGroup sg : viewport.getAlignment().getGroups())
3147 if ((trimLeft && !sg.adjustForRemoveLeft(column))
3148 || (!trimLeft && !sg.adjustForRemoveRight(column)))
3150 viewport.getAlignment().deleteGroup(sg);
3154 viewport.notifyAlignment();
3165 public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
3167 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3170 if (viewport.getSelectionGroup() != null)
3172 seqs = viewport.getSelectionGroup()
3173 .getSequencesAsArray(viewport.getHiddenRepSequences());
3174 start = viewport.getSelectionGroup().getStartRes();
3175 end = viewport.getSelectionGroup().getEndRes();
3179 seqs = viewport.getAlignment().getSequencesArray();
3182 RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
3183 "Remove Gapped Columns", seqs, start, end,
3184 viewport.getAlignment());
3186 addHistoryItem(removeGapCols);
3188 setStatus(MessageManager.formatMessage("label.removed_empty_columns",
3190 { Integer.valueOf(removeGapCols.getSize()).toString() }));
3192 // This is to maintain viewport position on first residue
3193 // of first sequence
3194 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3195 ViewportRanges ranges = viewport.getRanges();
3196 int startRes = seq.findPosition(ranges.getStartRes());
3197 // ShiftList shifts;
3198 // viewport.getAlignment().removeGaps(shifts=new ShiftList());
3199 // edit.alColumnChanges=shifts.getInverse();
3200 // if (viewport.hasHiddenColumns)
3201 // viewport.getColumnSelection().compensateForEdits(shifts);
3202 ranges.setStartRes(seq.findIndex(startRes) - 1);
3203 viewport.notifyAlignment();
3214 public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
3216 int start = 0, end = viewport.getAlignment().getWidth() - 1;
3219 if (viewport.getSelectionGroup() != null)
3221 seqs = viewport.getSelectionGroup()
3222 .getSequencesAsArray(viewport.getHiddenRepSequences());
3223 start = viewport.getSelectionGroup().getStartRes();
3224 end = viewport.getSelectionGroup().getEndRes();
3228 seqs = viewport.getAlignment().getSequencesArray();
3231 // This is to maintain viewport position on first residue
3232 // of first sequence
3233 SequenceI seq = viewport.getAlignment().getSequenceAt(0);
3234 int startRes = seq.findPosition(viewport.getRanges().getStartRes());
3236 addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
3237 viewport.getAlignment()));
3239 viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
3241 viewport.notifyAlignment();
3252 public void padGapsMenuitem_actionPerformed(ActionEvent e)
3254 viewport.setPadGaps(padGapsMenuitem.isSelected());
3255 viewport.notifyAlignment();
3259 * Opens a Finder dialog
3264 public void findMenuItem_actionPerformed(ActionEvent e)
3266 new Finder(alignPanel, false, null);
3270 * Create a new view of the current alignment.
3273 public void newView_actionPerformed(ActionEvent e)
3275 newView(null, true);
3279 * Creates and shows a new view of the current alignment.
3282 * title of newly created view; if null, one will be generated
3283 * @param copyAnnotation
3284 * if true then duplicate all annnotation, groups and settings
3285 * @return new alignment panel, already displayed.
3287 public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
3290 * Create a new AlignmentPanel (with its own, new Viewport)
3292 AlignmentPanel newap = new jalview.project.Jalview2XML()
3293 .copyAlignPanel(alignPanel);
3294 if (!copyAnnotation)
3297 * remove all groups and annotation except for the automatic stuff
3299 newap.av.getAlignment().deleteAllGroups();
3300 newap.av.getAlignment().deleteAllAnnotations(false);
3303 newap.av.setGatherViewsHere(false);
3305 if (viewport.getViewName() == null)
3307 viewport.setViewName(
3308 MessageManager.getString("label.view_name_original"));
3312 * Views share the same edits undo and redo stacks
3314 newap.av.setHistoryList(viewport.getHistoryList());
3315 newap.av.setRedoList(viewport.getRedoList());
3318 * copy any visualisation settings that are not saved in the project
3320 newap.av.setColourAppliesToAllGroups(
3321 viewport.getColourAppliesToAllGroups());
3324 * Views share the same mappings; need to deregister any new mappings
3325 * created by copyAlignPanel, and register the new reference to the shared
3328 newap.av.replaceMappings(viewport.getAlignment());
3331 * start up cDNA consensus (if applicable) now mappings are in place
3333 if (newap.av.initComplementConsensus())
3335 newap.refresh(true); // adjust layout of annotations
3338 newap.av.setViewName(getNewViewName(viewTitle));
3340 addAlignmentPanel(newap, true);
3341 newap.alignmentChanged();
3343 if (alignPanels.size() == 2)
3345 viewport.setGatherViewsHere(true);
3347 tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
3352 * Make a new name for the view, ensuring it is unique within the current
3353 * sequenceSetId. (This used to be essential for Jalview Project archives, but
3354 * these now use viewId. Unique view names are still desirable for usability.)
3359 protected String getNewViewName(String viewTitle)
3361 int index = Desktop.getViewCount(viewport.getSequenceSetId());
3362 boolean addFirstIndex = false;
3363 if (viewTitle == null || viewTitle.trim().length() == 0)
3365 viewTitle = MessageManager.getString("action.view");
3366 addFirstIndex = true;
3370 index = 1;// we count from 1 if given a specific name
3372 String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
3374 List<Component> comps = PaintRefresher.components
3375 .get(viewport.getSequenceSetId());
3377 List<String> existingNames = getExistingViewNames(comps);
3379 while (existingNames.contains(newViewName))
3381 newViewName = viewTitle + " " + (++index);
3387 * Returns a list of distinct view names found in the given list of
3388 * components. View names are held on the viewport of an AlignmentPanel.
3393 protected List<String> getExistingViewNames(List<Component> comps)
3395 List<String> existingNames = new ArrayList<>();
3396 for (Component comp : comps)
3398 if (comp instanceof AlignmentPanel)
3400 AlignmentPanel ap = (AlignmentPanel) comp;
3401 if (!existingNames.contains(ap.av.getViewName()))
3403 existingNames.add(ap.av.getViewName());
3407 return existingNames;
3411 * Explode tabbed views into separate windows.
3414 public void expandViews_actionPerformed(ActionEvent e)
3416 Desktop.explodeViews(this);
3420 * Gather views in separate windows back into a tabbed presentation.
3423 public void gatherViews_actionPerformed(ActionEvent e)
3425 Desktop.getInstance().gatherViews(this);
3435 public void font_actionPerformed(ActionEvent e)
3437 new FontChooser(alignPanel);
3447 protected void seqLimit_actionPerformed(ActionEvent e)
3449 viewport.setShowJVSuffix(seqLimits.isSelected());
3451 alignPanel.getIdPanel().getIdCanvas()
3452 .setPreferredSize(alignPanel.calculateIdWidth());
3453 alignPanel.paintAlignment(true, false);
3457 public void idRightAlign_actionPerformed(ActionEvent e)
3459 viewport.setRightAlignIds(idRightAlign.isSelected());
3460 alignPanel.paintAlignment(false, false);
3464 public void centreColumnLabels_actionPerformed(ActionEvent e)
3466 viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3467 alignPanel.paintAlignment(false, false);
3473 * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3476 protected void followHighlight_actionPerformed()
3479 * Set the 'follow' flag on the Viewport (and scroll to position if now
3482 final boolean state = this.followHighlightMenuItem.getState();
3483 viewport.setFollowHighlight(state);
3486 alignPanel.scrollToPosition(viewport.getSearchResults());
3497 protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3499 viewport.setColourText(colourTextMenuItem.isSelected());
3500 alignPanel.paintAlignment(false, false);
3510 public void wrapMenuItem_actionPerformed(ActionEvent e)
3512 scaleAbove.setVisible(wrapMenuItem.isSelected());
3513 scaleLeft.setVisible(wrapMenuItem.isSelected());
3514 scaleRight.setVisible(wrapMenuItem.isSelected());
3515 viewport.setWrapAlignment(wrapMenuItem.isSelected());
3516 alignPanel.updateLayout();
3520 public void showAllSeqs_actionPerformed(ActionEvent e)
3522 viewport.showAllHiddenSeqs();
3526 public void showAllColumns_actionPerformed(ActionEvent e)
3528 viewport.showAllHiddenColumns();
3529 alignPanel.paintAlignment(true, true);
3530 viewport.sendSelection();
3534 public void hideSelSequences_actionPerformed(ActionEvent e)
3536 viewport.hideAllSelectedSeqs();
3540 * called by key handler and the hide all/show all menu items
3545 protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3548 boolean hide = false;
3549 SequenceGroup sg = viewport.getSelectionGroup();
3550 if (!toggleSeqs && !toggleCols)
3552 // Hide everything by the current selection - this is a hack - we do the
3553 // invert and then hide
3554 // first check that there will be visible columns after the invert.
3555 if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3556 && sg.getStartRes() <= sg.getEndRes()))
3558 // now invert the sequence set, if required - empty selection implies
3559 // that no hiding is required.
3562 invertSequenceMenuItem_actionPerformed(null);
3563 sg = viewport.getSelectionGroup();
3567 viewport.expandColSelection(sg, true);
3568 // finally invert the column selection and get the new sequence
3570 invertColSel_actionPerformed(null);
3577 if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3579 hideSelSequences_actionPerformed(null);
3582 else if (!(toggleCols && viewport.hasSelectedColumns()))
3584 showAllSeqs_actionPerformed(null);
3590 if (viewport.hasSelectedColumns())
3592 hideSelColumns_actionPerformed(null);
3595 viewport.setSelectionGroup(sg);
3600 showAllColumns_actionPerformed(null);
3609 * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3610 * event.ActionEvent)
3613 public void hideAllButSelection_actionPerformed(ActionEvent e)
3615 toggleHiddenRegions(false, false);
3616 viewport.sendSelection();
3623 * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3627 public void hideAllSelection_actionPerformed(ActionEvent e)
3629 SequenceGroup sg = viewport.getSelectionGroup();
3630 viewport.expandColSelection(sg, false);
3631 viewport.hideAllSelectedSeqs();
3632 viewport.hideSelectedColumns();
3633 alignPanel.updateLayout();
3634 alignPanel.paintAlignment(true, true);
3635 viewport.sendSelection();
3642 * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3646 public void showAllhidden_actionPerformed(ActionEvent e)
3648 viewport.showAllHiddenColumns();
3649 viewport.showAllHiddenSeqs();
3650 alignPanel.paintAlignment(true, true);
3651 viewport.sendSelection();
3655 public void hideSelColumns_actionPerformed(ActionEvent e)
3657 viewport.hideSelectedColumns();
3658 alignPanel.updateLayout();
3659 alignPanel.paintAlignment(true, true);
3660 viewport.sendSelection();
3664 public void hiddenMarkers_actionPerformed(ActionEvent e)
3666 viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3677 protected void scaleAbove_actionPerformed(ActionEvent e)
3679 viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3680 alignPanel.updateLayout();
3681 alignPanel.paintAlignment(true, false);
3691 protected void scaleLeft_actionPerformed(ActionEvent e)
3693 viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3694 alignPanel.updateLayout();
3695 alignPanel.paintAlignment(true, false);
3705 protected void scaleRight_actionPerformed(ActionEvent e)
3707 viewport.setScaleRightWrapped(scaleRight.isSelected());
3708 alignPanel.updateLayout();
3709 alignPanel.paintAlignment(true, false);
3719 public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3721 viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3722 alignPanel.paintAlignment(false, false);
3732 public void viewTextMenuItem_actionPerformed(ActionEvent e)
3734 viewport.setShowText(viewTextMenuItem.isSelected());
3735 alignPanel.paintAlignment(false, false);
3745 protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3747 viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3748 alignPanel.paintAlignment(false, false);
3751 public FeatureSettings featureSettings;
3754 public FeatureSettingsControllerI getFeatureSettingsUI()
3756 return featureSettings;
3760 public void featureSettings_actionPerformed(ActionEvent e)
3762 showFeatureSettingsUI();
3766 public FeatureSettingsControllerI showFeatureSettingsUI()
3768 if (featureSettings != null)
3770 featureSettings.closeOldSettings();
3771 featureSettings = null;
3773 if (!showSeqFeatures.isSelected())
3775 // make sure features are actually displayed
3776 showSeqFeatures.setSelected(true);
3777 showSeqFeatures_actionPerformed(null);
3779 featureSettings = new FeatureSettings(this);
3780 return featureSettings;
3784 * Set or clear 'Show Sequence Features'
3790 public void showSeqFeatures_actionPerformed(ActionEvent evt)
3792 viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3793 alignPanel.paintAlignment(true, true);
3797 * Action on toggle of the 'Show annotations' menu item. This shows or hides
3798 * the annotations panel as a whole.
3800 * The options to show/hide all annotations should be enabled when the panel
3801 * is shown, and disabled when the panel is hidden.
3806 public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3808 final boolean setVisible = annotationPanelMenuItem.isSelected();
3809 viewport.setShowAnnotation(setVisible);
3810 syncAnnotationMenuItems(setVisible);
3811 alignPanel.updateLayout();
3813 SwingUtilities.invokeLater(new Runnable() {
3818 alignPanel.updateScrollBarsFromRanges();
3824 private void syncAnnotationMenuItems(boolean setVisible)
3826 showAllSeqAnnotations.setEnabled(setVisible);
3827 hideAllSeqAnnotations.setEnabled(setVisible);
3828 showAllAlAnnotations.setEnabled(setVisible);
3829 hideAllAlAnnotations.setEnabled(setVisible);
3833 public void alignmentProperties()
3836 StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3839 String content = MessageManager.formatMessage("label.html_content",
3841 { contents.toString() });
3844 if (Platform.isJS())
3846 JLabel textLabel = new JLabel();
3847 textLabel.setText(content);
3848 textLabel.setBackground(Color.WHITE);
3850 pane = new JPanel(new BorderLayout());
3851 ((JPanel) pane).setOpaque(true);
3852 pane.setBackground(Color.WHITE);
3853 ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3862 JEditorPane editPane = new JEditorPane("text/html", "");
3863 editPane.setEditable(false);
3864 editPane.setText(content);
3868 JInternalFrame frame = new JInternalFrame();
3870 frame.getContentPane().add(new JScrollPane(pane));
3872 Desktop.addInternalFrame(frame, MessageManager
3873 .formatMessage("label.alignment_properties", new Object[]
3874 { getTitle() }), 500, 400);
3884 public void overviewMenuItem_actionPerformed(ActionEvent e)
3886 if (alignPanel.overviewPanel != null)
3891 JInternalFrame frame = new JInternalFrame();
3892 // BH 2019.07.26 we allow for an embedded
3893 // undecorated overview with defined size
3894 frame.setName(Platform.getAppID("overview"));
3896 Dimension dim = Platform.getDimIfEmbedded(frame, -1, -1);
3897 if (dim != null && dim.width == 0)
3899 dim = null; // hidden, not embedded
3901 OverviewPanel overview = new OverviewPanel(alignPanel, dim);
3902 frame.setContentPane(overview);
3905 dim = new Dimension();
3906 // was frame.getSize(), but that is 0,0 at this point;
3910 // we are imbedding, and so we have an undecorated frame
3911 // and we can set the the frame dimensions accordingly.
3913 // allowing for unresizable option using, style="resize:none"
3914 boolean resizable = (Platform.getEmbeddedAttribute(frame,
3915 "resize") != "none");
3916 Desktop.addInternalFrame(frame, MessageManager
3917 .formatMessage("label.overview_params", new Object[]
3918 { this.getTitle() }), Desktop.FRAME_MAKE_VISIBLE, dim.width,
3919 dim.height, resizable, Desktop.FRAME_ALLOW_ANY_SIZE);
3921 frame.setLayer(JLayeredPane.PALETTE_LAYER);
3922 frame.addInternalFrameListener(
3923 new javax.swing.event.InternalFrameAdapter()
3926 public void internalFrameClosed(
3927 javax.swing.event.InternalFrameEvent evt)
3930 alignPanel.setOverviewPanel(null);
3933 if (getKeyListeners().length > 0)
3935 frame.addKeyListener(getKeyListeners()[0]);
3938 alignPanel.setOverviewPanel(overview);
3942 public void textColour_actionPerformed()
3944 new TextColourChooser().chooseColour(alignPanel, null);
3948 * public void covariationColour_actionPerformed() {
3950 * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3954 public void annotationColour_actionPerformed()
3956 new AnnotationColourChooser(viewport, alignPanel);
3960 public void annotationColumn_actionPerformed(ActionEvent e)
3962 new AnnotationColumnChooser(viewport, alignPanel);
3966 * Action on the user checking or unchecking the option to apply the selected
3967 * colour scheme to all groups. If unchecked, groups may have their own
3968 * independent colour schemes.
3973 public void applyToAllGroups_actionPerformed(boolean selected)
3975 viewport.setColourAppliesToAllGroups(selected);
3979 * Action on user selecting a colour from the colour menu
3982 * the name (not the menu item label!) of the colour scheme
3985 public void changeColour_actionPerformed(String name)
3988 * 'User Defined' opens a panel to configure or load a
3989 * user-defined colour scheme
3991 if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3993 new UserDefinedColours(alignPanel);
3998 * otherwise set the chosen colour scheme (or null for 'None')
4000 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
4001 viewport, viewport.getAlignment(),
4002 viewport.getHiddenRepSequences());
4007 * Actions on setting or changing the alignment colour scheme
4012 public void changeColour(ColourSchemeI cs)
4014 // TODO: pull up to controller method
4015 ColourMenuHelper.setColourSelected(colourMenu, cs);
4017 viewport.setGlobalColourScheme(cs);
4019 alignPanel.paintAlignment(true, true);
4023 * Show the PID threshold slider panel
4026 protected void modifyPID_actionPerformed()
4028 SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
4029 alignPanel.getViewName());
4030 SliderPanel.showPIDSlider();
4034 * Show the Conservation slider panel
4037 protected void modifyConservation_actionPerformed()
4039 SliderPanel.setConservationSlider(alignPanel,
4040 viewport.getResidueShading(), alignPanel.getViewName());
4041 SliderPanel.showConservationSlider();
4045 * Action on selecting or deselecting (Colour) By Conservation
4048 public void conservationMenuItem_actionPerformed(boolean selected)
4050 modifyConservation.setEnabled(selected);
4051 viewport.setConservationSelected(selected);
4052 viewport.getResidueShading().setConservationApplied(selected);
4054 changeColour(viewport.getGlobalColourScheme());
4057 modifyConservation_actionPerformed();
4061 SliderPanel.hideConservationSlider();
4066 * Action on selecting or deselecting (Colour) Above PID Threshold
4069 public void abovePIDThreshold_actionPerformed(boolean selected)
4071 modifyPID.setEnabled(selected);
4072 viewport.setAbovePIDThreshold(selected);
4075 viewport.getResidueShading().setThreshold(0,
4076 viewport.isIgnoreGapsConsensus());
4079 changeColour(viewport.getGlobalColourScheme());
4082 modifyPID_actionPerformed();
4086 SliderPanel.hidePIDSlider();
4097 public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
4099 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4100 AlignmentSorter.sortByPID(viewport.getAlignment(),
4101 viewport.getAlignment().getSequenceAt(0));
4102 addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
4103 viewport.getAlignment()));
4104 alignPanel.paintAlignment(true, false);
4114 public void sortIDMenuItem_actionPerformed(ActionEvent e)
4116 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4117 AlignmentSorter.sortByID(viewport.getAlignment());
4119 new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
4120 alignPanel.paintAlignment(true, false);
4130 public void sortLengthMenuItem_actionPerformed(ActionEvent e)
4132 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4133 AlignmentSorter.sortByLength(viewport.getAlignment());
4134 addHistoryItem(new OrderCommand("Length Sort", oldOrder,
4135 viewport.getAlignment()));
4136 alignPanel.paintAlignment(true, false);
4146 public void sortGroupMenuItem_actionPerformed(ActionEvent e)
4148 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4149 AlignmentSorter.sortByGroup(viewport.getAlignment());
4150 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4151 viewport.getAlignment()));
4153 alignPanel.paintAlignment(true, false);
4157 public void sortEValueMenuItem_actionPerformed(ActionEvent e)
4159 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4160 AlignmentSorter.sortByEValue(viewport.getAlignment());
4161 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4162 viewport.getAlignment()));
4163 alignPanel.paintAlignment(true, false);
4168 public void sortBitScoreMenuItem_actionPerformed(ActionEvent e)
4170 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4171 AlignmentSorter.sortByBitScore(viewport.getAlignment());
4172 addHistoryItem(new OrderCommand("Group Sort", oldOrder,
4173 viewport.getAlignment()));
4174 alignPanel.paintAlignment(true, false);
4184 public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
4186 new RedundancyPanel(alignPanel, this);
4196 public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
4198 if ((viewport.getSelectionGroup() == null)
4199 || (viewport.getSelectionGroup().getSize() < 2))
4201 JvOptionPane.showInternalMessageDialog(this,
4202 MessageManager.getString(
4203 "label.you_must_select_least_two_sequences"),
4204 MessageManager.getString("label.invalid_selection"),
4205 JvOptionPane.WARNING_MESSAGE);
4209 JInternalFrame frame = new JInternalFrame();
4210 frame.setContentPane(new PairwiseAlignPanel(viewport));
4211 Desktop.addInternalFrame(frame,
4212 MessageManager.getString("action.pairwise_alignment"), 600,
4218 public void autoCalculate_actionPerformed(ActionEvent e)
4220 viewport.setAutoCalculateConsensusAndConservation(
4221 autoCalculate.isSelected());
4222 if (viewport.getAutoCalculateConsensusAndConservation())
4224 viewport.notifyAlignment();
4229 public void sortByTreeOption_actionPerformed(ActionEvent e)
4231 viewport.sortByTree = sortByTree.isSelected();
4235 protected void listenToViewSelections_actionPerformed(ActionEvent e)
4237 viewport.followSelection = listenToViewSelections.isSelected();
4241 * Constructs a tree panel and adds it to the desktop
4244 * tree type (NJ or AV)
4246 * name of score model used to compute the tree
4248 * parameters for the distance or similarity calculation
4250 void newTreePanel(String type, String modelName,
4251 SimilarityParamsI options)
4253 String frameTitle = "";
4256 boolean onSelection = false;
4257 if (viewport.getSelectionGroup() != null
4258 && viewport.getSelectionGroup().getSize() > 0)
4260 SequenceGroup sg = viewport.getSelectionGroup();
4262 /* Decide if the selection is a column region */
4263 for (SequenceI _s : sg.getSequences())
4265 if (_s.getLength() < sg.getEndRes())
4267 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4268 MessageManager.getString(
4269 "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4270 MessageManager.getString(
4271 "label.sequences_selection_not_aligned"),
4272 JvOptionPane.WARNING_MESSAGE);
4281 if (viewport.getAlignment().getHeight() < 2)
4287 tp = new TreePanel(alignPanel, type, modelName, options);
4288 frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
4290 frameTitle += " from ";
4292 if (viewport.getViewName() != null)
4294 frameTitle += viewport.getViewName() + " of ";
4297 frameTitle += this.title;
4299 Dimension dim = Platform.getDimIfEmbedded(tp, 600, 500);
4300 Desktop.addInternalFrame(tp, frameTitle, dim.width, dim.height);
4311 public void addSortByOrderMenuItem(String title,
4312 final AlignmentOrder order)
4314 final JMenuItem item = new JMenuItem(MessageManager
4315 .formatMessage("action.by_title_param", new Object[]
4318 item.addActionListener(new java.awt.event.ActionListener()
4321 public void actionPerformed(ActionEvent e)
4323 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4325 // TODO: JBPNote - have to map order entries to curent SequenceI
4327 AlignmentSorter.sortBy(viewport.getAlignment(), order);
4329 addHistoryItem(new OrderCommand(order.getName(), oldOrder,
4330 viewport.getAlignment()));
4332 alignPanel.paintAlignment(true, false);
4338 * Add a new sort by annotation score menu item
4341 * the menu to add the option to
4343 * the label used to retrieve scores for each sequence on the
4346 public void addSortByAnnotScoreMenuItem(JMenu sort,
4347 final String scoreLabel)
4349 final JMenuItem item = new JMenuItem(scoreLabel);
4351 item.addActionListener(new java.awt.event.ActionListener()
4354 public void actionPerformed(ActionEvent e)
4356 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4357 AlignmentSorter.sortByAnnotationScore(scoreLabel,
4358 viewport.getAlignment());// ,viewport.getSelectionGroup());
4359 addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4360 viewport.getAlignment()));
4361 alignPanel.paintAlignment(true, false);
4367 * last hash for alignment's annotation array - used to minimise cost of
4370 protected int _annotationScoreVectorHash;
4373 * search the alignment and rebuild the sort by annotation score submenu the
4374 * last alignment annotation vector hash is stored to minimize cost of
4375 * rebuilding in subsequence calls.
4379 public void buildSortByAnnotationScoresMenu()
4381 if (viewport.getAlignment().getAlignmentAnnotation() == null)
4386 if (viewport.getAlignment().getAlignmentAnnotation()
4387 .hashCode() == _annotationScoreVectorHash)
4392 sortByAnnotScore.removeAll();
4393 Set<String> scoreSorts = new HashSet<>();
4394 for (SequenceI sqa : viewport.getAlignment().getSequences())
4396 AlignmentAnnotation[] anns = sqa.getAnnotation();
4397 for (int i = 0; anns != null && i < anns.length; i++)
4399 AlignmentAnnotation aa = anns[i];
4400 if (aa != null && aa.hasScore() && aa.sequenceRef != null)
4402 scoreSorts.add(aa.label);
4406 for (String label : scoreSorts)
4408 addSortByAnnotScoreMenuItem(sortByAnnotScore, label);
4410 sortByAnnotScore.setVisible(!scoreSorts.isEmpty());
4412 _annotationScoreVectorHash = viewport.getAlignment()
4413 .getAlignmentAnnotation().hashCode();
4417 * Enable (or, if desired, make visible) the By Tree
4418 * submenu only if it has at least one element (or will have).
4422 protected void enableSortMenuOptions()
4424 List<TreePanel> treePanels = getTreePanels();
4425 sortByTreeMenu.setEnabled(!treePanels.isEmpty());
4429 * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4430 * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4431 * call. Listeners are added to remove the menu item when the treePanel is
4432 * closed, and adjust the tree leaf to sequence mapping when the alignment is
4436 public void buildTreeSortMenu()
4438 sortByTreeMenu.removeAll();
4440 List<TreePanel> treePanels = getTreePanels();
4442 for (final TreePanel tp : treePanels)
4444 final JMenuItem item = new JMenuItem(tp.getTitle());
4445 item.addActionListener(new java.awt.event.ActionListener()
4448 public void actionPerformed(ActionEvent e)
4450 tp.sortByTree_actionPerformed();
4451 addHistoryItem(tp.sortAlignmentIn(alignPanel));
4456 sortByTreeMenu.add(item);
4460 private List<TreePanel> getTreePanels()
4462 List<Component> comps = PaintRefresher.components
4463 .get(viewport.getSequenceSetId());
4464 List<TreePanel> treePanels = new ArrayList<>();
4465 for (Component comp : comps)
4467 if (comp instanceof TreePanel)
4469 treePanels.add((TreePanel) comp);
4474 public boolean sortBy(AlignmentOrder alorder, String undoname)
4476 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4477 AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4478 if (undoname != null)
4480 addHistoryItem(new OrderCommand(undoname, oldOrder,
4481 viewport.getAlignment()));
4483 alignPanel.paintAlignment(true, false);
4488 * Work out whether the whole set of sequences or just the selected set will
4489 * be submitted for multiple alignment.
4492 public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4494 // Now, check we have enough sequences
4495 AlignmentView msa = null;
4497 if ((viewport.getSelectionGroup() != null)
4498 && (viewport.getSelectionGroup().getSize() > 1))
4500 // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4501 // some common interface!
4503 * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4504 * SequenceI[sz = seqs.getSize(false)];
4506 * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4507 * seqs.getSequenceAt(i); }
4509 msa = viewport.getAlignmentView(true);
4511 else if (viewport.getSelectionGroup() != null
4512 && viewport.getSelectionGroup().getSize() == 1)
4514 int option = JvOptionPane.showConfirmDialog(this,
4515 MessageManager.getString("warn.oneseq_msainput_selection"),
4516 MessageManager.getString("label.invalid_selection"),
4517 JvOptionPane.OK_CANCEL_OPTION);
4518 if (option == JvOptionPane.OK_OPTION)
4520 msa = viewport.getAlignmentView(false);
4525 msa = viewport.getAlignmentView(false);
4531 * Decides what is submitted to a secondary structure prediction service: the
4532 * first sequence in the alignment, or in the current selection, or, if the
4533 * alignment is 'aligned' (ie padded with gaps), then the currently selected
4534 * region or the whole alignment. (where the first sequence in the set is the
4535 * one that the prediction will be for).
4537 public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4539 AlignmentView seqs = null;
4541 if ((viewport.getSelectionGroup() != null)
4542 && (viewport.getSelectionGroup().getSize() > 0))
4544 seqs = viewport.getAlignmentView(true);
4548 seqs = viewport.getAlignmentView(false);
4550 // limit sequences - JBPNote in future - could spawn multiple prediction
4552 // TODO: viewport.getAlignment().isAligned is a global state - the local
4553 // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4554 if (!viewport.getAlignment().isAligned(false))
4556 seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4557 // TODO: if seqs.getSequences().length>1 then should really have warned
4571 protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4573 // Pick the tree file
4574 JalviewFileChooser chooser = new JalviewFileChooser(
4575 Cache.getProperty("LAST_DIRECTORY"));
4576 chooser.setFileView(new JalviewFileView());
4577 chooser.setDialogTitle(
4578 MessageManager.getString("label.select_newick_like_tree_file"));
4579 chooser.setToolTipText(
4580 MessageManager.getString("label.load_tree_file"));
4582 chooser.setResponseHandler(0, new Runnable()
4587 String filePath = chooser.getSelectedFile().getPath();
4588 Cache.setProperty("LAST_DIRECTORY", filePath);
4589 NewickFile fin = null;
4592 fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4593 DataSourceType.FILE));
4594 viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4595 } catch (Exception ex)
4597 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4600 .getString("label.problem_reading_tree_file"),
4601 JvOptionPane.WARNING_MESSAGE);
4602 ex.printStackTrace();
4604 if (fin != null && fin.hasWarningMessage())
4606 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
4607 fin.getWarningMessage(),
4608 MessageManager.getString(
4609 "label.possible_problem_with_tree_file"),
4610 JvOptionPane.WARNING_MESSAGE);
4614 chooser.showOpenDialog(this);
4617 public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4619 return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4622 public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4623 int h, int x, int y)
4625 return showNewickTree(nf, treeTitle, null, w, h, x, y);
4629 * Add a treeviewer for the tree extracted from a Newick file object to the
4630 * current alignment view
4637 * Associated alignment input data (or null)
4646 * @return TreePanel handle
4648 public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4649 AlignmentView input, int w, int h, int x, int y)
4651 TreePanel tp = null;
4657 if (nf.getTree() != null)
4659 tp = new TreePanel(alignPanel, nf, treeTitle, input);
4661 Dimension dim = Platform.getDimIfEmbedded(tp, -1, -1);
4664 dim = new Dimension(w, h);
4668 // no offset, either
4671 tp.setSize(dim.width, dim.height);
4675 tp.setLocation(x, y);
4678 Desktop.addInternalFrame(tp, treeTitle, dim.width, dim.height);
4680 } catch (Exception ex)
4682 ex.printStackTrace();
4688 private WebServicesMenuManager slivkaMenu = new WebServicesMenuManager("slivka", this);
4689 private WebServicesMenuManager ebiMenu = new WebServicesMenuManager("job dispatcher", this);
4690 private WebServicesMenuManager jpred4Menu = new WebServicesMenuManager("jpred4", this);
4693 * Schedule the web services menu rebuild to the event dispatch thread.
4695 public void buildWebServicesMenu()
4697 SwingUtilities.invokeLater(() -> {
4698 Console.info("Rebuiling WS menu");
4699 webService.removeAll();
4700 if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
4702 Console.info("Building web service menu for slivka");
4703 SlivkaWSDiscoverer discoverer = SlivkaWSDiscoverer.getInstance();
4704 slivkaMenu.setServices(discoverer);
4705 slivkaMenu.setInProgress(discoverer.isRunning());
4706 slivkaMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4707 webService.add(slivkaMenu.getMenu());
4709 if (Cache.getDefault("SHOW_EBI_SERVICES", true))
4711 Console.info("Building web services menu for jobs dispatcher");
4712 JobDispatcherWSDiscoverer discoverer = JobDispatcherWSDiscoverer.getInstance();
4713 ebiMenu.setServices(discoverer);
4714 ebiMenu.setInProgress(discoverer.isRunning());
4715 ebiMenu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4716 webService.add(ebiMenu.getMenu());
4718 if (Cache.getDefault("SHOW_JPRED4_SERVICES", true))
4720 Console.info("Building web services menu for jpred4");
4721 JPred4WSDiscoverer discoverer = JPred4WSDiscoverer.getInstance();
4722 jpred4Menu.setServices(discoverer);
4723 jpred4Menu.setInProgress(discoverer.isRunning());
4724 jpred4Menu.setNoServices(discoverer.isDone() && !discoverer.hasServices());
4725 webService.add(jpred4Menu.getMenu());
4727 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4729 WSDiscovererI jws2servs = Jws2Discoverer.getInstance();
4730 JMenu submenu = new JMenu("JABAWS");
4731 buildLegacyWebServicesMenu(submenu);
4732 buildWebServicesMenu(jws2servs, submenu);
4733 webService.add(submenu);
4735 build_urlServiceMenu(webService);
4736 build_fetchdbmenu(webService);
4740 private void buildLegacyWebServicesMenu(JMenu menu)
4742 JMenu secstrmenu = new JMenu("Secondary Structure Prediction");
4743 if (Discoverer.getServices() != null && Discoverer.getServices().size() > 0)
4745 var secstrpred = Discoverer.getServices().get("SecStrPred");
4746 if (secstrpred != null)
4748 for (ext.vamsas.ServiceHandle sh : secstrpred)
4750 var menuProvider = Discoverer.getServiceClient(sh);
4751 menuProvider.attachWSMenuEntry(secstrmenu, this);
4755 menu.add(secstrmenu);
4759 * Constructs the web services menu for the given discoverer under the
4760 * specified menu. This method must be called on the EDT
4763 * the discoverer used to build the menu
4765 * parent component which the elements will be attached to
4767 private void buildWebServicesMenu(WSDiscovererI discoverer, JMenu menu)
4769 if (discoverer.hasServices())
4771 PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
4772 discoverer.getServices(), sv -> buildWebServicesMenu(), menu,
4775 if (discoverer.isRunning())
4777 JMenuItem item = new JMenuItem("Service discovery in progress.");
4778 item.setEnabled(false);
4781 else if (!discoverer.hasServices())
4783 JMenuItem item = new JMenuItem("No services available.");
4784 item.setEnabled(false);
4790 * construct any groupURL type service menu entries.
4794 protected void build_urlServiceMenu(JMenu webService)
4796 // TODO: remove this code when 2.7 is released
4797 // DEBUG - alignmentView
4799 * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4800 * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4802 * public void actionPerformed(ActionEvent e) {
4803 * jalview.datamodel.AlignmentView
4804 * .testSelectionViews(af.viewport.getAlignment(),
4805 * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4807 * }); webService.add(testAlView);
4809 // TODO: refactor to RestClient discoverer and merge menu entries for
4810 // rest-style services with other types of analysis/calculation service
4811 // SHmmr test client - still being implemented.
4812 // DEBUG - alignmentView
4814 for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4817 client.attachWSMenuEntry(
4818 JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4824 * Searches the alignment sequences for xRefs and builds the Show
4825 * Cross-References menu (formerly called Show Products), with database
4826 * sources for which cross-references are found (protein sources for a
4827 * nucleotide alignment and vice versa)
4829 * @return true if Show Cross-references menu should be enabled
4831 public boolean canShowProducts()
4833 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4834 AlignmentI dataset = viewport.getAlignment().getDataset();
4836 showProducts.removeAll();
4837 final boolean dna = viewport.getAlignment().isNucleotide();
4839 if (seqs == null || seqs.length == 0)
4841 // nothing to see here.
4845 boolean showp = false;
4848 List<String> ptypes = new CrossRef(seqs, dataset)
4849 .findXrefSourcesForSequences(dna);
4851 for (final String source : ptypes)
4854 final AlignFrame af = this;
4855 JMenuItem xtype = new JMenuItem(source);
4856 xtype.addActionListener(new ActionListener()
4859 public void actionPerformed(ActionEvent e)
4861 showProductsFor(af.viewport.getSequenceSelection(), dna,
4865 showProducts.add(xtype);
4867 showProducts.setVisible(showp);
4868 showProducts.setEnabled(showp);
4869 } catch (Exception e)
4872 "canShowProducts threw an exception - please report to help@jalview.org",
4880 * Finds and displays cross-references for the selected sequences (protein
4881 * products for nucleotide sequences, dna coding sequences for peptides).
4884 * the sequences to show cross-references for
4886 * true if from a nucleotide alignment (so showing proteins)
4888 * the database to show cross-references for
4890 protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4891 final String source)
4893 new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4898 * Construct and display a new frame containing the translation of this
4899 * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4902 public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4904 AlignmentI al = null;
4907 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4909 al = dna.translateCdna(codeTable);
4910 } catch (Exception ex)
4912 Console.error("Exception during translation. Please report this !",
4914 final String msg = MessageManager.getString(
4915 "label.error_when_translating_sequences_submit_bug_report");
4916 final String errorTitle = MessageManager
4917 .getString("label.implementation_error")
4918 + MessageManager.getString("label.translation_failed");
4919 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4920 errorTitle, JvOptionPane.ERROR_MESSAGE);
4923 if (al == null || al.getHeight() == 0)
4925 final String msg = MessageManager.getString(
4926 "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4927 final String errorTitle = MessageManager
4928 .getString("label.translation_failed");
4929 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(), msg,
4930 errorTitle, JvOptionPane.WARNING_MESSAGE);
4934 AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4935 af.setFileFormat(this.currentFileFormat);
4936 final String newTitle = MessageManager
4937 .formatMessage("label.translation_of_params", new Object[]
4938 { this.getTitle(), codeTable.getId() });
4939 af.setTitle(newTitle);
4940 if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4942 final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4943 AlignViewport.openSplitFrame(this, af, new Alignment(seqs));
4947 Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4954 * Set the file format
4958 public void setFileFormat(FileFormatI format)
4960 this.currentFileFormat = format;
4964 * Try to load a features file onto the alignment.
4967 * contents or path to retrieve file or a File object
4969 * access mode of file (see jalview.io.AlignFile)
4970 * @return true if features file was parsed correctly.
4972 public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4975 return avc.parseFeaturesFile(file, sourceType,
4976 Cache.getDefault(Preferences.RELAXEDSEQIDMATCHING, false));
4981 public void refreshFeatureUI(boolean enableIfNecessary)
4983 // note - currently this is only still here rather than in the controller
4984 // because of the featureSettings hard reference that is yet to be
4986 if (enableIfNecessary)
4988 viewport.setShowSequenceFeatures(true);
4989 showSeqFeatures.setSelected(true);
4995 public void dragEnter(DropTargetDragEvent evt)
5000 public void dragExit(DropTargetEvent evt)
5005 public void dragOver(DropTargetDragEvent evt)
5010 public void dropActionChanged(DropTargetDragEvent evt)
5015 public void drop(DropTargetDropEvent evt)
5017 // JAL-1552 - acceptDrop required before getTransferable call for
5018 // Java's Transferable for native dnd
5019 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5020 Transferable t = evt.getTransferable();
5022 final List<Object> files = new ArrayList<>();
5023 List<DataSourceType> protocols = new ArrayList<>();
5027 Desktop.transferFromDropTarget(files, protocols, evt, t);
5028 if (files.size() > 0)
5030 new Thread(new Runnable()
5036 loadDroppedFiles(files, protocols, evt, t);
5040 } catch (Exception e)
5042 e.printStackTrace();
5046 protected void loadDroppedFiles(List<Object> files,
5047 List<DataSourceType> protocols, DropTargetDropEvent evt,
5052 // check to see if any of these files have names matching sequences
5055 SequenceIdMatcher idm = new SequenceIdMatcher(
5056 viewport.getAlignment().getSequencesArray());
5058 * Object[] { String,SequenceI}
5060 ArrayList<Object[]> filesmatched = new ArrayList<>();
5061 ArrayList<Object> filesnotmatched = new ArrayList<>();
5062 for (int i = 0; i < files.size(); i++)
5065 Object fileObj = files.get(i);
5066 String fileName = fileObj.toString();
5068 DataSourceType protocol = (fileObj instanceof File
5069 ? DataSourceType.FILE
5070 : FormatAdapter.checkProtocol(fileName));
5071 if (protocol == DataSourceType.FILE)
5074 if (fileObj instanceof File)
5076 file = (File) fileObj;
5077 Platform.cacheFileData(file);
5081 file = new File(fileName);
5083 pdbfn = file.getName();
5085 else if (protocol == DataSourceType.URL)
5087 URL url = new URL(fileName);
5088 pdbfn = url.getFile();
5090 if (pdbfn.length() > 0)
5092 // attempt to find a match in the alignment
5093 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5094 int l = 0, c = pdbfn.indexOf(".");
5095 while (mtch == null && c != -1)
5100 } while ((c = pdbfn.indexOf(".", l)) > l);
5103 pdbfn = pdbfn.substring(0, l);
5105 mtch = idm.findAllIdMatches(pdbfn);
5112 type = new IdentifyFile().identify(fileObj, protocol);
5113 } catch (Exception ex)
5117 if (type != null && type.isStructureFile())
5119 filesmatched.add(new Object[] { fileObj, protocol, mtch });
5123 // File wasn't named like one of the sequences or wasn't a PDB
5125 filesnotmatched.add(fileObj);
5129 if (filesmatched.size() > 0)
5131 boolean autoAssociate = Cache
5132 .getDefault(Preferences.AUTOASSOCIATE_PDBANDSEQS, false);
5135 String msg = MessageManager.formatMessage(
5136 "label.automatically_associate_structure_files_with_sequences_same_name",
5138 { Integer.valueOf(filesmatched.size()).toString() });
5139 String ttl = MessageManager.getString(
5140 "label.automatically_associate_structure_files_by_name");
5141 int choice = JvOptionPane.showConfirmDialog(this, msg, ttl,
5142 JvOptionPane.YES_NO_OPTION);
5143 autoAssociate = choice == JvOptionPane.YES_OPTION;
5147 for (Object[] fm : filesmatched)
5149 // try and associate
5150 // TODO: may want to set a standard ID naming formalism for
5151 // associating PDB files which have no IDs.
5152 for (SequenceI toassoc : (SequenceI[]) fm[2])
5154 PDBEntry pe = AssociatePdbFileWithSeq.associatePdbWithSeq(
5155 fm[0].toString(), (DataSourceType) fm[1], toassoc,
5159 System.err.println("Associated file : " + (fm[0].toString())
5160 + " with " + toassoc.getDisplayId(true));
5165 // TODO: do we need to update overview ? only if features are
5167 alignPanel.paintAlignment(true, false);
5173 * add declined structures as sequences
5175 for (Object[] o : filesmatched)
5177 filesnotmatched.add(o[0]);
5181 if (filesnotmatched.size() > 0)
5183 if (assocfiles > 0 && (Cache
5184 .getDefault("AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
5185 || JvOptionPane.showConfirmDialog(this,
5186 "<html>" + MessageManager.formatMessage(
5187 "label.ignore_unmatched_dropped_files_info",
5189 { Integer.valueOf(filesnotmatched.size())
5192 MessageManager.getString(
5193 "label.ignore_unmatched_dropped_files"),
5194 JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
5198 for (Object fn : filesnotmatched)
5200 loadJalviewDataFile(fn, null, null, null);
5204 } catch (Exception ex)
5206 ex.printStackTrace();
5211 * Attempt to load a "dropped" file or URL string, by testing in turn for
5213 * <li>an Annotation file</li>
5214 * <li>a JNet file</li>
5215 * <li>a features file</li>
5216 * <li>else try to interpret as an alignment file</li>
5220 * either a filename or a URL string.
5221 * @throws InterruptedException
5222 * @throws IOException
5224 public void loadJalviewDataFile(Object file, DataSourceType sourceType,
5225 FileFormatI format, SequenceI assocSeq)
5227 // BH 2018 was String file
5230 if (sourceType == null)
5232 sourceType = FormatAdapter.checkProtocol(file);
5234 // if the file isn't identified, or not positively identified as some
5235 // other filetype (PFAM is default unidentified alignment file type) then
5236 // try to parse as annotation.
5237 boolean isAnnotation = (format == null
5238 || FileFormat.Pfam.equals(format))
5239 ? new AnnotationFile().annotateAlignmentView(viewport,
5245 // first see if its a T-COFFEE score file
5246 TCoffeeScoreFile tcf = null;
5249 tcf = new TCoffeeScoreFile(file, sourceType);
5252 if (tcf.annotateAlignment(viewport.getAlignment(), true))
5256 new TCoffeeColourScheme(viewport.getAlignment()));
5257 isAnnotation = true;
5258 setStatus(MessageManager.getString(
5259 "label.successfully_pasted_tcoffee_scores_to_alignment"));
5263 // some problem - if no warning its probable that the ID matching
5264 // process didn't work
5265 JvOptionPane.showMessageDialog(Desktop.getDesktopPane(),
5266 tcf.getWarningMessage() == null
5267 ? MessageManager.getString(
5268 "label.check_file_matches_sequence_ids_alignment")
5269 : tcf.getWarningMessage(),
5270 MessageManager.getString(
5271 "label.problem_reading_tcoffee_score_file"),
5272 JvOptionPane.WARNING_MESSAGE);
5279 } catch (Exception x)
5282 "Exception when processing data source as T-COFFEE score file",
5288 // try to see if its a JNet 'concise' style annotation file *before*
5290 // try to parse it as a features file
5293 format = new IdentifyFile().identify(file, sourceType);
5295 if (FileFormat.ScoreMatrix == format)
5297 ScoreMatrixFile sm = new ScoreMatrixFile(
5298 new FileParse(file, sourceType));
5300 // todo: i18n this message
5301 setStatus(MessageManager.formatMessage(
5302 "label.successfully_loaded_matrix",
5303 sm.getMatrixName()));
5305 else if (FileFormat.Jnet.equals(format))
5307 JPredFile predictions = new JPredFile(file, sourceType);
5308 new JnetAnnotationMaker();
5309 JnetAnnotationMaker.add_annotation(predictions,
5310 viewport.getAlignment(), 0, false);
5311 viewport.getAlignment().setupJPredAlignment();
5312 isAnnotation = true;
5314 // else if (IdentifyFile.FeaturesFile.equals(format))
5315 else if (FileFormat.Features.equals(format))
5317 if (parseFeaturesFile(file, sourceType))
5319 SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
5320 if (splitFrame != null)
5322 splitFrame.repaint();
5326 alignPanel.paintAlignment(true, true);
5332 new FileLoader().LoadFile(viewport, file, sourceType, format);
5339 updateForAnnotations();
5341 } catch (Exception ex)
5343 ex.printStackTrace();
5344 } catch (OutOfMemoryError oom)
5349 } catch (Exception x)
5354 + (sourceType != null
5355 ? (sourceType == DataSourceType.PASTE
5357 : "using " + sourceType + " from "
5361 ? "(parsing as '" + format + "' file)"
5363 oom, Desktop.getDesktopPane());
5368 * Do all updates necessary after an annotation file such as jnet. Also called
5369 * from Jalview.loadAppletParams for "annotations", "jnetFile"
5372 public void updateForAnnotations()
5374 alignPanel.adjustAnnotationHeight();
5375 viewport.updateSequenceIdColours();
5376 buildSortByAnnotationScoresMenu();
5377 alignPanel.paintAlignment(true, true);
5381 * Change the display state for the given feature groups -- Added by BH from
5385 * list of group strings
5387 * visible or invisible
5390 public void setFeatureGroupState(String[] groups, boolean state)
5392 jalview.api.FeatureRenderer fr = null;
5393 viewport.setShowSequenceFeatures(true);
5394 if (alignPanel != null
5395 && (fr = alignPanel.getFeatureRenderer()) != null)
5398 fr.setGroupVisibility(Arrays.asList(groups), state);
5399 alignPanel.getSeqPanel().seqCanvas.repaint();
5400 if (alignPanel.overviewPanel != null)
5402 alignPanel.overviewPanel.updateOverviewImage();
5408 * Method invoked by the ChangeListener on the tabbed pane, in other words
5409 * when a different tabbed pane is selected by the user or programmatically.
5412 public void tabSelectionChanged(int index)
5416 alignPanel = alignPanels.get(index);
5417 viewport = alignPanel.av;
5418 avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5419 setMenusFromViewport(viewport);
5420 if (featureSettings != null && featureSettings.isOpen()
5421 && featureSettings.fr.getViewport() != viewport)
5423 if (viewport.isShowSequenceFeatures())
5425 // refresh the featureSettings to reflect UI change
5426 showFeatureSettingsUI();
5430 // close feature settings for this view.
5431 featureSettings.close();
5438 * 'focus' any colour slider that is open to the selected viewport
5440 if (viewport.getConservationSelected())
5442 SliderPanel.setConservationSlider(alignPanel,
5443 viewport.getResidueShading(), alignPanel.getViewName());
5447 SliderPanel.hideConservationSlider();
5449 if (viewport.getAbovePIDThreshold())
5451 SliderPanel.setPIDSliderSource(alignPanel,
5452 viewport.getResidueShading(), alignPanel.getViewName());
5456 SliderPanel.hidePIDSlider();
5460 * If there is a frame linked to this one in a SplitPane, switch it to the
5461 * same view tab index. No infinite recursion of calls should happen, since
5462 * tabSelectionChanged() should not get invoked on setting the selected
5463 * index to an unchanged value. Guard against setting an invalid index
5464 * before the new view peer tab has been created.
5466 final AlignViewportI peer = viewport.getCodingComplement();
5469 AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5470 .getAlignPanel().alignFrame;
5471 if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5473 linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5479 * On right mouse click on view tab, prompt for and set new view name.
5482 public void tabbedPane_mousePressed(MouseEvent e)
5484 if (e.isPopupTrigger())
5486 String msg = MessageManager.getString("label.enter_view_name");
5487 String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5488 String reply = JvOptionPane.showInputDialog(msg, ttl);
5492 viewport.setViewName(reply);
5493 // TODO warn if reply is in getExistingViewNames()?
5494 tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5499 public AlignViewport getCurrentView()
5505 * Open the dialog for regex description parsing.
5508 protected void extractScores_actionPerformed(ActionEvent e)
5510 ParseProperties pp = new jalview.analysis.ParseProperties(
5511 viewport.getAlignment());
5512 // TODO: verify regex and introduce GUI dialog for version 2.5
5513 // if (pp.getScoresFromDescription("col", "score column ",
5514 // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5516 if (pp.getScoresFromDescription("description column",
5517 "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5519 buildSortByAnnotationScoresMenu();
5527 * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5531 protected void showDbRefs_actionPerformed(ActionEvent e)
5533 viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5539 * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5543 protected void showNpFeats_actionPerformed(ActionEvent e)
5545 viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5549 * find the viewport amongst the tabs in this alignment frame and close that
5554 public boolean closeView(AlignViewportI av)
5558 this.closeMenuItem_actionPerformed(false);
5561 Component[] comp = tabbedPane.getComponents();
5562 for (int i = 0; comp != null && i < comp.length; i++)
5564 if (comp[i] instanceof AlignmentPanel)
5566 if (((AlignmentPanel) comp[i]).av == av)
5569 closeView((AlignmentPanel) comp[i]);
5577 protected void build_fetchdbmenu(JMenu webService)
5579 // Temporary hack - DBRef Fetcher always top level ws entry.
5580 // TODO We probably want to store a sequence database checklist in
5581 // preferences and have checkboxes.. rather than individual sources selected
5583 final JMenu rfetch = new JMenu(
5584 MessageManager.getString("action.fetch_db_references"));
5585 rfetch.setToolTipText(MessageManager.getString(
5586 "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5587 webService.add(rfetch);
5589 final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5590 MessageManager.getString("option.trim_retrieved_seqs"));
5591 trimrs.setToolTipText(
5592 MessageManager.getString("label.trim_retrieved_sequences"));
5594 Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5595 trimrs.addActionListener(new ActionListener()
5598 public void actionPerformed(ActionEvent e)
5600 trimrs.setSelected(trimrs.isSelected());
5601 Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5602 Boolean.valueOf(trimrs.isSelected()).toString());
5606 JMenuItem fetchr = new JMenuItem(
5607 MessageManager.getString("label.standard_databases"));
5608 fetchr.setToolTipText(
5609 MessageManager.getString("label.fetch_embl_uniprot"));
5610 fetchr.addActionListener(new ActionListener()
5614 public void actionPerformed(ActionEvent e)
5616 new Thread(new Runnable()
5621 boolean isNucleotide = alignPanel.alignFrame.getViewport()
5622 .getAlignment().isNucleotide();
5623 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5624 alignPanel.av.getSequenceSelection(),
5625 alignPanel.alignFrame, null,
5626 alignPanel.alignFrame.featureSettings, isNucleotide);
5627 dbRefFetcher.addListener(new FetchFinishedListenerI()
5630 public void finished()
5633 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5634 .getFeatureSettingsModels())
5637 alignPanel.av.mergeFeaturesStyle(srcSettings);
5639 AlignFrame.this.setMenusForViewport();
5642 dbRefFetcher.fetchDBRefs(false);
5650 new Thread(new Runnable()
5656 // final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5657 // .getSequenceFetcherSingleton();
5658 javax.swing.SwingUtilities.invokeLater(new Runnable()
5663 jalview.ws.SequenceFetcher sf = jalview.ws.SequenceFetcher
5665 String[] dbclasses = sf.getNonAlignmentSources();
5666 List<DbSourceProxy> otherdb;
5667 JMenu dfetch = new JMenu();
5668 JMenu ifetch = new JMenu();
5669 JMenuItem fetchr = null;
5670 int comp = 0, icomp = 0, mcomp = 15;
5671 String mname = null;
5673 for (String dbclass : dbclasses)
5675 otherdb = sf.getSourceProxy(dbclass);
5676 // add a single entry for this class, or submenu allowing 'fetch
5678 if (otherdb == null || otherdb.size() < 1)
5684 mname = "From " + dbclass;
5686 if (otherdb.size() == 1)
5688 DbSourceProxy src = otherdb.get(0);
5689 DbSourceProxy[] dassource = new DbSourceProxy[] { src };
5690 fetchr = new JMenuItem(src.getDbSource());
5691 fetchr.addActionListener(new ActionListener()
5695 public void actionPerformed(ActionEvent e)
5697 new Thread(new Runnable()
5703 boolean isNucleotide = alignPanel.alignFrame
5704 .getViewport().getAlignment()
5706 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5707 alignPanel.av.getSequenceSelection(),
5708 alignPanel.alignFrame, dassource,
5709 alignPanel.alignFrame.featureSettings,
5712 .addListener(new FetchFinishedListenerI()
5715 public void finished()
5717 FeatureSettingsModelI srcSettings = dassource[0]
5718 .getFeatureColourScheme();
5719 alignPanel.av.mergeFeaturesStyle(
5721 AlignFrame.this.setMenusForViewport();
5724 dbRefFetcher.fetchDBRefs(false);
5730 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5731 MessageManager.formatMessage(
5732 "label.fetch_retrieve_from", new Object[]
5733 { src.getDbName() })));
5739 final DbSourceProxy[] dassource = otherdb
5740 .toArray(new DbSourceProxy[0]);
5742 DbSourceProxy src = otherdb.get(0);
5743 fetchr = new JMenuItem(MessageManager
5744 .formatMessage("label.fetch_all_param", new Object[]
5745 { src.getDbSource() }));
5746 fetchr.addActionListener(new ActionListener()
5749 public void actionPerformed(ActionEvent e)
5751 new Thread(new Runnable()
5757 boolean isNucleotide = alignPanel.alignFrame
5758 .getViewport().getAlignment()
5760 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5761 alignPanel.av.getSequenceSelection(),
5762 alignPanel.alignFrame, dassource,
5763 alignPanel.alignFrame.featureSettings,
5766 .addListener(new FetchFinishedListenerI()
5769 public void finished()
5771 AlignFrame.this.setMenusForViewport();
5774 dbRefFetcher.fetchDBRefs(false);
5780 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5781 MessageManager.formatMessage(
5782 "label.fetch_retrieve_from_all_sources",
5784 { Integer.valueOf(otherdb.size())
5786 src.getDbSource(), src.getDbName() })));
5789 // and then build the rest of the individual menus
5790 ifetch = new JMenu(MessageManager.formatMessage(
5791 "label.source_from_db_source", new Object[]
5792 { src.getDbSource() }));
5794 String imname = null;
5796 for (DbSourceProxy sproxy : otherdb)
5798 String dbname = sproxy.getDbName();
5799 String sname = dbname.length() > 5
5800 ? dbname.substring(0, 5) + "..."
5802 String msname = dbname.length() > 10
5803 ? dbname.substring(0, 10) + "..."
5807 imname = MessageManager
5808 .formatMessage("label.from_msname", new Object[]
5811 fetchr = new JMenuItem(msname);
5812 final DbSourceProxy[] dassrc = { sproxy };
5813 fetchr.addActionListener(new ActionListener()
5817 public void actionPerformed(ActionEvent e)
5819 new Thread(new Runnable()
5825 boolean isNucleotide = alignPanel.alignFrame
5826 .getViewport().getAlignment()
5828 DBRefFetcher dbRefFetcher = new DBRefFetcher(
5829 alignPanel.av.getSequenceSelection(),
5830 alignPanel.alignFrame, dassrc,
5831 alignPanel.alignFrame.featureSettings,
5834 .addListener(new FetchFinishedListenerI()
5837 public void finished()
5839 AlignFrame.this.setMenusForViewport();
5842 dbRefFetcher.fetchDBRefs(false);
5848 fetchr.setToolTipText(
5849 "<html>" + MessageManager.formatMessage(
5850 "label.fetch_retrieve_from", new Object[]
5854 if (++icomp >= mcomp || i == (otherdb.size()))
5856 ifetch.setText(MessageManager.formatMessage(
5857 "label.source_to_target", imname, sname));
5859 ifetch = new JMenu();
5867 if (comp >= mcomp || dbi >= (dbclasses.length))
5869 dfetch.setText(MessageManager.formatMessage(
5870 "label.source_to_target", mname, dbclass));
5872 dfetch = new JMenu();
5885 * Left justify the whole alignment.
5888 protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5890 viewport.getAlignment().justify(false);
5891 viewport.notifyAlignment();
5895 * Right justify the whole alignment.
5898 protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5900 viewport.getAlignment().justify(true);
5901 viewport.notifyAlignment();
5905 public void setShowSeqFeatures(boolean b)
5907 showSeqFeatures.setSelected(b);
5908 viewport.setShowSequenceFeatures(b);
5915 * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5916 * awt.event.ActionEvent)
5919 protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5921 viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5922 alignPanel.paintAlignment(false, false);
5929 * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5933 protected void showGroupConsensus_actionPerformed(ActionEvent e)
5935 viewport.setShowGroupConsensus(showGroupConsensus.getState());
5936 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5944 * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5945 * .event.ActionEvent)
5948 protected void showGroupConservation_actionPerformed(ActionEvent e)
5950 viewport.setShowGroupConservation(showGroupConservation.getState());
5951 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5958 * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5959 * .event.ActionEvent)
5962 protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5964 viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5965 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5972 * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5973 * .event.ActionEvent)
5976 protected void showSequenceLogo_actionPerformed(ActionEvent e)
5978 viewport.setShowSequenceLogo(showSequenceLogo.getState());
5979 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5983 protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5985 showSequenceLogo.setState(true);
5986 viewport.setShowSequenceLogo(true);
5987 viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5988 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5992 protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5994 alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
6001 * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
6002 * .event.ActionEvent)
6005 protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
6007 if (avc.makeGroupsFromSelection())
6009 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6010 alignPanel.updateAnnotation();
6011 alignPanel.paintAlignment(true,
6012 viewport.needToUpdateStructureViews());
6016 public void clearAlignmentSeqRep()
6018 // TODO refactor alignmentseqrep to controller
6019 if (viewport.getAlignment().hasSeqrep())
6021 viewport.getAlignment().setSeqrep(null);
6022 PaintRefresher.Refresh(this, viewport.getSequenceSetId());
6023 alignPanel.updateAnnotation();
6024 alignPanel.paintAlignment(true, true);
6029 protected void createGroup_actionPerformed(ActionEvent e)
6031 if (avc.createGroup())
6033 if (applyAutoAnnotationSettings.isSelected())
6035 alignPanel.updateAnnotation(true, false);
6037 alignPanel.alignmentChanged();
6042 protected void unGroup_actionPerformed(ActionEvent e)
6046 alignPanel.alignmentChanged();
6051 * make the given alignmentPanel the currently selected tab
6053 * @param alignmentPanel
6055 public void setDisplayedView(AlignmentPanel alignmentPanel)
6057 if (!viewport.getSequenceSetId()
6058 .equals(alignmentPanel.av.getSequenceSetId()))
6060 throw new Error(MessageManager.getString(
6061 "error.implementation_error_cannot_show_view_alignment_frame"));
6063 if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
6064 .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
6066 tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
6071 * Action on selection of menu options to Show or Hide annotations.
6074 * @param forSequences
6075 * update sequence-related annotations
6076 * @param forAlignment
6077 * update non-sequence-related annotations
6080 protected void setAnnotationsVisibility(boolean visible,
6081 boolean forSequences, boolean forAlignment)
6083 AlignmentAnnotation[] anns = alignPanel.getAlignment()
6084 .getAlignmentAnnotation();
6089 for (AlignmentAnnotation aa : anns)
6092 * don't display non-positional annotations on an alignment
6094 if (aa.annotations == null)
6098 boolean apply = (aa.sequenceRef == null && forAlignment)
6099 || (aa.sequenceRef != null && forSequences);
6102 aa.visible = visible;
6105 alignPanel.validateAnnotationDimensions(true);
6106 alignPanel.alignmentChanged();
6110 * Store selected annotation sort order for the view and repaint.
6113 protected void sortAnnotations_actionPerformed()
6115 this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
6117 .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
6118 alignPanel.paintAlignment(false, false);
6123 * @return alignment panels in this alignment frame
6125 public List<? extends AlignmentViewPanel> getAlignPanels()
6127 // alignPanels is never null
6128 // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
6133 * Open a new alignment window, with the cDNA associated with this (protein)
6134 * alignment, aligned as is the protein.
6136 protected void viewAsCdna_actionPerformed()
6138 // TODO no longer a menu action - refactor as required
6139 final AlignmentI alignment = getViewport().getAlignment();
6140 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
6141 if (mappings == null)
6145 List<SequenceI> cdnaSeqs = new ArrayList<>();
6146 for (SequenceI aaSeq : alignment.getSequences())
6148 for (AlignedCodonFrame acf : mappings)
6150 SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
6154 * There is a cDNA mapping for this protein sequence - add to new
6155 * alignment. It will share the same dataset sequence as other mapped
6156 * cDNA (no new mappings need to be created).
6158 final Sequence newSeq = new Sequence(dnaSeq);
6159 newSeq.setDatasetSequence(dnaSeq);
6160 cdnaSeqs.add(newSeq);
6164 if (cdnaSeqs.size() == 0)
6166 // show a warning dialog no mapped cDNA
6169 AlignmentI cdna = new Alignment(
6170 cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
6171 GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
6172 AlignFrame.DEFAULT_HEIGHT);
6173 cdna.alignAs(alignment);
6174 String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
6176 Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
6177 AlignFrame.DEFAULT_HEIGHT);
6181 * Set visibility of dna/protein complement view (available when shown in a
6187 protected void showComplement_actionPerformed(boolean show)
6189 SplitContainerI sf = getSplitViewContainer();
6192 sf.setComplementVisible(this, show);
6197 * Generate the reverse (optionally complemented) of the selected sequences,
6198 * and add them to the alignment
6201 protected void showReverse_actionPerformed(boolean complement)
6203 AlignmentI al = null;
6206 Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
6207 al = dna.reverseCdna(complement);
6208 viewport.addAlignment(al, "");
6209 addHistoryItem(new EditCommand(
6210 MessageManager.getString("label.add_sequences"), Action.PASTE,
6211 al.getSequencesArray(), 0, al.getWidth(),
6212 viewport.getAlignment()));
6213 } catch (Exception ex)
6215 System.err.println(ex.getMessage());
6221 * Try to run a script in the Groovy console, having first ensured that this
6222 * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
6223 * be targeted at this alignment.
6226 protected void runGroovy_actionPerformed()
6228 Jalview.setCurrentAlignFrame(this);
6229 groovy.ui.Console console = Desktop.getGroovyConsole();
6230 if (console != null)
6234 console.runScript();
6235 } catch (Exception ex)
6237 System.err.println((ex.toString()));
6238 JvOptionPane.showInternalMessageDialog(Desktop.getDesktopPane(),
6239 MessageManager.getString("label.couldnt_run_groovy_script"),
6240 MessageManager.getString("label.groovy_support_failed"),
6241 JvOptionPane.ERROR_MESSAGE);
6246 System.err.println("Can't run Groovy script as console not found");
6251 * Hides columns containing (or not containing) a specified feature, provided
6252 * that would not leave all columns hidden
6254 * @param featureType
6255 * @param columnsContaining
6258 public boolean hideFeatureColumns(String featureType,
6259 boolean columnsContaining)
6261 boolean notForHiding = avc.markColumnsContainingFeatures(
6262 columnsContaining, false, false, featureType);
6265 if (avc.markColumnsContainingFeatures(!columnsContaining, false,
6266 false, featureType))
6268 getViewport().hideSelectedColumns();
6276 protected void selectHighlightedColumns_actionPerformed(
6277 ActionEvent actionEvent)
6279 // include key modifier check in case user selects from menu
6280 avc.markHighlightedColumns(
6281 (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
6282 (actionEvent.getModifiers() & (ActionEvent.META_MASK
6283 | ActionEvent.CTRL_MASK)) != 0);
6287 * Rebuilds the Colour menu, including any user-defined colours which have
6288 * been loaded either on startup or during the session
6290 public void buildColourMenu()
6292 colourMenu.removeAll();
6294 colourMenu.add(applyToAllGroups);
6295 colourMenu.add(textColour);
6296 colourMenu.addSeparator();
6298 ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
6299 viewport.getAlignment(), false);
6301 colourMenu.add(annotationColour);
6302 bg.add(annotationColour);
6303 colourMenu.addSeparator();
6304 colourMenu.add(conservationMenuItem);
6305 colourMenu.add(modifyConservation);
6306 colourMenu.add(abovePIDThreshold);
6307 colourMenu.add(modifyPID);
6309 ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
6310 ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
6314 * Open a dialog (if not already open) that allows the user to select and
6315 * calculate PCA or Tree analysis
6317 protected void openTreePcaDialog()
6319 if (alignPanel.getCalculationDialog() == null)
6321 new CalculationChooser(AlignFrame.this);
6326 * Sets the status of the HMMER menu
6328 public void updateHMMERStatus()
6330 hmmerMenu.setEnabled(HmmerCommand.isHmmerAvailable());
6333 protected void loadVcf_actionPerformed()
6335 JalviewFileChooser chooser = new JalviewFileChooser(
6336 Cache.getProperty("LAST_DIRECTORY"));
6337 chooser.setFileView(new JalviewFileView());
6338 chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
6339 chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
6340 final AlignFrame us = this;
6341 chooser.setResponseHandler(0, new Runnable()
6346 String choice = chooser.getSelectedFile().getPath();
6347 Cache.setProperty("LAST_DIRECTORY", choice);
6348 SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
6349 new VCFLoader(choice).loadVCF(seqs, us);
6352 chooser.showOpenDialog(null);
6356 private Rectangle lastFeatureSettingsBounds = null;
6359 public void setFeatureSettingsGeometry(Rectangle bounds)
6361 lastFeatureSettingsBounds = bounds;
6365 public Rectangle getFeatureSettingsGeometry()
6367 return lastFeatureSettingsBounds;
6370 public void scrollTo(int row, int column)
6372 alignPanel.getSeqPanel().scrollTo(row, column);
6375 public void scrollToRow(int row)
6377 alignPanel.getSeqPanel().scrollToRow(row);
6380 public void scrollToColumn(int column)
6382 alignPanel.getSeqPanel().scrollToColumn(column);
6386 * BH 2019 from JalviewLite
6388 * get sequence feature groups that are hidden or shown
6395 public String[] getFeatureGroupsOfState(boolean visible)
6397 jalview.api.FeatureRenderer fr = null;
6398 if (alignPanel != null
6399 && (fr = alignPanel.getFeatureRenderer()) != null)
6401 List<String> gps = fr.getGroups(visible);
6402 String[] _gps = gps.toArray(new String[gps.size()]);
6410 * @return list of feature groups on the view
6413 public String[] getFeatureGroups()
6415 jalview.api.FeatureRenderer fr = null;
6416 if (alignPanel != null
6417 && (fr = alignPanel.getFeatureRenderer()) != null)
6419 List<String> gps = fr.getFeatureGroups();
6420 String[] _gps = gps.toArray(new String[gps.size()]);
6426 public void select(SequenceGroup sel, ColumnSelection csel,
6427 HiddenColumns hidden)
6429 alignPanel.getSeqPanel().selection(sel, csel, hidden, null);
6437 static class PrintThread extends Thread
6441 public PrintThread(AlignmentPanel ap)
6446 static PageFormat pf;
6451 PrinterJob printJob = PrinterJob.getPrinterJob();
6455 printJob.setPrintable(ap, pf);
6459 printJob.setPrintable(ap);
6462 if (printJob.printDialog())
6467 } catch (Exception PrintException)
6469 PrintException.printStackTrace();