JAL-3982 highlight any 3D structure mappings for positions mapped via CDS/transcript...
[jalview.git] / src / jalview / gui / AlignFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import java.util.Locale;
24
25 import java.awt.BorderLayout;
26 import java.awt.Color;
27 import java.awt.Component;
28 import java.awt.Rectangle;
29 import java.awt.Toolkit;
30 import java.awt.datatransfer.Clipboard;
31 import java.awt.datatransfer.DataFlavor;
32 import java.awt.datatransfer.StringSelection;
33 import java.awt.datatransfer.Transferable;
34 import java.awt.dnd.DnDConstants;
35 import java.awt.dnd.DropTargetDragEvent;
36 import java.awt.dnd.DropTargetDropEvent;
37 import java.awt.dnd.DropTargetEvent;
38 import java.awt.dnd.DropTargetListener;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.FocusAdapter;
42 import java.awt.event.FocusEvent;
43 import java.awt.event.ItemEvent;
44 import java.awt.event.ItemListener;
45 import java.awt.event.KeyAdapter;
46 import java.awt.event.KeyEvent;
47 import java.awt.event.MouseEvent;
48 import java.awt.print.PageFormat;
49 import java.awt.print.PrinterJob;
50 import java.beans.PropertyChangeEvent;
51 import java.io.File;
52 import java.io.FileWriter;
53 import java.io.IOException;
54 import java.io.PrintWriter;
55 import java.net.URL;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Deque;
59 import java.util.Enumeration;
60 import java.util.HashMap;
61 import java.util.Hashtable;
62 import java.util.List;
63 import java.util.Map;
64 import java.util.Vector;
65 import java.util.concurrent.CompletableFuture;
66
67 import javax.swing.ButtonGroup;
68 import javax.swing.JCheckBoxMenuItem;
69 import javax.swing.JComponent;
70 import javax.swing.JEditorPane;
71 import javax.swing.JInternalFrame;
72 import javax.swing.JLabel;
73 import javax.swing.JLayeredPane;
74 import javax.swing.JMenu;
75 import javax.swing.JMenuItem;
76 import javax.swing.JPanel;
77 import javax.swing.JScrollPane;
78 import javax.swing.SwingUtilities;
79
80 import ext.vamsas.ServiceHandle;
81 import jalview.analysis.AlignmentSorter;
82 import jalview.analysis.AlignmentUtils;
83 import jalview.analysis.CrossRef;
84 import jalview.analysis.Dna;
85 import jalview.analysis.GeneticCodeI;
86 import jalview.analysis.ParseProperties;
87 import jalview.analysis.SequenceIdMatcher;
88 import jalview.api.AlignExportSettingsI;
89 import jalview.api.AlignViewControllerGuiI;
90 import jalview.api.AlignViewControllerI;
91 import jalview.api.AlignViewportI;
92 import jalview.api.AlignmentViewPanel;
93 import jalview.api.FeatureSettingsControllerI;
94 import jalview.api.FeatureSettingsModelI;
95 import jalview.api.SplitContainerI;
96 import jalview.api.ViewStyleI;
97 import jalview.api.analysis.SimilarityParamsI;
98 import jalview.bin.Cache;
99 import jalview.bin.Console;
100 import jalview.bin.Jalview;
101 import jalview.commands.CommandI;
102 import jalview.commands.EditCommand;
103 import jalview.commands.EditCommand.Action;
104 import jalview.commands.OrderCommand;
105 import jalview.commands.RemoveGapColCommand;
106 import jalview.commands.RemoveGapsCommand;
107 import jalview.commands.SlideSequencesCommand;
108 import jalview.commands.TrimRegionCommand;
109 import jalview.datamodel.AlignExportSettingsAdapter;
110 import jalview.datamodel.AlignedCodonFrame;
111 import jalview.datamodel.Alignment;
112 import jalview.datamodel.AlignmentAnnotation;
113 import jalview.datamodel.AlignmentExportData;
114 import jalview.datamodel.AlignmentI;
115 import jalview.datamodel.AlignmentOrder;
116 import jalview.datamodel.AlignmentView;
117 import jalview.datamodel.ColumnSelection;
118 import jalview.datamodel.HiddenColumns;
119 import jalview.datamodel.PDBEntry;
120 import jalview.datamodel.SeqCigar;
121 import jalview.datamodel.Sequence;
122 import jalview.datamodel.SequenceGroup;
123 import jalview.datamodel.SequenceI;
124 import jalview.gui.ColourMenuHelper.ColourChangeListener;
125 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
126 import jalview.io.AlignmentProperties;
127 import jalview.io.AnnotationFile;
128 import jalview.io.BackupFiles;
129 import jalview.io.BioJsHTMLOutput;
130 import jalview.io.DataSourceType;
131 import jalview.io.FileFormat;
132 import jalview.io.FileFormatI;
133 import jalview.io.FileFormats;
134 import jalview.io.FileLoader;
135 import jalview.io.FileParse;
136 import jalview.io.FormatAdapter;
137 import jalview.io.HtmlSvgOutput;
138 import jalview.io.IdentifyFile;
139 import jalview.io.JPredFile;
140 import jalview.io.JalviewFileChooser;
141 import jalview.io.JalviewFileView;
142 import jalview.io.JnetAnnotationMaker;
143 import jalview.io.NewickFile;
144 import jalview.io.ScoreMatrixFile;
145 import jalview.io.TCoffeeScoreFile;
146 import jalview.io.vcf.VCFLoader;
147 import jalview.jbgui.GAlignFrame;
148 import jalview.project.Jalview2XML;
149 import jalview.schemes.ColourSchemeI;
150 import jalview.schemes.ColourSchemes;
151 import jalview.schemes.ResidueColourScheme;
152 import jalview.schemes.TCoffeeColourScheme;
153 import jalview.util.HttpUtils;
154 import jalview.util.ImageMaker.TYPE;
155 import jalview.util.MessageManager;
156 import jalview.util.Platform;
157 import jalview.viewmodel.AlignmentViewport;
158 import jalview.viewmodel.ViewportRanges;
159 import jalview.ws.DBRefFetcher;
160 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
161 import jalview.ws.jws1.Discoverer;
162 import jalview.ws.jws2.Jws2Discoverer;
163 import jalview.ws.jws2.jabaws2.Jws2Instance;
164 import jalview.ws.seqfetcher.DbSourceProxy;
165
166 /**
167  * DOCUMENT ME!
168  * 
169  * @author $author$
170  * @version $Revision$
171  */
172 @SuppressWarnings("serial")
173 public class AlignFrame extends GAlignFrame implements DropTargetListener,
174         IProgressIndicator, AlignViewControllerGuiI, ColourChangeListener
175 {
176
177   public static final int DEFAULT_WIDTH = 700;
178
179   public static final int DEFAULT_HEIGHT = 500;
180
181   /*
182    * The currently displayed panel (selected tabbed view if more than one)
183    */
184   public AlignmentPanel alignPanel;
185
186   AlignViewport viewport;
187
188   public AlignViewControllerI avc;
189
190   List<AlignmentPanel> alignPanels = new ArrayList<>();
191
192   /**
193    * Last format used to load or save alignments in this window
194    */
195   FileFormatI currentFileFormat = null;
196
197   /**
198    * Current filename for this alignment
199    */
200   String fileName = null;
201
202   File fileObject;
203
204   /**
205    * Creates a new AlignFrame object with specific width and height.
206    * 
207    * @param al
208    * @param width
209    * @param height
210    */
211   public AlignFrame(AlignmentI al, int width, int height)
212   {
213     this(al, null, width, height);
214   }
215
216   /**
217    * Creates a new AlignFrame object with specific width, height and
218    * sequenceSetId
219    * 
220    * @param al
221    * @param width
222    * @param height
223    * @param sequenceSetId
224    */
225   public AlignFrame(AlignmentI al, int width, int height,
226           String sequenceSetId)
227   {
228     this(al, null, width, height, sequenceSetId);
229   }
230
231   /**
232    * Creates a new AlignFrame object with specific width, height and
233    * sequenceSetId
234    * 
235    * @param al
236    * @param width
237    * @param height
238    * @param sequenceSetId
239    * @param viewId
240    */
241   public AlignFrame(AlignmentI al, int width, int height,
242           String sequenceSetId, String viewId)
243   {
244     this(al, null, width, height, sequenceSetId, viewId);
245   }
246
247   /**
248    * new alignment window with hidden columns
249    * 
250    * @param al
251    *          AlignmentI
252    * @param hiddenColumns
253    *          ColumnSelection or null
254    * @param width
255    *          Width of alignment frame
256    * @param height
257    *          height of frame.
258    */
259   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
260           int height)
261   {
262     this(al, hiddenColumns, width, height, null);
263   }
264
265   /**
266    * Create alignment frame for al with hiddenColumns, a specific width and
267    * height, and specific sequenceId
268    * 
269    * @param al
270    * @param hiddenColumns
271    * @param width
272    * @param height
273    * @param sequenceSetId
274    *          (may be null)
275    */
276   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
277           int height, String sequenceSetId)
278   {
279     this(al, hiddenColumns, width, height, sequenceSetId, null);
280   }
281
282   /**
283    * Create alignment frame for al with hiddenColumns, a specific width and
284    * height, and specific sequenceId
285    * 
286    * @param al
287    * @param hiddenColumns
288    * @param width
289    * @param height
290    * @param sequenceSetId
291    *          (may be null)
292    * @param viewId
293    *          (may be null)
294    */
295   public AlignFrame(AlignmentI al, HiddenColumns hiddenColumns, int width,
296           int height, String sequenceSetId, String viewId)
297   {
298     setSize(width, height);
299
300     if (al.getDataset() == null)
301     {
302       al.setDataset(null);
303     }
304
305     viewport = new AlignViewport(al, hiddenColumns, sequenceSetId, viewId);
306
307     alignPanel = new AlignmentPanel(this, viewport);
308
309     addAlignmentPanel(alignPanel, true);
310     init();
311   }
312
313   public AlignFrame(AlignmentI al, SequenceI[] hiddenSeqs,
314           HiddenColumns hiddenColumns, int width, int height)
315   {
316     setSize(width, height);
317
318     if (al.getDataset() == null)
319     {
320       al.setDataset(null);
321     }
322
323     viewport = new AlignViewport(al, hiddenColumns);
324
325     if (hiddenSeqs != null && hiddenSeqs.length > 0)
326     {
327       viewport.hideSequence(hiddenSeqs);
328     }
329     alignPanel = new AlignmentPanel(this, viewport);
330     addAlignmentPanel(alignPanel, true);
331     init();
332   }
333
334   /**
335    * Make a new AlignFrame from existing alignmentPanels
336    * 
337    * @param ap
338    *          AlignmentPanel
339    * @param av
340    *          AlignViewport
341    */
342   public AlignFrame(AlignmentPanel ap)
343   {
344     viewport = ap.av;
345     alignPanel = ap;
346     addAlignmentPanel(ap, false);
347     init();
348   }
349
350   /**
351    * initalise the alignframe from the underlying viewport data and the
352    * configurations
353    */
354   void init()
355   {
356     // setBackground(Color.white); // BH 2019
357
358     if (!Jalview.isHeadlessMode())
359     {
360       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
361     }
362
363     avc = new jalview.controller.AlignViewController(this, viewport,
364             alignPanel);
365     if (viewport.getAlignmentConservationAnnotation() == null)
366     {
367       // BLOSUM62Colour.setEnabled(false);
368       conservationMenuItem.setEnabled(false);
369       modifyConservation.setEnabled(false);
370       // PIDColour.setEnabled(false);
371       // abovePIDThreshold.setEnabled(false);
372       // modifyPID.setEnabled(false);
373     }
374
375     String sortby = Cache.getDefault("SORT_ALIGNMENT", "No sort");
376
377     if (sortby.equals("Id"))
378     {
379       sortIDMenuItem_actionPerformed(null);
380     }
381     else if (sortby.equals("Pairwise Identity"))
382     {
383       sortPairwiseMenuItem_actionPerformed(null);
384     }
385
386     this.alignPanel.av
387             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
388
389     setMenusFromViewport(viewport);
390     buildSortByAnnotationScoresMenu();
391     calculateTree.addActionListener(new ActionListener()
392     {
393
394       @Override
395       public void actionPerformed(ActionEvent e)
396       {
397         openTreePcaDialog();
398       }
399     });
400     buildColourMenu();
401
402     if (Desktop.desktop != null)
403     {
404       this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
405       if (!Platform.isJS())
406       {
407         addServiceListeners();
408       }
409       setGUINucleotide();
410     }
411
412     if (viewport.getWrapAlignment())
413     {
414       wrapMenuItem_actionPerformed(null);
415     }
416
417     if (Cache.getDefault("SHOW_OVERVIEW", false))
418     {
419       this.overviewMenuItem_actionPerformed(null);
420     }
421
422     addKeyListener();
423
424     final List<AlignmentViewPanel> selviews = new ArrayList<>();
425     final List<AlignmentPanel> origview = new ArrayList<>();
426     final String menuLabel = MessageManager
427             .getString("label.copy_format_from");
428     ViewSelectionMenu vsel = new ViewSelectionMenu(menuLabel,
429             new ViewSetProvider()
430             {
431
432               @Override
433               public AlignmentPanel[] getAllAlignmentPanels()
434               {
435                 origview.clear();
436                 origview.add(alignPanel);
437                 // make an array of all alignment panels except for this one
438                 List<AlignmentPanel> aps = new ArrayList<>(
439                         Arrays.asList(Desktop.getAlignmentPanels(null)));
440                 aps.remove(AlignFrame.this.alignPanel);
441                 return aps.toArray(new AlignmentPanel[aps.size()]);
442               }
443             }, selviews, new ItemListener()
444             {
445
446               @Override
447               public void itemStateChanged(ItemEvent e)
448               {
449                 if (origview.size() > 0)
450                 {
451                   final AlignmentPanel ap = origview.get(0);
452
453                   /*
454                    * Copy the ViewStyle of the selected panel to 'this one'.
455                    * Don't change value of 'scaleProteinAsCdna' unless copying
456                    * from a SplitFrame.
457                    */
458                   ViewStyleI vs = selviews.get(0).getAlignViewport()
459                           .getViewStyle();
460                   boolean fromSplitFrame = selviews.get(0)
461                           .getAlignViewport().getCodingComplement() != null;
462                   if (!fromSplitFrame)
463                   {
464                     vs.setScaleProteinAsCdna(ap.getAlignViewport()
465                             .getViewStyle().isScaleProteinAsCdna());
466                   }
467                   ap.getAlignViewport().setViewStyle(vs);
468
469                   /*
470                    * Also rescale ViewStyle of SplitFrame complement if there is
471                    * one _and_ it is set to 'scaledProteinAsCdna'; we don't copy
472                    * the whole ViewStyle (allow cDNA protein to have different
473                    * fonts)
474                    */
475                   AlignViewportI complement = ap.getAlignViewport()
476                           .getCodingComplement();
477                   if (complement != null && vs.isScaleProteinAsCdna())
478                   {
479                     AlignFrame af = Desktop.getAlignFrameFor(complement);
480                     ((SplitFrame) af.getSplitViewContainer())
481                             .adjustLayout();
482                     af.setMenusForViewport();
483                   }
484
485                   ap.updateLayout();
486                   ap.setSelected(true);
487                   ap.alignFrame.setMenusForViewport();
488
489                 }
490               }
491             });
492     if (Cache.getDefault("VERSION", "DEVELOPMENT").toLowerCase(Locale.ROOT)
493             .indexOf("devel") > -1
494             || Cache.getDefault("VERSION", "DEVELOPMENT")
495                     .toLowerCase(Locale.ROOT).indexOf("test") > -1)
496     {
497       formatMenu.add(vsel);
498     }
499     addFocusListener(new FocusAdapter()
500     {
501       @Override
502       public void focusGained(FocusEvent e)
503       {
504         Jalview.setCurrentAlignFrame(AlignFrame.this);
505       }
506     });
507
508   }
509
510   /**
511    * Change the filename and format for the alignment, and enable the 'reload'
512    * button functionality.
513    * 
514    * @param file
515    *          valid filename
516    * @param format
517    *          format of file
518    */
519   public void setFileName(String file, FileFormatI format)
520   {
521     fileName = file;
522     setFileFormat(format);
523     reload.setEnabled(true);
524   }
525
526   /**
527    * JavaScript will have this, maybe others. More dependable than a file name
528    * and maintains a reference to the actual bytes loaded.
529    * 
530    * @param file
531    */
532   public void setFileObject(File file)
533   {
534     this.fileObject = file;
535   }
536
537   /**
538    * Add a KeyListener with handlers for various KeyPressed and KeyReleased
539    * events
540    */
541   void addKeyListener()
542   {
543     addKeyListener(new KeyAdapter()
544     {
545       @Override
546       public void keyPressed(KeyEvent evt)
547       {
548         if (viewport.cursorMode
549                 && ((evt.getKeyCode() >= KeyEvent.VK_0
550                         && evt.getKeyCode() <= KeyEvent.VK_9)
551                         || (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0
552                                 && evt.getKeyCode() <= KeyEvent.VK_NUMPAD9))
553                 && Character.isDigit(evt.getKeyChar()))
554         {
555           alignPanel.getSeqPanel().numberPressed(evt.getKeyChar());
556         }
557
558         switch (evt.getKeyCode())
559         {
560
561         case 27: // escape key
562           deselectAllSequenceMenuItem_actionPerformed(null);
563
564           break;
565
566         case KeyEvent.VK_DOWN:
567           if (evt.isAltDown() || !viewport.cursorMode)
568           {
569             moveSelectedSequences(false);
570           }
571           if (viewport.cursorMode)
572           {
573             alignPanel.getSeqPanel().moveCursor(0, 1, evt.isShiftDown());
574           }
575           break;
576
577         case KeyEvent.VK_UP:
578           if (evt.isAltDown() || !viewport.cursorMode)
579           {
580             moveSelectedSequences(true);
581           }
582           if (viewport.cursorMode)
583           {
584             alignPanel.getSeqPanel().moveCursor(0, -1, evt.isShiftDown());
585           }
586
587           break;
588
589         case KeyEvent.VK_LEFT:
590           if (evt.isAltDown() || !viewport.cursorMode)
591           {
592             slideSequences(false,
593                     alignPanel.getSeqPanel().getKeyboardNo1());
594           }
595           else
596           {
597             alignPanel.getSeqPanel().moveCursor(-1, 0, evt.isShiftDown());
598           }
599
600           break;
601
602         case KeyEvent.VK_RIGHT:
603           if (evt.isAltDown() || !viewport.cursorMode)
604           {
605             slideSequences(true, alignPanel.getSeqPanel().getKeyboardNo1());
606           }
607           else
608           {
609             alignPanel.getSeqPanel().moveCursor(1, 0, evt.isShiftDown());
610           }
611           break;
612
613         case KeyEvent.VK_SPACE:
614           if (viewport.cursorMode)
615           {
616             alignPanel.getSeqPanel().insertGapAtCursor(evt.isControlDown()
617                     || evt.isShiftDown() || evt.isAltDown());
618           }
619           break;
620
621         // case KeyEvent.VK_A:
622         // if (viewport.cursorMode)
623         // {
624         // alignPanel.seqPanel.insertNucAtCursor(false,"A");
625         // //System.out.println("A");
626         // }
627         // break;
628         /*
629          * case KeyEvent.VK_CLOSE_BRACKET: if (viewport.cursorMode) {
630          * System.out.println("closing bracket"); } break;
631          */
632         case KeyEvent.VK_DELETE:
633         case KeyEvent.VK_BACK_SPACE:
634           if (!viewport.cursorMode)
635           {
636             cut_actionPerformed();
637           }
638           else
639           {
640             alignPanel.getSeqPanel().deleteGapAtCursor(evt.isControlDown()
641                     || evt.isShiftDown() || evt.isAltDown());
642           }
643
644           break;
645
646         case KeyEvent.VK_S:
647           if (viewport.cursorMode)
648           {
649             alignPanel.getSeqPanel().setCursorRow();
650           }
651           break;
652         case KeyEvent.VK_C:
653           if (viewport.cursorMode && !evt.isControlDown())
654           {
655             alignPanel.getSeqPanel().setCursorColumn();
656           }
657           break;
658         case KeyEvent.VK_P:
659           if (viewport.cursorMode)
660           {
661             alignPanel.getSeqPanel().setCursorPosition();
662           }
663           break;
664
665         case KeyEvent.VK_ENTER:
666         case KeyEvent.VK_COMMA:
667           if (viewport.cursorMode)
668           {
669             alignPanel.getSeqPanel().setCursorRowAndColumn();
670           }
671           break;
672
673         case KeyEvent.VK_Q:
674           if (viewport.cursorMode)
675           {
676             alignPanel.getSeqPanel().setSelectionAreaAtCursor(true);
677           }
678           break;
679         case KeyEvent.VK_M:
680           if (viewport.cursorMode)
681           {
682             alignPanel.getSeqPanel().setSelectionAreaAtCursor(false);
683           }
684           break;
685
686         case KeyEvent.VK_F2:
687           viewport.cursorMode = !viewport.cursorMode;
688           setStatus(MessageManager
689                   .formatMessage("label.keyboard_editing_mode", new String[]
690                   { (viewport.cursorMode ? "on" : "off") }));
691           if (viewport.cursorMode)
692           {
693             ViewportRanges ranges = viewport.getRanges();
694             alignPanel.getSeqPanel().seqCanvas.cursorX = ranges
695                     .getStartRes();
696             alignPanel.getSeqPanel().seqCanvas.cursorY = ranges
697                     .getStartSeq();
698           }
699           alignPanel.getSeqPanel().seqCanvas.repaint();
700           break;
701
702         case KeyEvent.VK_F1:
703           try
704           {
705             Help.showHelpWindow();
706           } catch (Exception ex)
707           {
708             ex.printStackTrace();
709           }
710           break;
711         case KeyEvent.VK_H:
712         {
713           boolean toggleSeqs = !evt.isControlDown();
714           boolean toggleCols = !evt.isShiftDown();
715           toggleHiddenRegions(toggleSeqs, toggleCols);
716           break;
717         }
718         case KeyEvent.VK_B:
719         {
720           boolean toggleSel = evt.isControlDown() || evt.isMetaDown();
721           boolean modifyExisting = true; // always modify, don't clear
722                                          // evt.isShiftDown();
723           boolean invertHighlighted = evt.isAltDown();
724           avc.markHighlightedColumns(invertHighlighted, modifyExisting,
725                   toggleSel);
726           break;
727         }
728         case KeyEvent.VK_PAGE_UP:
729           viewport.getRanges().pageUp();
730           break;
731         case KeyEvent.VK_PAGE_DOWN:
732           viewport.getRanges().pageDown();
733           break;
734         }
735       }
736
737       @Override
738       public void keyReleased(KeyEvent evt)
739       {
740         switch (evt.getKeyCode())
741         {
742         case KeyEvent.VK_LEFT:
743           if (evt.isAltDown() || !viewport.cursorMode)
744           {
745             viewport.firePropertyChange("alignment", null,
746                     viewport.getAlignment().getSequences());
747           }
748           break;
749
750         case KeyEvent.VK_RIGHT:
751           if (evt.isAltDown() || !viewport.cursorMode)
752           {
753             viewport.firePropertyChange("alignment", null,
754                     viewport.getAlignment().getSequences());
755           }
756           break;
757         }
758       }
759     });
760   }
761
762   public void addAlignmentPanel(final AlignmentPanel ap, boolean newPanel)
763   {
764     ap.alignFrame = this;
765     avc = new jalview.controller.AlignViewController(this, viewport,
766             alignPanel);
767
768     alignPanels.add(ap);
769
770     PaintRefresher.Register(ap, ap.av.getSequenceSetId());
771
772     int aSize = alignPanels.size();
773
774     tabbedPane.setVisible(aSize > 1 || ap.av.getViewName() != null);
775
776     if (aSize == 1 && ap.av.getViewName() == null)
777     {
778       this.getContentPane().add(ap, BorderLayout.CENTER);
779     }
780     else
781     {
782       if (aSize == 2)
783       {
784         setInitialTabVisible();
785       }
786
787       expandViews.setEnabled(true);
788       gatherViews.setEnabled(true);
789       tabbedPane.addTab(ap.av.getViewName(), ap);
790
791       ap.setVisible(false);
792     }
793
794     if (newPanel)
795     {
796       if (ap.av.isPadGaps())
797       {
798         ap.av.getAlignment().padGaps();
799       }
800       ap.av.updateConservation(ap);
801       ap.av.updateConsensus(ap);
802       ap.av.updateStrucConsensus(ap);
803     }
804   }
805
806   public void setInitialTabVisible()
807   {
808     expandViews.setEnabled(true);
809     gatherViews.setEnabled(true);
810     tabbedPane.setVisible(true);
811     AlignmentPanel first = alignPanels.get(0);
812     tabbedPane.addTab(first.av.getViewName(), first);
813     this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
814   }
815
816   public AlignViewport getViewport()
817   {
818     return viewport;
819   }
820
821   /* Set up intrinsic listeners for dynamically generated GUI bits. */
822   private void addServiceListeners()
823   {
824     final java.beans.PropertyChangeListener thisListener;
825     Desktop.instance.addJalviewPropertyChangeListener("services",
826             thisListener = new java.beans.PropertyChangeListener()
827             {
828               @Override
829               public void propertyChange(PropertyChangeEvent evt)
830               {
831                 // // System.out.println("Discoverer property change.");
832                 // if (evt.getPropertyName().equals("services"))
833                 {
834                   SwingUtilities.invokeLater(new Runnable()
835                   {
836
837                     @Override
838                     public void run()
839                     {
840                       System.err.println(
841                               "Rebuild WS Menu for service change");
842                       BuildWebServiceMenu();
843                     }
844
845                   });
846                 }
847               }
848             });
849     addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
850     {
851       @Override
852       public void internalFrameClosed(
853               javax.swing.event.InternalFrameEvent evt)
854       {
855         // System.out.println("deregistering discoverer listener");
856         Desktop.instance.removeJalviewPropertyChangeListener("services",
857                 thisListener);
858         closeMenuItem_actionPerformed(true);
859       }
860     });
861     // Finally, build the menu once to get current service state
862     new Thread(new Runnable()
863     {
864       @Override
865       public void run()
866       {
867         BuildWebServiceMenu();
868       }
869     }).start();
870   }
871
872   /**
873    * Configure menu items that vary according to whether the alignment is
874    * nucleotide or protein
875    */
876   public void setGUINucleotide()
877   {
878     AlignmentI al = getViewport().getAlignment();
879     boolean nucleotide = al.isNucleotide();
880
881     loadVcf.setVisible(nucleotide);
882     showTranslation.setVisible(nucleotide);
883     showReverse.setVisible(nucleotide);
884     showReverseComplement.setVisible(nucleotide);
885     conservationMenuItem.setEnabled(!nucleotide);
886     modifyConservation
887             .setEnabled(!nucleotide && conservationMenuItem.isSelected());
888     showGroupConservation.setEnabled(!nucleotide);
889
890     showComplementMenuItem
891             .setText(nucleotide ? MessageManager.getString("label.protein")
892                     : MessageManager.getString("label.nucleotide"));
893   }
894
895   /**
896    * set up menus for the current viewport. This may be called after any
897    * operation that affects the data in the current view (selection changed,
898    * etc) to update the menus to reflect the new state.
899    */
900   @Override
901   public void setMenusForViewport()
902   {
903     setMenusFromViewport(viewport);
904   }
905
906   /**
907    * Need to call this method when tabs are selected for multiple views, or when
908    * loading from Jalview2XML.java
909    * 
910    * @param av
911    *          AlignViewport
912    */
913   public void setMenusFromViewport(AlignViewport av)
914   {
915     padGapsMenuitem.setSelected(av.isPadGaps());
916     colourTextMenuItem.setSelected(av.isShowColourText());
917     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
918     modifyPID.setEnabled(abovePIDThreshold.isSelected());
919     conservationMenuItem.setSelected(av.getConservationSelected());
920     modifyConservation.setEnabled(conservationMenuItem.isSelected());
921     seqLimits.setSelected(av.getShowJVSuffix());
922     idRightAlign.setSelected(av.isRightAlignIds());
923     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
924     renderGapsMenuItem.setSelected(av.isRenderGaps());
925     wrapMenuItem.setSelected(av.getWrapAlignment());
926     scaleAbove.setVisible(av.getWrapAlignment());
927     scaleLeft.setVisible(av.getWrapAlignment());
928     scaleRight.setVisible(av.getWrapAlignment());
929     annotationPanelMenuItem.setState(av.isShowAnnotation());
930     /*
931      * Show/hide annotations only enabled if annotation panel is shown
932      */
933     showAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
934     hideAllSeqAnnotations.setEnabled(annotationPanelMenuItem.getState());
935     showAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
936     hideAllAlAnnotations.setEnabled(annotationPanelMenuItem.getState());
937     viewBoxesMenuItem.setSelected(av.getShowBoxes());
938     viewTextMenuItem.setSelected(av.getShowText());
939     showNonconservedMenuItem.setSelected(av.getShowUnconserved());
940     showGroupConsensus.setSelected(av.isShowGroupConsensus());
941     showGroupConservation.setSelected(av.isShowGroupConservation());
942     showConsensusHistogram.setSelected(av.isShowConsensusHistogram());
943     showSequenceLogo.setSelected(av.isShowSequenceLogo());
944     normaliseSequenceLogo.setSelected(av.isNormaliseSequenceLogo());
945
946     ColourMenuHelper.setColourSelected(colourMenu,
947             av.getGlobalColourScheme());
948
949     showSeqFeatures.setSelected(av.isShowSequenceFeatures());
950     hiddenMarkers.setState(av.getShowHiddenMarkers());
951     applyToAllGroups.setState(av.getColourAppliesToAllGroups());
952     showNpFeatsMenuitem.setSelected(av.isShowNPFeats());
953     showDbRefsMenuitem.setSelected(av.isShowDBRefs());
954     autoCalculate.setSelected(av.autoCalculateConsensus);
955     sortByTree.setSelected(av.sortByTree);
956     listenToViewSelections.setSelected(av.followSelection);
957
958     showProducts.setEnabled(canShowProducts());
959     setGroovyEnabled(Desktop.getGroovyConsole() != null);
960
961     updateEditMenuBar();
962   }
963
964   /**
965    * Set the enabled state of the 'Run Groovy' option in the Calculate menu
966    * 
967    * @param b
968    */
969   public void setGroovyEnabled(boolean b)
970   {
971     runGroovy.setEnabled(b);
972   }
973
974   private IProgressIndicator progressBar;
975
976   /*
977    * (non-Javadoc)
978    * 
979    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
980    */
981   @Override
982   public void setProgressBar(String message, long id)
983   {
984     progressBar.setProgressBar(message, id);
985   }
986
987   @Override
988   public void registerHandler(final long id,
989           final IProgressIndicatorHandler handler)
990   {
991     progressBar.registerHandler(id, handler);
992   }
993
994   /**
995    * 
996    * @return true if any progress bars are still active
997    */
998   @Override
999   public boolean operationInProgress()
1000   {
1001     return progressBar.operationInProgress();
1002   }
1003
1004   /**
1005    * Sets the text of the status bar. Note that setting a null or empty value
1006    * will cause the status bar to be hidden, with possibly undesirable flicker
1007    * of the screen layout.
1008    */
1009   @Override
1010   public void setStatus(String text)
1011   {
1012     statusBar.setText(text == null || text.isEmpty() ? " " : text);
1013   }
1014
1015   /*
1016    * Added so Castor Mapping file can obtain Jalview Version
1017    */
1018   public String getVersion()
1019   {
1020     return Cache.getProperty("VERSION");
1021   }
1022
1023   public FeatureRenderer getFeatureRenderer()
1024   {
1025     return alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer();
1026   }
1027
1028   @Override
1029   public void fetchSequence_actionPerformed()
1030   {
1031     new SequenceFetcher(this);
1032   }
1033
1034   @Override
1035   public void addFromFile_actionPerformed(ActionEvent e)
1036   {
1037     Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
1038   }
1039
1040   @Override
1041   public void reload_actionPerformed(ActionEvent e)
1042   {
1043     if (fileName != null)
1044     {
1045       // TODO: JAL-1108 - ensure all associated frames are closed regardless of
1046       // originating file's format
1047       // TODO: work out how to recover feature settings for correct view(s) when
1048       // file is reloaded.
1049       if (FileFormat.Jalview.equals(currentFileFormat))
1050       {
1051         JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1052         for (int i = 0; i < frames.length; i++)
1053         {
1054           if (frames[i] instanceof AlignFrame && frames[i] != this
1055                   && ((AlignFrame) frames[i]).fileName != null
1056                   && ((AlignFrame) frames[i]).fileName.equals(fileName))
1057           {
1058             try
1059             {
1060               frames[i].setSelected(true);
1061               Desktop.instance.closeAssociatedWindows();
1062             } catch (java.beans.PropertyVetoException ex)
1063             {
1064             }
1065           }
1066
1067         }
1068         Desktop.instance.closeAssociatedWindows();
1069
1070         FileLoader loader = new FileLoader();
1071         DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(fileName)
1072                 ? DataSourceType.URL
1073                 : DataSourceType.FILE;
1074         loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
1075       }
1076       else
1077       {
1078         Rectangle bounds = this.getBounds();
1079
1080         FileLoader loader = new FileLoader();
1081
1082         AlignFrame newframe = null;
1083
1084         if (fileObject == null)
1085         {
1086
1087           DataSourceType protocol = HttpUtils.startsWithHttpOrHttps(
1088                   fileName) ? DataSourceType.URL : DataSourceType.FILE;
1089           newframe = loader.LoadFileWaitTillLoaded(fileName, protocol,
1090                   currentFileFormat);
1091         }
1092         else
1093         {
1094           newframe = loader.LoadFileWaitTillLoaded(fileObject,
1095                   DataSourceType.FILE, currentFileFormat);
1096         }
1097
1098         newframe.setBounds(bounds);
1099         if (featureSettings != null && featureSettings.isShowing())
1100         {
1101           final Rectangle fspos = featureSettings.frame.getBounds();
1102           // TODO: need a 'show feature settings' function that takes bounds -
1103           // need to refactor Desktop.addFrame
1104           newframe.featureSettings_actionPerformed(null);
1105           final FeatureSettings nfs = newframe.featureSettings;
1106           SwingUtilities.invokeLater(new Runnable()
1107           {
1108             @Override
1109             public void run()
1110             {
1111               nfs.frame.setBounds(fspos);
1112             }
1113           });
1114           this.featureSettings.close();
1115           this.featureSettings = null;
1116         }
1117         this.closeMenuItem_actionPerformed(true);
1118       }
1119     }
1120   }
1121
1122   @Override
1123   public void addFromText_actionPerformed(ActionEvent e)
1124   {
1125     Desktop.instance
1126             .inputTextboxMenuItem_actionPerformed(viewport.getAlignPanel());
1127   }
1128
1129   @Override
1130   public void addFromURL_actionPerformed(ActionEvent e)
1131   {
1132     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
1133   }
1134
1135   @Override
1136   public void save_actionPerformed(ActionEvent e)
1137   {
1138     if (fileName == null || (currentFileFormat == null)
1139             || HttpUtils.startsWithHttpOrHttps(fileName))
1140     {
1141       saveAs_actionPerformed();
1142     }
1143     else
1144     {
1145       saveAlignment(fileName, currentFileFormat);
1146     }
1147   }
1148
1149   /**
1150    * Saves the alignment to a file with a name chosen by the user, if necessary
1151    * warning if a file would be overwritten
1152    */
1153   @Override
1154   public void saveAs_actionPerformed()
1155   {
1156     String format = currentFileFormat == null ? null
1157             : currentFileFormat.getName();
1158     JalviewFileChooser chooser = JalviewFileChooser
1159             .forWrite(Cache.getProperty("LAST_DIRECTORY"), format);
1160
1161     chooser.setFileView(new JalviewFileView());
1162     chooser.setDialogTitle(
1163             MessageManager.getString("label.save_alignment_to_file"));
1164     chooser.setToolTipText(MessageManager.getString("action.save"));
1165
1166     int value = chooser.showSaveDialog(this);
1167
1168     if (value != JalviewFileChooser.APPROVE_OPTION)
1169     {
1170       return;
1171     }
1172     currentFileFormat = chooser.getSelectedFormat();
1173     // todo is this (2005) test now obsolete - value is never null?
1174     while (currentFileFormat == null)
1175     {
1176       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1177               MessageManager
1178                       .getString("label.select_file_format_before_saving"),
1179               MessageManager.getString("label.file_format_not_specified"),
1180               JvOptionPane.WARNING_MESSAGE);
1181       currentFileFormat = chooser.getSelectedFormat();
1182       value = chooser.showSaveDialog(this);
1183       if (value != JalviewFileChooser.APPROVE_OPTION)
1184       {
1185         return;
1186       }
1187     }
1188
1189     fileName = chooser.getSelectedFile().getPath();
1190
1191     Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
1192     Cache.setProperty("LAST_DIRECTORY", fileName);
1193     saveAlignment(fileName, currentFileFormat);
1194   }
1195
1196   boolean lastSaveSuccessful = false;
1197
1198   FileFormatI lastFormatSaved;
1199
1200   String lastFilenameSaved;
1201
1202   /**
1203    * Raise a dialog or status message for the last call to saveAlignment.
1204    *
1205    * @return true if last call to saveAlignment(file, format) was successful.
1206    */
1207   public boolean isSaveAlignmentSuccessful()
1208   {
1209
1210     if (!lastSaveSuccessful)
1211     {
1212       if (!Platform.isHeadless())
1213       {
1214         JvOptionPane.showInternalMessageDialog(this, MessageManager
1215                 .formatMessage("label.couldnt_save_file", new Object[]
1216                 { lastFilenameSaved }),
1217                 MessageManager.getString("label.error_saving_file"),
1218                 JvOptionPane.WARNING_MESSAGE);
1219       }
1220       else
1221       {
1222         Console.error(MessageManager
1223                 .formatMessage("label.couldnt_save_file", new Object[]
1224                 { lastFilenameSaved }));
1225       }
1226     }
1227     else
1228     {
1229
1230       setStatus(MessageManager.formatMessage(
1231               "label.successfully_saved_to_file_in_format", new Object[]
1232               { lastFilenameSaved, lastFormatSaved }));
1233
1234     }
1235     return lastSaveSuccessful;
1236   }
1237
1238   /**
1239    * Saves the alignment to the specified file path, in the specified format,
1240    * which may be an alignment format, or Jalview project format. If the
1241    * alignment has hidden regions, or the format is one capable of including
1242    * non-sequence data (features, annotations, groups), then the user may be
1243    * prompted to specify what to include in the output.
1244    * 
1245    * @param file
1246    * @param format
1247    */
1248   public void saveAlignment(String file, FileFormatI format)
1249   {
1250     lastSaveSuccessful = true;
1251     lastFilenameSaved = file;
1252     lastFormatSaved = format;
1253
1254     if (FileFormat.Jalview.equals(format))
1255     {
1256       String shortName = title;
1257       if (shortName.indexOf(File.separatorChar) > -1)
1258       {
1259         shortName = shortName
1260                 .substring(shortName.lastIndexOf(File.separatorChar) + 1);
1261       }
1262       lastSaveSuccessful = new Jalview2XML().saveAlignment(this, file,
1263               shortName);
1264
1265       statusBar.setText(MessageManager.formatMessage(
1266               "label.successfully_saved_to_file_in_format", new Object[]
1267               { file, format }));
1268
1269       return;
1270     }
1271
1272     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1273     Runnable cancelAction = new Runnable()
1274     {
1275       @Override
1276       public void run()
1277       {
1278         lastSaveSuccessful = false;
1279       }
1280     };
1281     Runnable outputAction = new Runnable()
1282     {
1283       @Override
1284       public void run()
1285       {
1286         // todo defer this to inside formatSequences (or later)
1287         AlignmentExportData exportData = viewport
1288                 .getAlignExportData(options);
1289         String output = new FormatAdapter(alignPanel, options)
1290                 .formatSequences(format, exportData.getAlignment(),
1291                         exportData.getOmitHidden(),
1292                         exportData.getStartEndPostions(),
1293                         viewport.getAlignment().getHiddenColumns());
1294         if (output == null)
1295         {
1296           lastSaveSuccessful = false;
1297         }
1298         else
1299         {
1300           // create backupfiles object and get new temp filename destination
1301           boolean doBackup = BackupFiles.getEnabled();
1302           BackupFiles backupfiles = null;
1303           if (doBackup)
1304           {
1305             Console.trace(
1306                     "ALIGNFRAME making backupfiles object for " + file);
1307             backupfiles = new BackupFiles(file);
1308           }
1309           try
1310           {
1311             String tempFilePath = doBackup ? backupfiles.getTempFilePath()
1312                     : file;
1313             Console.trace("ALIGNFRAME setting PrintWriter");
1314             PrintWriter out = new PrintWriter(new FileWriter(tempFilePath));
1315
1316             if (backupfiles != null)
1317             {
1318               Console.trace("ALIGNFRAME about to write to temp file "
1319                       + backupfiles.getTempFilePath());
1320             }
1321
1322             out.print(output);
1323             Console.trace("ALIGNFRAME about to close file");
1324             out.close();
1325             Console.trace("ALIGNFRAME closed file");
1326             AlignFrame.this.setTitle(file);
1327             statusBar.setText(MessageManager.formatMessage(
1328                     "label.successfully_saved_to_file_in_format",
1329                     new Object[]
1330                     { fileName, format.getName() }));
1331             lastSaveSuccessful = true;
1332           } catch (IOException e)
1333           {
1334             lastSaveSuccessful = false;
1335             Console.error(
1336                     "ALIGNFRAME Something happened writing the temp file");
1337             Console.error(e.getMessage());
1338             Console.debug(Cache.getStackTraceString(e));
1339           } catch (Exception ex)
1340           {
1341             lastSaveSuccessful = false;
1342             Console.error(
1343                     "ALIGNFRAME Something unexpected happened writing the temp file");
1344             Console.error(ex.getMessage());
1345             Console.debug(Cache.getStackTraceString(ex));
1346           }
1347
1348           if (doBackup)
1349           {
1350             backupfiles.setWriteSuccess(lastSaveSuccessful);
1351             Console.debug("ALIGNFRAME writing temp file was "
1352                     + (lastSaveSuccessful ? "" : "NOT ") + "successful");
1353             // do the backup file roll and rename the temp file to actual file
1354             Console.trace(
1355                     "ALIGNFRAME about to rollBackupsAndRenameTempFile");
1356             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1357             Console.debug(
1358                     "ALIGNFRAME performed rollBackupsAndRenameTempFile "
1359                             + (lastSaveSuccessful ? "" : "un")
1360                             + "successfully");
1361           }
1362         }
1363       }
1364     };
1365
1366     /*
1367      * show dialog with export options if applicable; else just do it
1368      */
1369     if (AlignExportOptions.isNeeded(viewport, format))
1370     {
1371       AlignExportOptions choices = new AlignExportOptions(
1372               alignPanel.getAlignViewport(), format, options);
1373       choices.setResponseAction(0, outputAction);
1374       choices.setResponseAction(1, cancelAction);
1375       choices.showDialog();
1376     }
1377     else
1378     {
1379       outputAction.run();
1380     }
1381   }
1382
1383   /**
1384    * Outputs the alignment to textbox in the requested format, if necessary
1385    * first prompting the user for whether to include hidden regions or
1386    * non-sequence data
1387    * 
1388    * @param fileFormatName
1389    */
1390   @Override
1391   protected void outputText_actionPerformed(String fileFormatName)
1392   {
1393     FileFormatI fileFormat = FileFormats.getInstance()
1394             .forName(fileFormatName);
1395     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1396     Runnable outputAction = new Runnable()
1397     {
1398       @Override
1399       public void run()
1400       {
1401         // todo defer this to inside formatSequences (or later)
1402         AlignmentExportData exportData = viewport
1403                 .getAlignExportData(options);
1404         CutAndPasteTransfer cap = new CutAndPasteTransfer();
1405         cap.setForInput(null);
1406         try
1407         {
1408           FileFormatI format = fileFormat;
1409           cap.setText(new FormatAdapter(alignPanel, options)
1410                   .formatSequences(format, exportData.getAlignment(),
1411                           exportData.getOmitHidden(),
1412                           exportData.getStartEndPostions(),
1413                           viewport.getAlignment().getHiddenColumns()));
1414           Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1415                   "label.alignment_output_command", new Object[]
1416                   { fileFormat.getName() }), 600, 500);
1417         } catch (OutOfMemoryError oom)
1418         {
1419           new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1420                   oom);
1421           cap.dispose();
1422         }
1423       }
1424     };
1425
1426     /*
1427      * show dialog with export options if applicable; else just do it
1428      */
1429     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1430     {
1431       AlignExportOptions choices = new AlignExportOptions(
1432               alignPanel.getAlignViewport(), fileFormat, options);
1433       choices.setResponseAction(0, outputAction);
1434       choices.showDialog();
1435     }
1436     else
1437     {
1438       outputAction.run();
1439     }
1440   }
1441
1442   /**
1443    * DOCUMENT ME!
1444    * 
1445    * @param e
1446    *          DOCUMENT ME!
1447    */
1448   @Override
1449   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1450   {
1451     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1452     htmlSVG.exportHTML(null);
1453   }
1454
1455   @Override
1456   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1457   {
1458     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1459     bjs.exportHTML(null);
1460   }
1461
1462   public void createImageMap(File file, String image)
1463   {
1464     alignPanel.makePNGImageMap(file, image);
1465   }
1466
1467   /**
1468    * Creates a PNG image of the alignment and writes it to the given file. If
1469    * the file is null, the user is prompted to choose a file.
1470    * 
1471    * @param f
1472    */
1473   @Override
1474   public void createPNG(File f)
1475   {
1476     alignPanel.makeAlignmentImage(TYPE.PNG, f);
1477   }
1478
1479   /**
1480    * Creates an EPS image of the alignment and writes it to the given file. If
1481    * the file is null, the user is prompted to choose a file.
1482    * 
1483    * @param f
1484    */
1485   @Override
1486   public void createEPS(File f)
1487   {
1488     alignPanel.makeAlignmentImage(TYPE.EPS, f);
1489   }
1490
1491   /**
1492    * Creates an SVG image of the alignment and writes it to the given file. If
1493    * the file is null, the user is prompted to choose a file.
1494    * 
1495    * @param f
1496    */
1497   @Override
1498   public void createSVG(File f)
1499   {
1500     alignPanel.makeAlignmentImage(TYPE.SVG, f);
1501   }
1502
1503   @Override
1504   public void pageSetup_actionPerformed(ActionEvent e)
1505   {
1506     PrinterJob printJob = PrinterJob.getPrinterJob();
1507     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1508   }
1509
1510   /**
1511    * DOCUMENT ME!
1512    * 
1513    * @param e
1514    *          DOCUMENT ME!
1515    */
1516   @Override
1517   public void printMenuItem_actionPerformed(ActionEvent e)
1518   {
1519     // Putting in a thread avoids Swing painting problems
1520     PrintThread thread = new PrintThread(alignPanel);
1521     thread.start();
1522   }
1523
1524   @Override
1525   public void exportFeatures_actionPerformed(ActionEvent e)
1526   {
1527     new AnnotationExporter(alignPanel).exportFeatures();
1528   }
1529
1530   @Override
1531   public void exportAnnotations_actionPerformed(ActionEvent e)
1532   {
1533     new AnnotationExporter(alignPanel).exportAnnotations();
1534   }
1535
1536   @Override
1537   public void associatedData_actionPerformed(ActionEvent e)
1538   {
1539     final JalviewFileChooser chooser = new JalviewFileChooser(
1540             Cache.getProperty("LAST_DIRECTORY"));
1541     chooser.setFileView(new JalviewFileView());
1542     String tooltip = MessageManager
1543             .getString("label.load_jalview_annotations");
1544     chooser.setDialogTitle(tooltip);
1545     chooser.setToolTipText(tooltip);
1546     chooser.setResponseHandler(0, new Runnable()
1547     {
1548       @Override
1549       public void run()
1550       {
1551         String choice = chooser.getSelectedFile().getPath();
1552         Cache.setProperty("LAST_DIRECTORY", choice);
1553         loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1554       }
1555     });
1556
1557     chooser.showOpenDialog(this);
1558   }
1559
1560   /**
1561    * Close the current view or all views in the alignment frame. If the frame
1562    * only contains one view then the alignment will be removed from memory.
1563    * 
1564    * @param closeAllTabs
1565    */
1566   @Override
1567   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1568   {
1569     if (alignPanels != null && alignPanels.size() < 2)
1570     {
1571       closeAllTabs = true;
1572     }
1573
1574     try
1575     {
1576       if (alignPanels != null)
1577       {
1578         if (closeAllTabs)
1579         {
1580           if (this.isClosed())
1581           {
1582             // really close all the windows - otherwise wait till
1583             // setClosed(true) is called
1584             for (int i = 0; i < alignPanels.size(); i++)
1585             {
1586               AlignmentPanel ap = alignPanels.get(i);
1587               ap.closePanel();
1588             }
1589           }
1590         }
1591         else
1592         {
1593           closeView(alignPanel);
1594         }
1595       }
1596       if (closeAllTabs)
1597       {
1598         if (featureSettings != null && featureSettings.isOpen())
1599         {
1600           featureSettings.close();
1601           featureSettings = null;
1602         }
1603         /*
1604          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1605          * be called recursively, with the frame now in 'closed' state
1606          */
1607         this.setClosed(true);
1608       }
1609     } catch (Exception ex)
1610     {
1611       ex.printStackTrace();
1612     }
1613   }
1614
1615   /**
1616    * Close the specified panel and close up tabs appropriately.
1617    * 
1618    * @param panelToClose
1619    */
1620   public void closeView(AlignmentPanel panelToClose)
1621   {
1622     int index = tabbedPane.getSelectedIndex();
1623     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1624     alignPanels.remove(panelToClose);
1625     panelToClose.closePanel();
1626     panelToClose = null;
1627
1628     tabbedPane.removeTabAt(closedindex);
1629     tabbedPane.validate();
1630
1631     if (index > closedindex || index == tabbedPane.getTabCount())
1632     {
1633       // modify currently selected tab index if necessary.
1634       index--;
1635     }
1636
1637     this.tabSelectionChanged(index);
1638   }
1639
1640   /**
1641    * DOCUMENT ME!
1642    */
1643   void updateEditMenuBar()
1644   {
1645
1646     if (viewport.getHistoryList().size() > 0)
1647     {
1648       undoMenuItem.setEnabled(true);
1649       CommandI command = viewport.getHistoryList().peek();
1650       undoMenuItem.setText(MessageManager
1651               .formatMessage("label.undo_command", new Object[]
1652               { command.getDescription() }));
1653     }
1654     else
1655     {
1656       undoMenuItem.setEnabled(false);
1657       undoMenuItem.setText(MessageManager.getString("action.undo"));
1658     }
1659
1660     if (viewport.getRedoList().size() > 0)
1661     {
1662       redoMenuItem.setEnabled(true);
1663
1664       CommandI command = viewport.getRedoList().peek();
1665       redoMenuItem.setText(MessageManager
1666               .formatMessage("label.redo_command", new Object[]
1667               { command.getDescription() }));
1668     }
1669     else
1670     {
1671       redoMenuItem.setEnabled(false);
1672       redoMenuItem.setText(MessageManager.getString("action.redo"));
1673     }
1674   }
1675
1676   @Override
1677   public void addHistoryItem(CommandI command)
1678   {
1679     if (command.getSize() > 0)
1680     {
1681       viewport.addToHistoryList(command);
1682       viewport.clearRedoList();
1683       updateEditMenuBar();
1684       viewport.updateHiddenColumns();
1685       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1686       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1687       // viewport.getColumnSelection()
1688       // .getHiddenColumns().size() > 0);
1689     }
1690   }
1691
1692   /**
1693    * 
1694    * @return alignment objects for all views
1695    */
1696   AlignmentI[] getViewAlignments()
1697   {
1698     if (alignPanels != null)
1699     {
1700       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1701       int i = 0;
1702       for (AlignmentPanel ap : alignPanels)
1703       {
1704         als[i++] = ap.av.getAlignment();
1705       }
1706       return als;
1707     }
1708     if (viewport != null)
1709     {
1710       return new AlignmentI[] { viewport.getAlignment() };
1711     }
1712     return null;
1713   }
1714
1715   /**
1716    * DOCUMENT ME!
1717    * 
1718    * @param e
1719    *          DOCUMENT ME!
1720    */
1721   @Override
1722   protected void undoMenuItem_actionPerformed(ActionEvent e)
1723   {
1724     if (viewport.getHistoryList().isEmpty())
1725     {
1726       return;
1727     }
1728     CommandI command = viewport.getHistoryList().pop();
1729     viewport.addToRedoList(command);
1730     command.undoCommand(getViewAlignments());
1731
1732     AlignmentViewport originalSource = getOriginatingSource(command);
1733     updateEditMenuBar();
1734
1735     if (originalSource != null)
1736     {
1737       if (originalSource != viewport)
1738       {
1739         Console.warn(
1740                 "Implementation worry: mismatch of viewport origin for undo");
1741       }
1742       originalSource.updateHiddenColumns();
1743       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1744       // null
1745       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1746       // viewport.getColumnSelection()
1747       // .getHiddenColumns().size() > 0);
1748       originalSource.firePropertyChange("alignment", null,
1749               originalSource.getAlignment().getSequences());
1750     }
1751   }
1752
1753   /**
1754    * DOCUMENT ME!
1755    * 
1756    * @param e
1757    *          DOCUMENT ME!
1758    */
1759   @Override
1760   protected void redoMenuItem_actionPerformed(ActionEvent e)
1761   {
1762     if (viewport.getRedoList().size() < 1)
1763     {
1764       return;
1765     }
1766
1767     CommandI command = viewport.getRedoList().pop();
1768     viewport.addToHistoryList(command);
1769     command.doCommand(getViewAlignments());
1770
1771     AlignmentViewport originalSource = getOriginatingSource(command);
1772     updateEditMenuBar();
1773
1774     if (originalSource != null)
1775     {
1776
1777       if (originalSource != viewport)
1778       {
1779         Console.warn(
1780                 "Implementation worry: mismatch of viewport origin for redo");
1781       }
1782       originalSource.updateHiddenColumns();
1783       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1784       // null
1785       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1786       // viewport.getColumnSelection()
1787       // .getHiddenColumns().size() > 0);
1788       originalSource.firePropertyChange("alignment", null,
1789               originalSource.getAlignment().getSequences());
1790     }
1791   }
1792
1793   AlignmentViewport getOriginatingSource(CommandI command)
1794   {
1795     AlignmentViewport originalSource = null;
1796     // For sequence removal and addition, we need to fire
1797     // the property change event FROM the viewport where the
1798     // original alignment was altered
1799     AlignmentI al = null;
1800     if (command instanceof EditCommand)
1801     {
1802       EditCommand editCommand = (EditCommand) command;
1803       al = editCommand.getAlignment();
1804       List<Component> comps = PaintRefresher.components
1805               .get(viewport.getSequenceSetId());
1806
1807       for (Component comp : comps)
1808       {
1809         if (comp instanceof AlignmentPanel)
1810         {
1811           if (al == ((AlignmentPanel) comp).av.getAlignment())
1812           {
1813             originalSource = ((AlignmentPanel) comp).av;
1814             break;
1815           }
1816         }
1817       }
1818     }
1819
1820     if (originalSource == null)
1821     {
1822       // The original view is closed, we must validate
1823       // the current view against the closed view first
1824       if (al != null)
1825       {
1826         PaintRefresher.validateSequences(al, viewport.getAlignment());
1827       }
1828
1829       originalSource = viewport;
1830     }
1831
1832     return originalSource;
1833   }
1834
1835   /**
1836    * Calls AlignmentI.moveSelectedSequencesByOne with current sequence selection
1837    * or the sequence under cursor in keyboard mode
1838    * 
1839    * @param up
1840    *          or down (if !up)
1841    */
1842   public void moveSelectedSequences(boolean up)
1843   {
1844     SequenceGroup sg = viewport.getSelectionGroup();
1845
1846     if (sg == null)
1847     {
1848       if (viewport.cursorMode)
1849       {
1850         sg = new SequenceGroup();
1851         sg.addSequence(viewport.getAlignment().getSequenceAt(
1852                 alignPanel.getSeqPanel().seqCanvas.cursorY), false);
1853       }
1854       else
1855       {
1856         return;
1857       }
1858     }
1859
1860     if (sg.getSize() < 1)
1861     {
1862       return;
1863     }
1864
1865     // TODO: JAL-3733 - add an event to the undo buffer for this !
1866
1867     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1868             viewport.getHiddenRepSequences(), up);
1869     alignPanel.paintAlignment(true, false);
1870   }
1871
1872   synchronized void slideSequences(boolean right, int size)
1873   {
1874     List<SequenceI> sg = new ArrayList<>();
1875     if (viewport.cursorMode)
1876     {
1877       sg.add(viewport.getAlignment()
1878               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1879     }
1880     else if (viewport.getSelectionGroup() != null
1881             && viewport.getSelectionGroup().getSize() != viewport
1882                     .getAlignment().getHeight())
1883     {
1884       sg = viewport.getSelectionGroup()
1885               .getSequences(viewport.getHiddenRepSequences());
1886     }
1887
1888     if (sg.size() < 1)
1889     {
1890       return;
1891     }
1892
1893     List<SequenceI> invertGroup = new ArrayList<>();
1894
1895     for (SequenceI seq : viewport.getAlignment().getSequences())
1896     {
1897       if (!sg.contains(seq))
1898       {
1899         invertGroup.add(seq);
1900       }
1901     }
1902
1903     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1904
1905     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1906     for (int i = 0; i < invertGroup.size(); i++)
1907     {
1908       seqs2[i] = invertGroup.get(i);
1909     }
1910
1911     SlideSequencesCommand ssc;
1912     if (right)
1913     {
1914       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1915               viewport.getGapCharacter());
1916     }
1917     else
1918     {
1919       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1920               viewport.getGapCharacter());
1921     }
1922
1923     int groupAdjustment = 0;
1924     if (ssc.getGapsInsertedBegin() && right)
1925     {
1926       if (viewport.cursorMode)
1927       {
1928         alignPanel.getSeqPanel().moveCursor(size, 0);
1929       }
1930       else
1931       {
1932         groupAdjustment = size;
1933       }
1934     }
1935     else if (!ssc.getGapsInsertedBegin() && !right)
1936     {
1937       if (viewport.cursorMode)
1938       {
1939         alignPanel.getSeqPanel().moveCursor(-size, 0);
1940       }
1941       else
1942       {
1943         groupAdjustment = -size;
1944       }
1945     }
1946
1947     if (groupAdjustment != 0)
1948     {
1949       viewport.getSelectionGroup().setStartRes(
1950               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1951       viewport.getSelectionGroup().setEndRes(
1952               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1953     }
1954
1955     /*
1956      * just extend the last slide command if compatible; but not if in
1957      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1958      */
1959     boolean appendHistoryItem = false;
1960     Deque<CommandI> historyList = viewport.getHistoryList();
1961     boolean inSplitFrame = getSplitViewContainer() != null;
1962     if (!inSplitFrame && historyList != null && historyList.size() > 0
1963             && historyList.peek() instanceof SlideSequencesCommand)
1964     {
1965       appendHistoryItem = ssc.appendSlideCommand(
1966               (SlideSequencesCommand) historyList.peek());
1967     }
1968
1969     if (!appendHistoryItem)
1970     {
1971       addHistoryItem(ssc);
1972     }
1973
1974     repaint();
1975   }
1976
1977   /**
1978    * DOCUMENT ME!
1979    * 
1980    * @param e
1981    *          DOCUMENT ME!
1982    */
1983   @Override
1984   protected void copy_actionPerformed()
1985   {
1986     if (viewport.getSelectionGroup() == null)
1987     {
1988       return;
1989     }
1990     // TODO: preserve the ordering of displayed alignment annotation in any
1991     // internal paste (particularly sequence associated annotation)
1992     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1993     String[] omitHidden = null;
1994
1995     if (viewport.hasHiddenColumns())
1996     {
1997       omitHidden = viewport.getViewAsString(true);
1998     }
1999
2000     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
2001             seqs, omitHidden, null);
2002
2003     StringSelection ss = new StringSelection(output);
2004
2005     try
2006     {
2007       jalview.gui.Desktop.internalCopy = true;
2008       // Its really worth setting the clipboard contents
2009       // to empty before setting the large StringSelection!!
2010       Toolkit.getDefaultToolkit().getSystemClipboard()
2011               .setContents(new StringSelection(""), null);
2012
2013       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
2014               Desktop.instance);
2015     } catch (OutOfMemoryError er)
2016     {
2017       new OOMWarning("copying region", er);
2018       return;
2019     }
2020
2021     HiddenColumns hiddenColumns = null;
2022     if (viewport.hasHiddenColumns())
2023     {
2024       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
2025       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
2026
2027       // create new HiddenColumns object with copy of hidden regions
2028       // between startRes and endRes, offset by startRes
2029       hiddenColumns = new HiddenColumns(
2030               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
2031               hiddenCutoff, hiddenOffset);
2032     }
2033
2034     Desktop.jalviewClipboard = new Object[] { seqs,
2035         viewport.getAlignment().getDataset(), hiddenColumns };
2036     setStatus(MessageManager.formatMessage(
2037             "label.copied_sequences_to_clipboard", new Object[]
2038             { Integer.valueOf(seqs.length).toString() }));
2039   }
2040
2041   /**
2042    * DOCUMENT ME!
2043    * 
2044    * @param e
2045    *          DOCUMENT ME!
2046    */
2047   @Override
2048   protected void pasteNew_actionPerformed(ActionEvent e)
2049   {
2050     paste(true);
2051   }
2052
2053   /**
2054    * DOCUMENT ME!
2055    * 
2056    * @param e
2057    *          DOCUMENT ME!
2058    */
2059   @Override
2060   protected void pasteThis_actionPerformed(ActionEvent e)
2061   {
2062     paste(false);
2063   }
2064
2065   /**
2066    * Paste contents of Jalview clipboard
2067    * 
2068    * @param newAlignment
2069    *          true to paste to a new alignment, otherwise add to this.
2070    */
2071   void paste(boolean newAlignment)
2072   {
2073     boolean externalPaste = true;
2074     try
2075     {
2076       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2077       Transferable contents = c.getContents(this);
2078
2079       if (contents == null)
2080       {
2081         return;
2082       }
2083
2084       String str;
2085       FileFormatI format;
2086       try
2087       {
2088         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2089         if (str.length() < 1)
2090         {
2091           return;
2092         }
2093
2094         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2095
2096       } catch (OutOfMemoryError er)
2097       {
2098         new OOMWarning("Out of memory pasting sequences!!", er);
2099         return;
2100       }
2101
2102       SequenceI[] sequences;
2103       boolean annotationAdded = false;
2104       AlignmentI alignment = null;
2105
2106       if (Desktop.jalviewClipboard != null)
2107       {
2108         // The clipboard was filled from within Jalview, we must use the
2109         // sequences
2110         // And dataset from the copied alignment
2111         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2112         // be doubly sure that we create *new* sequence objects.
2113         sequences = new SequenceI[newseq.length];
2114         for (int i = 0; i < newseq.length; i++)
2115         {
2116           sequences[i] = new Sequence(newseq[i]);
2117         }
2118         alignment = new Alignment(sequences);
2119         externalPaste = false;
2120       }
2121       else
2122       {
2123         // parse the clipboard as an alignment.
2124         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2125                 format);
2126         sequences = alignment.getSequencesArray();
2127       }
2128
2129       int alwidth = 0;
2130       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2131       int fgroup = -1;
2132
2133       if (newAlignment)
2134       {
2135
2136         if (Desktop.jalviewClipboard != null)
2137         {
2138           // dataset is inherited
2139           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2140         }
2141         else
2142         {
2143           // new dataset is constructed
2144           alignment.setDataset(null);
2145         }
2146         alwidth = alignment.getWidth() + 1;
2147       }
2148       else
2149       {
2150         AlignmentI pastedal = alignment; // preserve pasted alignment object
2151         // Add pasted sequences and dataset into existing alignment.
2152         alignment = viewport.getAlignment();
2153         alwidth = alignment.getWidth() + 1;
2154         // decide if we need to import sequences from an existing dataset
2155         boolean importDs = Desktop.jalviewClipboard != null
2156                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2157         // importDs==true instructs us to copy over new dataset sequences from
2158         // an existing alignment
2159         Vector<SequenceI> newDs = (importDs) ? new Vector<>() : null; // used to
2160                                                                       // create
2161         // minimum dataset set
2162
2163         for (int i = 0; i < sequences.length; i++)
2164         {
2165           if (importDs)
2166           {
2167             newDs.addElement(null);
2168           }
2169           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2170           // paste
2171           if (importDs && ds != null)
2172           {
2173             if (!newDs.contains(ds))
2174             {
2175               newDs.setElementAt(ds, i);
2176               ds = new Sequence(ds);
2177               // update with new dataset sequence
2178               sequences[i].setDatasetSequence(ds);
2179             }
2180             else
2181             {
2182               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2183             }
2184           }
2185           else
2186           {
2187             // copy and derive new dataset sequence
2188             sequences[i] = sequences[i].deriveSequence();
2189             alignment.getDataset()
2190                     .addSequence(sequences[i].getDatasetSequence());
2191             // TODO: avoid creation of duplicate dataset sequences with a
2192             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2193           }
2194           alignment.addSequence(sequences[i]); // merges dataset
2195         }
2196         if (newDs != null)
2197         {
2198           newDs.clear(); // tidy up
2199         }
2200         if (alignment.getAlignmentAnnotation() != null)
2201         {
2202           for (AlignmentAnnotation alan : alignment
2203                   .getAlignmentAnnotation())
2204           {
2205             if (alan.graphGroup > fgroup)
2206             {
2207               fgroup = alan.graphGroup;
2208             }
2209           }
2210         }
2211         if (pastedal.getAlignmentAnnotation() != null)
2212         {
2213           // Add any annotation attached to alignment.
2214           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2215           for (int i = 0; i < alann.length; i++)
2216           {
2217             annotationAdded = true;
2218             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2219             {
2220               AlignmentAnnotation newann = new AlignmentAnnotation(
2221                       alann[i]);
2222               if (newann.graphGroup > -1)
2223               {
2224                 if (newGraphGroups.size() <= newann.graphGroup
2225                         || newGraphGroups.get(newann.graphGroup) == null)
2226                 {
2227                   for (int q = newGraphGroups
2228                           .size(); q <= newann.graphGroup; q++)
2229                   {
2230                     newGraphGroups.add(q, null);
2231                   }
2232                   newGraphGroups.set(newann.graphGroup,
2233                           Integer.valueOf(++fgroup));
2234                 }
2235                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2236                         .intValue();
2237               }
2238
2239               newann.padAnnotation(alwidth);
2240               alignment.addAnnotation(newann);
2241             }
2242           }
2243         }
2244       }
2245       if (!newAlignment)
2246       {
2247         // /////
2248         // ADD HISTORY ITEM
2249         //
2250         addHistoryItem(new EditCommand(
2251                 MessageManager.getString("label.add_sequences"),
2252                 Action.PASTE, sequences, 0, alignment.getWidth(),
2253                 alignment));
2254       }
2255       // Add any annotations attached to sequences
2256       for (int i = 0; i < sequences.length; i++)
2257       {
2258         if (sequences[i].getAnnotation() != null)
2259         {
2260           AlignmentAnnotation newann;
2261           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2262           {
2263             annotationAdded = true;
2264             newann = sequences[i].getAnnotation()[a];
2265             newann.adjustForAlignment();
2266             newann.padAnnotation(alwidth);
2267             if (newann.graphGroup > -1)
2268             {
2269               if (newann.graphGroup > -1)
2270               {
2271                 if (newGraphGroups.size() <= newann.graphGroup
2272                         || newGraphGroups.get(newann.graphGroup) == null)
2273                 {
2274                   for (int q = newGraphGroups
2275                           .size(); q <= newann.graphGroup; q++)
2276                   {
2277                     newGraphGroups.add(q, null);
2278                   }
2279                   newGraphGroups.set(newann.graphGroup,
2280                           Integer.valueOf(++fgroup));
2281                 }
2282                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2283                         .intValue();
2284               }
2285             }
2286             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2287             // was
2288             // duplicated
2289             // earlier
2290             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2291                     a);
2292           }
2293         }
2294       }
2295       if (!newAlignment)
2296       {
2297
2298         // propagate alignment changed.
2299         viewport.getRanges().setEndSeq(alignment.getHeight() - 1);
2300         if (annotationAdded)
2301         {
2302           // Duplicate sequence annotation in all views.
2303           AlignmentI[] alview = this.getViewAlignments();
2304           for (int i = 0; i < sequences.length; i++)
2305           {
2306             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2307             if (sann == null)
2308             {
2309               continue;
2310             }
2311             for (int avnum = 0; avnum < alview.length; avnum++)
2312             {
2313               if (alview[avnum] != alignment)
2314               {
2315                 // duplicate in a view other than the one with input focus
2316                 int avwidth = alview[avnum].getWidth() + 1;
2317                 // this relies on sann being preserved after we
2318                 // modify the sequence's annotation array for each duplication
2319                 for (int a = 0; a < sann.length; a++)
2320                 {
2321                   AlignmentAnnotation newann = new AlignmentAnnotation(
2322                           sann[a]);
2323                   sequences[i].addAlignmentAnnotation(newann);
2324                   newann.padAnnotation(avwidth);
2325                   alview[avnum].addAnnotation(newann); // annotation was
2326                   // duplicated earlier
2327                   // TODO JAL-1145 graphGroups are not updated for sequence
2328                   // annotation added to several views. This may cause
2329                   // strangeness
2330                   alview[avnum].setAnnotationIndex(newann, a);
2331                 }
2332               }
2333             }
2334           }
2335           buildSortByAnnotationScoresMenu();
2336         }
2337         viewport.firePropertyChange("alignment", null,
2338                 alignment.getSequences());
2339         if (alignPanels != null)
2340         {
2341           for (AlignmentPanel ap : alignPanels)
2342           {
2343             ap.validateAnnotationDimensions(false);
2344           }
2345         }
2346         else
2347         {
2348           alignPanel.validateAnnotationDimensions(false);
2349         }
2350
2351       }
2352       else
2353       {
2354         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2355                 DEFAULT_HEIGHT);
2356         String newtitle = new String("Copied sequences");
2357
2358         if (Desktop.jalviewClipboard != null
2359                 && Desktop.jalviewClipboard[2] != null)
2360         {
2361           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2362           af.viewport.setHiddenColumns(hc);
2363         }
2364
2365         // >>>This is a fix for the moment, until a better solution is
2366         // found!!<<<
2367         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2368                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2369                         .getFeatureRenderer());
2370
2371         // TODO: maintain provenance of an alignment, rather than just make the
2372         // title a concatenation of operations.
2373         if (!externalPaste)
2374         {
2375           if (title.startsWith("Copied sequences"))
2376           {
2377             newtitle = title;
2378           }
2379           else
2380           {
2381             newtitle = newtitle.concat("- from " + title);
2382           }
2383         }
2384         else
2385         {
2386           newtitle = new String("Pasted sequences");
2387         }
2388
2389         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2390                 DEFAULT_HEIGHT);
2391
2392       }
2393
2394     } catch (Exception ex)
2395     {
2396       ex.printStackTrace();
2397       System.out.println("Exception whilst pasting: " + ex);
2398       // could be anything being pasted in here
2399     }
2400
2401   }
2402
2403   @Override
2404   protected void expand_newalign(ActionEvent e)
2405   {
2406     try
2407     {
2408       AlignmentI alignment = AlignmentUtils
2409               .expandContext(getViewport().getAlignment(), -1);
2410       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2411               DEFAULT_HEIGHT);
2412       String newtitle = new String("Flanking alignment");
2413
2414       if (Desktop.jalviewClipboard != null
2415               && Desktop.jalviewClipboard[2] != null)
2416       {
2417         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2418         af.viewport.setHiddenColumns(hc);
2419       }
2420
2421       // >>>This is a fix for the moment, until a better solution is
2422       // found!!<<<
2423       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2424               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2425                       .getFeatureRenderer());
2426
2427       // TODO: maintain provenance of an alignment, rather than just make the
2428       // title a concatenation of operations.
2429       {
2430         if (title.startsWith("Copied sequences"))
2431         {
2432           newtitle = title;
2433         }
2434         else
2435         {
2436           newtitle = newtitle.concat("- from " + title);
2437         }
2438       }
2439
2440       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2441
2442     } catch (Exception ex)
2443     {
2444       ex.printStackTrace();
2445       System.out.println("Exception whilst pasting: " + ex);
2446       // could be anything being pasted in here
2447     } catch (OutOfMemoryError oom)
2448     {
2449       new OOMWarning("Viewing flanking region of alignment", oom);
2450     }
2451   }
2452
2453   /**
2454    * Action Cut (delete and copy) the selected region
2455    */
2456   @Override
2457   protected void cut_actionPerformed()
2458   {
2459     copy_actionPerformed();
2460     delete_actionPerformed();
2461   }
2462
2463   /**
2464    * Performs menu option to Delete the currently selected region
2465    */
2466   @Override
2467   protected void delete_actionPerformed()
2468   {
2469
2470     SequenceGroup sg = viewport.getSelectionGroup();
2471     if (sg == null)
2472     {
2473       return;
2474     }
2475
2476     Runnable okAction = new Runnable()
2477     {
2478       @Override
2479       public void run()
2480       {
2481         SequenceI[] cut = sg.getSequences()
2482                 .toArray(new SequenceI[sg.getSize()]);
2483
2484         addHistoryItem(new EditCommand(
2485                 MessageManager.getString("label.cut_sequences"), Action.CUT,
2486                 cut, sg.getStartRes(),
2487                 sg.getEndRes() - sg.getStartRes() + 1,
2488                 viewport.getAlignment()));
2489
2490         viewport.setSelectionGroup(null);
2491         viewport.sendSelection();
2492         viewport.getAlignment().deleteGroup(sg);
2493
2494         viewport.firePropertyChange("alignment", null,
2495                 viewport.getAlignment().getSequences());
2496         if (viewport.getAlignment().getHeight() < 1)
2497         {
2498           try
2499           {
2500             AlignFrame.this.setClosed(true);
2501           } catch (Exception ex)
2502           {
2503           }
2504         }
2505       }
2506     };
2507
2508     /*
2509      * If the cut affects all sequences, prompt for confirmation
2510      */
2511     boolean wholeHeight = sg.getSize() == viewport.getAlignment()
2512             .getHeight();
2513     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2514             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2515     if (wholeHeight && wholeWidth)
2516     {
2517       JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2518       dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2519       Object[] options = new Object[] {
2520           MessageManager.getString("action.ok"),
2521           MessageManager.getString("action.cancel") };
2522       dialog.showDialog(MessageManager.getString("warn.delete_all"),
2523               MessageManager.getString("label.delete_all"),
2524               JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2525               options, options[0]);
2526     }
2527     else
2528     {
2529       okAction.run();
2530     }
2531   }
2532
2533   /**
2534    * DOCUMENT ME!
2535    * 
2536    * @param e
2537    *          DOCUMENT ME!
2538    */
2539   @Override
2540   protected void deleteGroups_actionPerformed(ActionEvent e)
2541   {
2542     if (avc.deleteGroups())
2543     {
2544       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2545       alignPanel.updateAnnotation();
2546       alignPanel.paintAlignment(true, true);
2547     }
2548   }
2549
2550   /**
2551    * DOCUMENT ME!
2552    * 
2553    * @param e
2554    *          DOCUMENT ME!
2555    */
2556   @Override
2557   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2558   {
2559     SequenceGroup sg = new SequenceGroup(
2560             viewport.getAlignment().getSequences());
2561
2562     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2563     viewport.setSelectionGroup(sg);
2564     viewport.isSelectionGroupChanged(true);
2565     viewport.sendSelection();
2566     // JAL-2034 - should delegate to
2567     // alignPanel to decide if overview needs
2568     // updating.
2569     alignPanel.paintAlignment(false, false);
2570     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2571   }
2572
2573   /**
2574    * DOCUMENT ME!
2575    * 
2576    * @param e
2577    *          DOCUMENT ME!
2578    */
2579   @Override
2580   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2581   {
2582     if (viewport.cursorMode)
2583     {
2584       alignPanel.getSeqPanel().keyboardNo1 = null;
2585       alignPanel.getSeqPanel().keyboardNo2 = null;
2586     }
2587     viewport.setSelectionGroup(null);
2588     viewport.getColumnSelection().clear();
2589     viewport.setSearchResults(null);
2590     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2591     // JAL-2034 - should delegate to
2592     // alignPanel to decide if overview needs
2593     // updating.
2594     alignPanel.paintAlignment(false, false);
2595     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2596     viewport.sendSelection();
2597   }
2598
2599   /**
2600    * DOCUMENT ME!
2601    * 
2602    * @param e
2603    *          DOCUMENT ME!
2604    */
2605   @Override
2606   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2607   {
2608     SequenceGroup sg = viewport.getSelectionGroup();
2609
2610     if (sg == null)
2611     {
2612       selectAllSequenceMenuItem_actionPerformed(null);
2613
2614       return;
2615     }
2616
2617     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2618     {
2619       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2620     }
2621     // JAL-2034 - should delegate to
2622     // alignPanel to decide if overview needs
2623     // updating.
2624
2625     alignPanel.paintAlignment(true, false);
2626     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2627     viewport.sendSelection();
2628   }
2629
2630   @Override
2631   public void invertColSel_actionPerformed(ActionEvent e)
2632   {
2633     viewport.invertColumnSelection();
2634     alignPanel.paintAlignment(true, false);
2635     viewport.sendSelection();
2636   }
2637
2638   /**
2639    * DOCUMENT ME!
2640    * 
2641    * @param e
2642    *          DOCUMENT ME!
2643    */
2644   @Override
2645   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2646   {
2647     trimAlignment(true);
2648   }
2649
2650   /**
2651    * DOCUMENT ME!
2652    * 
2653    * @param e
2654    *          DOCUMENT ME!
2655    */
2656   @Override
2657   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2658   {
2659     trimAlignment(false);
2660   }
2661
2662   void trimAlignment(boolean trimLeft)
2663   {
2664     ColumnSelection colSel = viewport.getColumnSelection();
2665     int column;
2666
2667     if (!colSel.isEmpty())
2668     {
2669       if (trimLeft)
2670       {
2671         column = colSel.getMin();
2672       }
2673       else
2674       {
2675         column = colSel.getMax();
2676       }
2677
2678       SequenceI[] seqs;
2679       if (viewport.getSelectionGroup() != null)
2680       {
2681         seqs = viewport.getSelectionGroup()
2682                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2683       }
2684       else
2685       {
2686         seqs = viewport.getAlignment().getSequencesArray();
2687       }
2688
2689       TrimRegionCommand trimRegion;
2690       if (trimLeft)
2691       {
2692         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2693                 column, viewport.getAlignment());
2694         viewport.getRanges().setStartRes(0);
2695       }
2696       else
2697       {
2698         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2699                 column, viewport.getAlignment());
2700       }
2701
2702       setStatus(MessageManager.formatMessage("label.removed_columns",
2703               new String[]
2704               { Integer.valueOf(trimRegion.getSize()).toString() }));
2705
2706       addHistoryItem(trimRegion);
2707
2708       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2709       {
2710         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2711                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2712         {
2713           viewport.getAlignment().deleteGroup(sg);
2714         }
2715       }
2716
2717       viewport.firePropertyChange("alignment", null,
2718               viewport.getAlignment().getSequences());
2719     }
2720   }
2721
2722   /**
2723    * DOCUMENT ME!
2724    * 
2725    * @param e
2726    *          DOCUMENT ME!
2727    */
2728   @Override
2729   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2730   {
2731     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2732
2733     SequenceI[] seqs;
2734     if (viewport.getSelectionGroup() != null)
2735     {
2736       seqs = viewport.getSelectionGroup()
2737               .getSequencesAsArray(viewport.getHiddenRepSequences());
2738       start = viewport.getSelectionGroup().getStartRes();
2739       end = viewport.getSelectionGroup().getEndRes();
2740     }
2741     else
2742     {
2743       seqs = viewport.getAlignment().getSequencesArray();
2744     }
2745
2746     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2747             "Remove Gapped Columns", seqs, start, end,
2748             viewport.getAlignment());
2749
2750     addHistoryItem(removeGapCols);
2751
2752     setStatus(MessageManager.formatMessage("label.removed_empty_columns",
2753             new Object[]
2754             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2755
2756     // This is to maintain viewport position on first residue
2757     // of first sequence
2758     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2759     ViewportRanges ranges = viewport.getRanges();
2760     int startRes = seq.findPosition(ranges.getStartRes());
2761     // ShiftList shifts;
2762     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2763     // edit.alColumnChanges=shifts.getInverse();
2764     // if (viewport.hasHiddenColumns)
2765     // viewport.getColumnSelection().compensateForEdits(shifts);
2766     ranges.setStartRes(seq.findIndex(startRes) - 1);
2767     viewport.firePropertyChange("alignment", null,
2768             viewport.getAlignment().getSequences());
2769
2770   }
2771
2772   /**
2773    * DOCUMENT ME!
2774    * 
2775    * @param e
2776    *          DOCUMENT ME!
2777    */
2778   @Override
2779   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2780   {
2781     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2782
2783     SequenceI[] seqs;
2784     if (viewport.getSelectionGroup() != null)
2785     {
2786       seqs = viewport.getSelectionGroup()
2787               .getSequencesAsArray(viewport.getHiddenRepSequences());
2788       start = viewport.getSelectionGroup().getStartRes();
2789       end = viewport.getSelectionGroup().getEndRes();
2790     }
2791     else
2792     {
2793       seqs = viewport.getAlignment().getSequencesArray();
2794     }
2795
2796     // This is to maintain viewport position on first residue
2797     // of first sequence
2798     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2799     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2800
2801     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2802             viewport.getAlignment()));
2803
2804     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2805
2806     viewport.firePropertyChange("alignment", null,
2807             viewport.getAlignment().getSequences());
2808
2809   }
2810
2811   /**
2812    * DOCUMENT ME!
2813    * 
2814    * @param e
2815    *          DOCUMENT ME!
2816    */
2817   @Override
2818   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2819   {
2820     viewport.setPadGaps(padGapsMenuitem.isSelected());
2821     viewport.firePropertyChange("alignment", null,
2822             viewport.getAlignment().getSequences());
2823   }
2824
2825   /**
2826    * Opens a Finder dialog
2827    * 
2828    * @param e
2829    */
2830   @Override
2831   public void findMenuItem_actionPerformed(ActionEvent e)
2832   {
2833     new Finder(alignPanel, false, null);
2834   }
2835
2836   /**
2837    * Create a new view of the current alignment.
2838    */
2839   @Override
2840   public void newView_actionPerformed(ActionEvent e)
2841   {
2842     newView(null, true);
2843   }
2844
2845   /**
2846    * Creates and shows a new view of the current alignment.
2847    * 
2848    * @param viewTitle
2849    *          title of newly created view; if null, one will be generated
2850    * @param copyAnnotation
2851    *          if true then duplicate all annnotation, groups and settings
2852    * @return new alignment panel, already displayed.
2853    */
2854   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2855   {
2856     /*
2857      * Create a new AlignmentPanel (with its own, new Viewport)
2858      */
2859     AlignmentPanel newap = new jalview.project.Jalview2XML()
2860             .copyAlignPanel(alignPanel);
2861     if (!copyAnnotation)
2862     {
2863       /*
2864        * remove all groups and annotation except for the automatic stuff
2865        */
2866       newap.av.getAlignment().deleteAllGroups();
2867       newap.av.getAlignment().deleteAllAnnotations(false);
2868     }
2869
2870     newap.av.setGatherViewsHere(false);
2871
2872     if (viewport.getViewName() == null)
2873     {
2874       viewport.setViewName(
2875               MessageManager.getString("label.view_name_original"));
2876     }
2877
2878     /*
2879      * Views share the same edits undo and redo stacks
2880      */
2881     newap.av.setHistoryList(viewport.getHistoryList());
2882     newap.av.setRedoList(viewport.getRedoList());
2883
2884     /*
2885      * copy any visualisation settings that are not saved in the project
2886      */
2887     newap.av.setColourAppliesToAllGroups(
2888             viewport.getColourAppliesToAllGroups());
2889
2890     /*
2891      * Views share the same mappings; need to deregister any new mappings
2892      * created by copyAlignPanel, and register the new reference to the shared
2893      * mappings
2894      */
2895     newap.av.replaceMappings(viewport.getAlignment());
2896
2897     /*
2898      * start up cDNA consensus (if applicable) now mappings are in place
2899      */
2900     if (newap.av.initComplementConsensus())
2901     {
2902       newap.refresh(true); // adjust layout of annotations
2903     }
2904
2905     newap.av.setViewName(getNewViewName(viewTitle));
2906
2907     addAlignmentPanel(newap, true);
2908     newap.alignmentChanged();
2909
2910     if (alignPanels.size() == 2)
2911     {
2912       viewport.setGatherViewsHere(true);
2913     }
2914     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2915     return newap;
2916   }
2917
2918   /**
2919    * Make a new name for the view, ensuring it is unique within the current
2920    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2921    * these now use viewId. Unique view names are still desirable for usability.)
2922    * 
2923    * @param viewTitle
2924    * @return
2925    */
2926   protected String getNewViewName(String viewTitle)
2927   {
2928     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2929     boolean addFirstIndex = false;
2930     if (viewTitle == null || viewTitle.trim().length() == 0)
2931     {
2932       viewTitle = MessageManager.getString("action.view");
2933       addFirstIndex = true;
2934     }
2935     else
2936     {
2937       index = 1;// we count from 1 if given a specific name
2938     }
2939     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2940
2941     List<Component> comps = PaintRefresher.components
2942             .get(viewport.getSequenceSetId());
2943
2944     List<String> existingNames = getExistingViewNames(comps);
2945
2946     while (existingNames.contains(newViewName))
2947     {
2948       newViewName = viewTitle + " " + (++index);
2949     }
2950     return newViewName;
2951   }
2952
2953   /**
2954    * Returns a list of distinct view names found in the given list of
2955    * components. View names are held on the viewport of an AlignmentPanel.
2956    * 
2957    * @param comps
2958    * @return
2959    */
2960   protected List<String> getExistingViewNames(List<Component> comps)
2961   {
2962     List<String> existingNames = new ArrayList<>();
2963     for (Component comp : comps)
2964     {
2965       if (comp instanceof AlignmentPanel)
2966       {
2967         AlignmentPanel ap = (AlignmentPanel) comp;
2968         if (!existingNames.contains(ap.av.getViewName()))
2969         {
2970           existingNames.add(ap.av.getViewName());
2971         }
2972       }
2973     }
2974     return existingNames;
2975   }
2976
2977   /**
2978    * Explode tabbed views into separate windows.
2979    */
2980   @Override
2981   public void expandViews_actionPerformed(ActionEvent e)
2982   {
2983     Desktop.explodeViews(this);
2984   }
2985
2986   /**
2987    * Gather views in separate windows back into a tabbed presentation.
2988    */
2989   @Override
2990   public void gatherViews_actionPerformed(ActionEvent e)
2991   {
2992     Desktop.instance.gatherViews(this);
2993   }
2994
2995   /**
2996    * DOCUMENT ME!
2997    * 
2998    * @param e
2999    *          DOCUMENT ME!
3000    */
3001   @Override
3002   public void font_actionPerformed(ActionEvent e)
3003   {
3004     new FontChooser(alignPanel);
3005   }
3006
3007   /**
3008    * DOCUMENT ME!
3009    * 
3010    * @param e
3011    *          DOCUMENT ME!
3012    */
3013   @Override
3014   protected void seqLimit_actionPerformed(ActionEvent e)
3015   {
3016     viewport.setShowJVSuffix(seqLimits.isSelected());
3017
3018     alignPanel.getIdPanel().getIdCanvas()
3019             .setPreferredSize(alignPanel.calculateIdWidth());
3020     alignPanel.paintAlignment(true, false);
3021   }
3022
3023   @Override
3024   public void idRightAlign_actionPerformed(ActionEvent e)
3025   {
3026     viewport.setRightAlignIds(idRightAlign.isSelected());
3027     alignPanel.paintAlignment(false, false);
3028   }
3029
3030   @Override
3031   public void centreColumnLabels_actionPerformed(ActionEvent e)
3032   {
3033     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
3034     alignPanel.paintAlignment(false, false);
3035   }
3036
3037   /*
3038    * (non-Javadoc)
3039    * 
3040    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
3041    */
3042   @Override
3043   protected void followHighlight_actionPerformed()
3044   {
3045     /*
3046      * Set the 'follow' flag on the Viewport (and scroll to position if now
3047      * true).
3048      */
3049     final boolean state = this.followHighlightMenuItem.getState();
3050     viewport.setFollowHighlight(state);
3051     if (state)
3052     {
3053       alignPanel.scrollToPosition(viewport.getSearchResults());
3054     }
3055   }
3056
3057   /**
3058    * DOCUMENT ME!
3059    * 
3060    * @param e
3061    *          DOCUMENT ME!
3062    */
3063   @Override
3064   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
3065   {
3066     viewport.setColourText(colourTextMenuItem.isSelected());
3067     alignPanel.paintAlignment(false, false);
3068   }
3069
3070   /**
3071    * DOCUMENT ME!
3072    * 
3073    * @param e
3074    *          DOCUMENT ME!
3075    */
3076   @Override
3077   public void wrapMenuItem_actionPerformed(ActionEvent e)
3078   {
3079     scaleAbove.setVisible(wrapMenuItem.isSelected());
3080     scaleLeft.setVisible(wrapMenuItem.isSelected());
3081     scaleRight.setVisible(wrapMenuItem.isSelected());
3082     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3083     alignPanel.updateLayout();
3084   }
3085
3086   @Override
3087   public void showAllSeqs_actionPerformed(ActionEvent e)
3088   {
3089     viewport.showAllHiddenSeqs();
3090   }
3091
3092   @Override
3093   public void showAllColumns_actionPerformed(ActionEvent e)
3094   {
3095     viewport.showAllHiddenColumns();
3096     alignPanel.paintAlignment(true, true);
3097     viewport.sendSelection();
3098   }
3099
3100   @Override
3101   public void hideSelSequences_actionPerformed(ActionEvent e)
3102   {
3103     viewport.hideAllSelectedSeqs();
3104   }
3105
3106   /**
3107    * called by key handler and the hide all/show all menu items
3108    * 
3109    * @param toggleSeqs
3110    * @param toggleCols
3111    */
3112   protected void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3113   {
3114
3115     boolean hide = false;
3116     SequenceGroup sg = viewport.getSelectionGroup();
3117     if (!toggleSeqs && !toggleCols)
3118     {
3119       // Hide everything by the current selection - this is a hack - we do the
3120       // invert and then hide
3121       // first check that there will be visible columns after the invert.
3122       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3123               && sg.getStartRes() <= sg.getEndRes()))
3124       {
3125         // now invert the sequence set, if required - empty selection implies
3126         // that no hiding is required.
3127         if (sg != null)
3128         {
3129           invertSequenceMenuItem_actionPerformed(null);
3130           sg = viewport.getSelectionGroup();
3131           toggleSeqs = true;
3132
3133         }
3134         viewport.expandColSelection(sg, true);
3135         // finally invert the column selection and get the new sequence
3136         // selection.
3137         invertColSel_actionPerformed(null);
3138         toggleCols = true;
3139       }
3140     }
3141
3142     if (toggleSeqs)
3143     {
3144       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3145       {
3146         hideSelSequences_actionPerformed(null);
3147         hide = true;
3148       }
3149       else if (!(toggleCols && viewport.hasSelectedColumns()))
3150       {
3151         showAllSeqs_actionPerformed(null);
3152       }
3153     }
3154
3155     if (toggleCols)
3156     {
3157       if (viewport.hasSelectedColumns())
3158       {
3159         hideSelColumns_actionPerformed(null);
3160         if (!toggleSeqs)
3161         {
3162           viewport.setSelectionGroup(sg);
3163         }
3164       }
3165       else if (!hide)
3166       {
3167         showAllColumns_actionPerformed(null);
3168       }
3169     }
3170   }
3171
3172   /*
3173    * (non-Javadoc)
3174    * 
3175    * @see
3176    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3177    * event.ActionEvent)
3178    */
3179   @Override
3180   public void hideAllButSelection_actionPerformed(ActionEvent e)
3181   {
3182     toggleHiddenRegions(false, false);
3183     viewport.sendSelection();
3184   }
3185
3186   /*
3187    * (non-Javadoc)
3188    * 
3189    * @see
3190    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3191    * .ActionEvent)
3192    */
3193   @Override
3194   public void hideAllSelection_actionPerformed(ActionEvent e)
3195   {
3196     SequenceGroup sg = viewport.getSelectionGroup();
3197     viewport.expandColSelection(sg, false);
3198     viewport.hideAllSelectedSeqs();
3199     viewport.hideSelectedColumns();
3200     alignPanel.updateLayout();
3201     alignPanel.paintAlignment(true, true);
3202     viewport.sendSelection();
3203   }
3204
3205   /*
3206    * (non-Javadoc)
3207    * 
3208    * @see
3209    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3210    * ActionEvent)
3211    */
3212   @Override
3213   public void showAllhidden_actionPerformed(ActionEvent e)
3214   {
3215     viewport.showAllHiddenColumns();
3216     viewport.showAllHiddenSeqs();
3217     alignPanel.paintAlignment(true, true);
3218     viewport.sendSelection();
3219   }
3220
3221   @Override
3222   public void hideSelColumns_actionPerformed(ActionEvent e)
3223   {
3224     viewport.hideSelectedColumns();
3225     alignPanel.updateLayout();
3226     alignPanel.paintAlignment(true, true);
3227     viewport.sendSelection();
3228   }
3229
3230   @Override
3231   public void hiddenMarkers_actionPerformed(ActionEvent e)
3232   {
3233     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3234     repaint();
3235   }
3236
3237   /**
3238    * DOCUMENT ME!
3239    * 
3240    * @param e
3241    *          DOCUMENT ME!
3242    */
3243   @Override
3244   protected void scaleAbove_actionPerformed(ActionEvent e)
3245   {
3246     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3247     alignPanel.updateLayout();
3248     alignPanel.paintAlignment(true, false);
3249   }
3250
3251   /**
3252    * DOCUMENT ME!
3253    * 
3254    * @param e
3255    *          DOCUMENT ME!
3256    */
3257   @Override
3258   protected void scaleLeft_actionPerformed(ActionEvent e)
3259   {
3260     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3261     alignPanel.updateLayout();
3262     alignPanel.paintAlignment(true, false);
3263   }
3264
3265   /**
3266    * DOCUMENT ME!
3267    * 
3268    * @param e
3269    *          DOCUMENT ME!
3270    */
3271   @Override
3272   protected void scaleRight_actionPerformed(ActionEvent e)
3273   {
3274     viewport.setScaleRightWrapped(scaleRight.isSelected());
3275     alignPanel.updateLayout();
3276     alignPanel.paintAlignment(true, false);
3277   }
3278
3279   /**
3280    * DOCUMENT ME!
3281    * 
3282    * @param e
3283    *          DOCUMENT ME!
3284    */
3285   @Override
3286   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3287   {
3288     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3289     alignPanel.paintAlignment(false, false);
3290   }
3291
3292   /**
3293    * DOCUMENT ME!
3294    * 
3295    * @param e
3296    *          DOCUMENT ME!
3297    */
3298   @Override
3299   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3300   {
3301     viewport.setShowText(viewTextMenuItem.isSelected());
3302     alignPanel.paintAlignment(false, false);
3303   }
3304
3305   /**
3306    * DOCUMENT ME!
3307    * 
3308    * @param e
3309    *          DOCUMENT ME!
3310    */
3311   @Override
3312   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3313   {
3314     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3315     alignPanel.paintAlignment(false, false);
3316   }
3317
3318   public FeatureSettings featureSettings;
3319
3320   @Override
3321   public FeatureSettingsControllerI getFeatureSettingsUI()
3322   {
3323     return featureSettings;
3324   }
3325
3326   @Override
3327   public void featureSettings_actionPerformed(ActionEvent e)
3328   {
3329     showFeatureSettingsUI();
3330   }
3331
3332   @Override
3333   public FeatureSettingsControllerI showFeatureSettingsUI()
3334   {
3335     if (featureSettings != null)
3336     {
3337       featureSettings.closeOldSettings();
3338       featureSettings = null;
3339     }
3340     if (!showSeqFeatures.isSelected())
3341     {
3342       // make sure features are actually displayed
3343       showSeqFeatures.setSelected(true);
3344       showSeqFeatures_actionPerformed(null);
3345     }
3346     featureSettings = new FeatureSettings(this);
3347     return featureSettings;
3348   }
3349
3350   /**
3351    * Set or clear 'Show Sequence Features'
3352    * 
3353    * @param evt
3354    *          DOCUMENT ME!
3355    */
3356   @Override
3357   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3358   {
3359     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3360     alignPanel.paintAlignment(true, true);
3361   }
3362
3363   /**
3364    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3365    * the annotations panel as a whole.
3366    * 
3367    * The options to show/hide all annotations should be enabled when the panel
3368    * is shown, and disabled when the panel is hidden.
3369    * 
3370    * @param e
3371    */
3372   @Override
3373   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3374   {
3375     final boolean setVisible = annotationPanelMenuItem.isSelected();
3376     viewport.setShowAnnotation(setVisible);
3377     this.showAllSeqAnnotations.setEnabled(setVisible);
3378     this.hideAllSeqAnnotations.setEnabled(setVisible);
3379     this.showAllAlAnnotations.setEnabled(setVisible);
3380     this.hideAllAlAnnotations.setEnabled(setVisible);
3381     alignPanel.updateLayout();
3382   }
3383
3384   @Override
3385   public void alignmentProperties()
3386   {
3387     JComponent pane;
3388     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3389
3390             .formatAsHtml();
3391     String content = MessageManager.formatMessage("label.html_content",
3392             new Object[]
3393             { contents.toString() });
3394     contents = null;
3395
3396     if (Platform.isJS())
3397     {
3398       JLabel textLabel = new JLabel();
3399       textLabel.setText(content);
3400       textLabel.setBackground(Color.WHITE);
3401
3402       pane = new JPanel(new BorderLayout());
3403       ((JPanel) pane).setOpaque(true);
3404       pane.setBackground(Color.WHITE);
3405       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3406     }
3407     else
3408     /**
3409      * Java only
3410      * 
3411      * @j2sIgnore
3412      */
3413     {
3414       JEditorPane editPane = new JEditorPane("text/html", "");
3415       editPane.setEditable(false);
3416       editPane.setText(content);
3417       pane = editPane;
3418     }
3419
3420     JInternalFrame frame = new JInternalFrame();
3421
3422     frame.getContentPane().add(new JScrollPane(pane));
3423
3424     Desktop.addInternalFrame(frame, MessageManager
3425             .formatMessage("label.alignment_properties", new Object[]
3426             { getTitle() }), 500, 400);
3427   }
3428
3429   /**
3430    * DOCUMENT ME!
3431    * 
3432    * @param e
3433    *          DOCUMENT ME!
3434    */
3435   @Override
3436   public void overviewMenuItem_actionPerformed(ActionEvent e)
3437   {
3438     if (alignPanel.overviewPanel != null)
3439     {
3440       return;
3441     }
3442
3443     JInternalFrame frame = new JInternalFrame();
3444     final OverviewPanel overview = new OverviewPanel(alignPanel);
3445     frame.setContentPane(overview);
3446     Desktop.addInternalFrame(frame, MessageManager
3447             .formatMessage("label.overview_params", new Object[]
3448             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3449             true, true);
3450     frame.pack();
3451     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3452     frame.addInternalFrameListener(
3453             new javax.swing.event.InternalFrameAdapter()
3454             {
3455               @Override
3456               public void internalFrameClosed(
3457                       javax.swing.event.InternalFrameEvent evt)
3458               {
3459                 overview.dispose();
3460                 alignPanel.setOverviewPanel(null);
3461               }
3462             });
3463     if (getKeyListeners().length > 0)
3464     {
3465       frame.addKeyListener(getKeyListeners()[0]);
3466     }
3467
3468     alignPanel.setOverviewPanel(overview);
3469   }
3470
3471   @Override
3472   public void textColour_actionPerformed()
3473   {
3474     new TextColourChooser().chooseColour(alignPanel, null);
3475   }
3476
3477   /*
3478    * public void covariationColour_actionPerformed() {
3479    * changeColour(new
3480    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3481    * ()[0])); }
3482    */
3483   @Override
3484   public void annotationColour_actionPerformed()
3485   {
3486     new AnnotationColourChooser(viewport, alignPanel);
3487   }
3488
3489   @Override
3490   public void annotationColumn_actionPerformed(ActionEvent e)
3491   {
3492     new AnnotationColumnChooser(viewport, alignPanel);
3493   }
3494
3495   /**
3496    * Action on the user checking or unchecking the option to apply the selected
3497    * colour scheme to all groups. If unchecked, groups may have their own
3498    * independent colour schemes.
3499    * 
3500    * @param selected
3501    */
3502   @Override
3503   public void applyToAllGroups_actionPerformed(boolean selected)
3504   {
3505     viewport.setColourAppliesToAllGroups(selected);
3506   }
3507
3508   /**
3509    * Action on user selecting a colour from the colour menu
3510    * 
3511    * @param name
3512    *          the name (not the menu item label!) of the colour scheme
3513    */
3514   @Override
3515   public void changeColour_actionPerformed(String name)
3516   {
3517     /*
3518      * 'User Defined' opens a panel to configure or load a
3519      * user-defined colour scheme
3520      */
3521     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3522     {
3523       new UserDefinedColours(alignPanel);
3524       return;
3525     }
3526
3527     /*
3528      * otherwise set the chosen colour scheme (or null for 'None')
3529      */
3530     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3531             viewport, viewport.getAlignment(),
3532             viewport.getHiddenRepSequences());
3533     changeColour(cs);
3534   }
3535
3536   /**
3537    * Actions on setting or changing the alignment colour scheme
3538    * 
3539    * @param cs
3540    */
3541   @Override
3542   public void changeColour(ColourSchemeI cs)
3543   {
3544     // TODO: pull up to controller method
3545     ColourMenuHelper.setColourSelected(colourMenu, cs);
3546
3547     viewport.setGlobalColourScheme(cs);
3548
3549     alignPanel.paintAlignment(true, true);
3550   }
3551
3552   /**
3553    * Show the PID threshold slider panel
3554    */
3555   @Override
3556   protected void modifyPID_actionPerformed()
3557   {
3558     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3559             alignPanel.getViewName());
3560     SliderPanel.showPIDSlider();
3561   }
3562
3563   /**
3564    * Show the Conservation slider panel
3565    */
3566   @Override
3567   protected void modifyConservation_actionPerformed()
3568   {
3569     SliderPanel.setConservationSlider(alignPanel,
3570             viewport.getResidueShading(), alignPanel.getViewName());
3571     SliderPanel.showConservationSlider();
3572   }
3573
3574   /**
3575    * Action on selecting or deselecting (Colour) By Conservation
3576    */
3577   @Override
3578   public void conservationMenuItem_actionPerformed(boolean selected)
3579   {
3580     modifyConservation.setEnabled(selected);
3581     viewport.setConservationSelected(selected);
3582     viewport.getResidueShading().setConservationApplied(selected);
3583
3584     changeColour(viewport.getGlobalColourScheme());
3585     if (selected)
3586     {
3587       modifyConservation_actionPerformed();
3588     }
3589     else
3590     {
3591       SliderPanel.hideConservationSlider();
3592     }
3593   }
3594
3595   /**
3596    * Action on selecting or deselecting (Colour) Above PID Threshold
3597    */
3598   @Override
3599   public void abovePIDThreshold_actionPerformed(boolean selected)
3600   {
3601     modifyPID.setEnabled(selected);
3602     viewport.setAbovePIDThreshold(selected);
3603     if (!selected)
3604     {
3605       viewport.getResidueShading().setThreshold(0,
3606               viewport.isIgnoreGapsConsensus());
3607     }
3608
3609     changeColour(viewport.getGlobalColourScheme());
3610     if (selected)
3611     {
3612       modifyPID_actionPerformed();
3613     }
3614     else
3615     {
3616       SliderPanel.hidePIDSlider();
3617     }
3618   }
3619
3620   /**
3621    * DOCUMENT ME!
3622    * 
3623    * @param e
3624    *          DOCUMENT ME!
3625    */
3626   @Override
3627   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3628   {
3629     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3630     AlignmentSorter.sortByPID(viewport.getAlignment(),
3631             viewport.getAlignment().getSequenceAt(0));
3632     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3633             viewport.getAlignment()));
3634     alignPanel.paintAlignment(true, false);
3635   }
3636
3637   /**
3638    * DOCUMENT ME!
3639    * 
3640    * @param e
3641    *          DOCUMENT ME!
3642    */
3643   @Override
3644   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3645   {
3646     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3647     AlignmentSorter.sortByID(viewport.getAlignment());
3648     addHistoryItem(
3649             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3650     alignPanel.paintAlignment(true, false);
3651   }
3652
3653   /**
3654    * DOCUMENT ME!
3655    * 
3656    * @param e
3657    *          DOCUMENT ME!
3658    */
3659   @Override
3660   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3661   {
3662     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3663     AlignmentSorter.sortByLength(viewport.getAlignment());
3664     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3665             viewport.getAlignment()));
3666     alignPanel.paintAlignment(true, false);
3667   }
3668
3669   /**
3670    * DOCUMENT ME!
3671    * 
3672    * @param e
3673    *          DOCUMENT ME!
3674    */
3675   @Override
3676   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3677   {
3678     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3679     AlignmentSorter.sortByGroup(viewport.getAlignment());
3680     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3681             viewport.getAlignment()));
3682
3683     alignPanel.paintAlignment(true, false);
3684   }
3685
3686   /**
3687    * DOCUMENT ME!
3688    * 
3689    * @param e
3690    *          DOCUMENT ME!
3691    */
3692   @Override
3693   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3694   {
3695     new RedundancyPanel(alignPanel, this);
3696   }
3697
3698   /**
3699    * DOCUMENT ME!
3700    * 
3701    * @param e
3702    *          DOCUMENT ME!
3703    */
3704   @Override
3705   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3706   {
3707     if ((viewport.getSelectionGroup() == null)
3708             || (viewport.getSelectionGroup().getSize() < 2))
3709     {
3710       JvOptionPane.showInternalMessageDialog(this,
3711               MessageManager.getString(
3712                       "label.you_must_select_least_two_sequences"),
3713               MessageManager.getString("label.invalid_selection"),
3714               JvOptionPane.WARNING_MESSAGE);
3715     }
3716     else
3717     {
3718       JInternalFrame frame = new JInternalFrame();
3719       frame.setContentPane(new PairwiseAlignPanel(viewport));
3720       Desktop.addInternalFrame(frame,
3721               MessageManager.getString("action.pairwise_alignment"), 600,
3722               500);
3723     }
3724   }
3725
3726   @Override
3727   public void autoCalculate_actionPerformed(ActionEvent e)
3728   {
3729     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3730     if (viewport.autoCalculateConsensus)
3731     {
3732       viewport.firePropertyChange("alignment", null,
3733               viewport.getAlignment().getSequences());
3734     }
3735   }
3736
3737   @Override
3738   public void sortByTreeOption_actionPerformed(ActionEvent e)
3739   {
3740     viewport.sortByTree = sortByTree.isSelected();
3741   }
3742
3743   @Override
3744   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3745   {
3746     viewport.followSelection = listenToViewSelections.isSelected();
3747   }
3748
3749   /**
3750    * Constructs a tree panel and adds it to the desktop
3751    * 
3752    * @param type
3753    *          tree type (NJ or AV)
3754    * @param modelName
3755    *          name of score model used to compute the tree
3756    * @param options
3757    *          parameters for the distance or similarity calculation
3758    */
3759   void newTreePanel(String type, String modelName,
3760           SimilarityParamsI options)
3761   {
3762     String frameTitle = "";
3763     TreePanel tp;
3764
3765     boolean onSelection = false;
3766     if (viewport.getSelectionGroup() != null
3767             && viewport.getSelectionGroup().getSize() > 0)
3768     {
3769       SequenceGroup sg = viewport.getSelectionGroup();
3770
3771       /* Decide if the selection is a column region */
3772       for (SequenceI _s : sg.getSequences())
3773       {
3774         if (_s.getLength() < sg.getEndRes())
3775         {
3776           JvOptionPane.showMessageDialog(Desktop.desktop,
3777                   MessageManager.getString(
3778                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3779                   MessageManager.getString(
3780                           "label.sequences_selection_not_aligned"),
3781                   JvOptionPane.WARNING_MESSAGE);
3782
3783           return;
3784         }
3785       }
3786       onSelection = true;
3787     }
3788     else
3789     {
3790       if (viewport.getAlignment().getHeight() < 2)
3791       {
3792         return;
3793       }
3794     }
3795
3796     tp = new TreePanel(alignPanel, type, modelName, options);
3797     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3798
3799     frameTitle += " from ";
3800
3801     if (viewport.getViewName() != null)
3802     {
3803       frameTitle += viewport.getViewName() + " of ";
3804     }
3805
3806     frameTitle += this.title;
3807
3808     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3809   }
3810
3811   /**
3812    * DOCUMENT ME!
3813    * 
3814    * @param title
3815    *          DOCUMENT ME!
3816    * @param order
3817    *          DOCUMENT ME!
3818    */
3819   public void addSortByOrderMenuItem(String title,
3820           final AlignmentOrder order)
3821   {
3822     final JMenuItem item = new JMenuItem(MessageManager
3823             .formatMessage("action.by_title_param", new Object[]
3824             { title }));
3825     sort.add(item);
3826     item.addActionListener(new java.awt.event.ActionListener()
3827     {
3828       @Override
3829       public void actionPerformed(ActionEvent e)
3830       {
3831         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3832
3833         // TODO: JBPNote - have to map order entries to curent SequenceI
3834         // pointers
3835         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3836
3837         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3838                 viewport.getAlignment()));
3839
3840         alignPanel.paintAlignment(true, false);
3841       }
3842     });
3843   }
3844
3845   /**
3846    * Add a new sort by annotation score menu item
3847    * 
3848    * @param sort
3849    *          the menu to add the option to
3850    * @param scoreLabel
3851    *          the label used to retrieve scores for each sequence on the
3852    *          alignment
3853    */
3854   public void addSortByAnnotScoreMenuItem(JMenu sort,
3855           final String scoreLabel)
3856   {
3857     final JMenuItem item = new JMenuItem(scoreLabel);
3858     sort.add(item);
3859     item.addActionListener(new java.awt.event.ActionListener()
3860     {
3861       @Override
3862       public void actionPerformed(ActionEvent e)
3863       {
3864         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3865         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3866                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3867         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3868                 viewport.getAlignment()));
3869         alignPanel.paintAlignment(true, false);
3870       }
3871     });
3872   }
3873
3874   /**
3875    * last hash for alignment's annotation array - used to minimise cost of
3876    * rebuild.
3877    */
3878   protected int _annotationScoreVectorHash;
3879
3880   /**
3881    * search the alignment and rebuild the sort by annotation score submenu the
3882    * last alignment annotation vector hash is stored to minimize cost of
3883    * rebuilding in subsequence calls.
3884    * 
3885    */
3886   @Override
3887   public void buildSortByAnnotationScoresMenu()
3888   {
3889     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3890     {
3891       return;
3892     }
3893
3894     if (viewport.getAlignment().getAlignmentAnnotation()
3895             .hashCode() != _annotationScoreVectorHash)
3896     {
3897       sortByAnnotScore.removeAll();
3898       // almost certainly a quicker way to do this - but we keep it simple
3899       Hashtable<String, String> scoreSorts = new Hashtable<>();
3900       AlignmentAnnotation aann[];
3901       for (SequenceI sqa : viewport.getAlignment().getSequences())
3902       {
3903         aann = sqa.getAnnotation();
3904         for (int i = 0; aann != null && i < aann.length; i++)
3905         {
3906           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3907           {
3908             scoreSorts.put(aann[i].label, aann[i].label);
3909           }
3910         }
3911       }
3912       Enumeration<String> labels = scoreSorts.keys();
3913       while (labels.hasMoreElements())
3914       {
3915         addSortByAnnotScoreMenuItem(sortByAnnotScore, labels.nextElement());
3916       }
3917       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3918       scoreSorts.clear();
3919
3920       _annotationScoreVectorHash = viewport.getAlignment()
3921               .getAlignmentAnnotation().hashCode();
3922     }
3923   }
3924
3925   /**
3926    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3927    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3928    * call. Listeners are added to remove the menu item when the treePanel is
3929    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3930    * modified.
3931    */
3932   @Override
3933   public void buildTreeSortMenu()
3934   {
3935     sortByTreeMenu.removeAll();
3936
3937     List<Component> comps = PaintRefresher.components
3938             .get(viewport.getSequenceSetId());
3939     List<TreePanel> treePanels = new ArrayList<>();
3940     for (Component comp : comps)
3941     {
3942       if (comp instanceof TreePanel)
3943       {
3944         treePanels.add((TreePanel) comp);
3945       }
3946     }
3947
3948     if (treePanels.size() < 1)
3949     {
3950       sortByTreeMenu.setVisible(false);
3951       return;
3952     }
3953
3954     sortByTreeMenu.setVisible(true);
3955
3956     for (final TreePanel tp : treePanels)
3957     {
3958       final JMenuItem item = new JMenuItem(tp.getTitle());
3959       item.addActionListener(new java.awt.event.ActionListener()
3960       {
3961         @Override
3962         public void actionPerformed(ActionEvent e)
3963         {
3964           tp.sortByTree_actionPerformed();
3965           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3966
3967         }
3968       });
3969
3970       sortByTreeMenu.add(item);
3971     }
3972   }
3973
3974   public boolean sortBy(AlignmentOrder alorder, String undoname)
3975   {
3976     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3977     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3978     if (undoname != null)
3979     {
3980       addHistoryItem(new OrderCommand(undoname, oldOrder,
3981               viewport.getAlignment()));
3982     }
3983     alignPanel.paintAlignment(true, false);
3984     return true;
3985   }
3986
3987   /**
3988    * Work out whether the whole set of sequences or just the selected set will
3989    * be submitted for multiple alignment.
3990    * 
3991    */
3992   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3993   {
3994     // Now, check we have enough sequences
3995     AlignmentView msa = null;
3996
3997     if ((viewport.getSelectionGroup() != null)
3998             && (viewport.getSelectionGroup().getSize() > 1))
3999     {
4000       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4001       // some common interface!
4002       /*
4003        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4004        * SequenceI[sz = seqs.getSize(false)];
4005        * 
4006        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4007        * seqs.getSequenceAt(i); }
4008        */
4009       msa = viewport.getAlignmentView(true);
4010     }
4011     else if (viewport.getSelectionGroup() != null
4012             && viewport.getSelectionGroup().getSize() == 1)
4013     {
4014       int option = JvOptionPane.showConfirmDialog(this,
4015               MessageManager.getString("warn.oneseq_msainput_selection"),
4016               MessageManager.getString("label.invalid_selection"),
4017               JvOptionPane.OK_CANCEL_OPTION);
4018       if (option == JvOptionPane.OK_OPTION)
4019       {
4020         msa = viewport.getAlignmentView(false);
4021       }
4022     }
4023     else
4024     {
4025       msa = viewport.getAlignmentView(false);
4026     }
4027     return msa;
4028   }
4029
4030   /**
4031    * Decides what is submitted to a secondary structure prediction service: the
4032    * first sequence in the alignment, or in the current selection, or, if the
4033    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4034    * region or the whole alignment. (where the first sequence in the set is the
4035    * one that the prediction will be for).
4036    */
4037   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4038   {
4039     AlignmentView seqs = null;
4040
4041     if ((viewport.getSelectionGroup() != null)
4042             && (viewport.getSelectionGroup().getSize() > 0))
4043     {
4044       seqs = viewport.getAlignmentView(true);
4045     }
4046     else
4047     {
4048       seqs = viewport.getAlignmentView(false);
4049     }
4050     // limit sequences - JBPNote in future - could spawn multiple prediction
4051     // jobs
4052     // TODO: viewport.getAlignment().isAligned is a global state - the local
4053     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4054     if (!viewport.getAlignment().isAligned(false))
4055     {
4056       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
4057       // TODO: if seqs.getSequences().length>1 then should really have warned
4058       // user!
4059
4060     }
4061     return seqs;
4062   }
4063
4064   /**
4065    * DOCUMENT ME!
4066    * 
4067    * @param e
4068    *          DOCUMENT ME!
4069    */
4070   @Override
4071   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
4072   {
4073     // Pick the tree file
4074     JalviewFileChooser chooser = new JalviewFileChooser(
4075             Cache.getProperty("LAST_DIRECTORY"));
4076     chooser.setFileView(new JalviewFileView());
4077     chooser.setDialogTitle(
4078             MessageManager.getString("label.select_newick_like_tree_file"));
4079     chooser.setToolTipText(
4080             MessageManager.getString("label.load_tree_file"));
4081
4082     chooser.setResponseHandler(0, new Runnable()
4083     {
4084       @Override
4085       public void run()
4086       {
4087         String filePath = chooser.getSelectedFile().getPath();
4088         Cache.setProperty("LAST_DIRECTORY", filePath);
4089         NewickFile fin = null;
4090         try
4091         {
4092           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4093                   DataSourceType.FILE));
4094           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4095         } catch (Exception ex)
4096         {
4097           JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4098                   MessageManager
4099                           .getString("label.problem_reading_tree_file"),
4100                   JvOptionPane.WARNING_MESSAGE);
4101           ex.printStackTrace();
4102         }
4103         if (fin != null && fin.hasWarningMessage())
4104         {
4105           JvOptionPane.showMessageDialog(Desktop.desktop,
4106                   fin.getWarningMessage(),
4107                   MessageManager.getString(
4108                           "label.possible_problem_with_tree_file"),
4109                   JvOptionPane.WARNING_MESSAGE);
4110         }
4111       }
4112     });
4113     chooser.showOpenDialog(this);
4114   }
4115
4116   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4117   {
4118     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4119   }
4120
4121   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4122           int h, int x, int y)
4123   {
4124     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4125   }
4126
4127   /**
4128    * Add a treeviewer for the tree extracted from a Newick file object to the
4129    * current alignment view
4130    * 
4131    * @param nf
4132    *          the tree
4133    * @param title
4134    *          tree viewer title
4135    * @param input
4136    *          Associated alignment input data (or null)
4137    * @param w
4138    *          width
4139    * @param h
4140    *          height
4141    * @param x
4142    *          position
4143    * @param y
4144    *          position
4145    * @return TreePanel handle
4146    */
4147   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4148           AlignmentView input, int w, int h, int x, int y)
4149   {
4150     TreePanel tp = null;
4151
4152     try
4153     {
4154       nf.parse();
4155
4156       if (nf.getTree() != null)
4157       {
4158         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4159
4160         tp.setSize(w, h);
4161
4162         if (x > 0 && y > 0)
4163         {
4164           tp.setLocation(x, y);
4165         }
4166
4167         Desktop.addInternalFrame(tp, treeTitle, w, h);
4168       }
4169     } catch (Exception ex)
4170     {
4171       ex.printStackTrace();
4172     }
4173
4174     return tp;
4175   }
4176
4177   private boolean buildingMenu = false;
4178
4179   /**
4180    * Generates menu items and listener event actions for web service clients
4181    * 
4182    */
4183   public void BuildWebServiceMenu()
4184   {
4185     while (buildingMenu)
4186     {
4187       try
4188       {
4189         System.err.println("Waiting for building menu to finish.");
4190         Thread.sleep(10);
4191       } catch (Exception e)
4192       {
4193       }
4194     }
4195     final AlignFrame me = this;
4196     buildingMenu = true;
4197     new Thread(new Runnable()
4198     {
4199       @Override
4200       public void run()
4201       {
4202         final List<JMenuItem> legacyItems = new ArrayList<>();
4203         try
4204         {
4205           // System.err.println("Building ws menu again "
4206           // + Thread.currentThread());
4207           // TODO: add support for context dependent disabling of services based
4208           // on
4209           // alignment and current selection
4210           // TODO: add additional serviceHandle parameter to specify abstract
4211           // handler
4212           // class independently of AbstractName
4213           // TODO: add in rediscovery GUI function to restart discoverer
4214           // TODO: group services by location as well as function and/or
4215           // introduce
4216           // object broker mechanism.
4217           final Vector<JMenu> wsmenu = new Vector<>();
4218           final IProgressIndicator af = me;
4219
4220           /*
4221            * do not i18n these strings - they are hard-coded in class
4222            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4223            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4224            */
4225           final JMenu msawsmenu = new JMenu("Alignment");
4226           final JMenu secstrmenu = new JMenu(
4227                   "Secondary Structure Prediction");
4228           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4229           final JMenu analymenu = new JMenu("Analysis");
4230           final JMenu dismenu = new JMenu("Protein Disorder");
4231           // JAL-940 - only show secondary structure prediction services from
4232           // the legacy server
4233           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4234               // &&
4235           Discoverer.services != null && (Discoverer.services.size() > 0))
4236           {
4237             // TODO: refactor to allow list of AbstractName/Handler bindings to
4238             // be
4239             // stored or retrieved from elsewhere
4240             // No MSAWS used any more:
4241             // Vector msaws = null; // (Vector)
4242             // Discoverer.services.get("MsaWS");
4243             Vector<ServiceHandle> secstrpr = Discoverer.services
4244                     .get("SecStrPred");
4245             if (secstrpr != null)
4246             {
4247               // Add any secondary structure prediction services
4248               for (int i = 0, j = secstrpr.size(); i < j; i++)
4249               {
4250                 final ext.vamsas.ServiceHandle sh = secstrpr.get(i);
4251                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4252                         .getServiceClient(sh);
4253                 int p = secstrmenu.getItemCount();
4254                 impl.attachWSMenuEntry(secstrmenu, me);
4255                 int q = secstrmenu.getItemCount();
4256                 for (int litm = p; litm < q; litm++)
4257                 {
4258                   legacyItems.add(secstrmenu.getItem(litm));
4259                 }
4260               }
4261             }
4262           }
4263
4264           // Add all submenus in the order they should appear on the web
4265           // services menu
4266           wsmenu.add(msawsmenu);
4267           wsmenu.add(secstrmenu);
4268           wsmenu.add(dismenu);
4269           wsmenu.add(analymenu);
4270           // No search services yet
4271           // wsmenu.add(seqsrchmenu);
4272
4273           javax.swing.SwingUtilities.invokeLater(new Runnable()
4274           {
4275             @Override
4276             public void run()
4277             {
4278               try
4279               {
4280                 webService.removeAll();
4281                 // first, add discovered services onto the webservices menu
4282                 if (wsmenu.size() > 0)
4283                 {
4284                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4285                   {
4286                     webService.add(wsmenu.get(i));
4287                   }
4288                 }
4289                 else
4290                 {
4291                   webService.add(me.webServiceNoServices);
4292                 }
4293                 // TODO: move into separate menu builder class.
4294                 {
4295                   // logic for 2.11.1.4 is
4296                   // always look to see if there is a discover. if there isn't
4297                   // we can't show any Jws2 services
4298                   // if there are services available, show them - regardless of
4299                   // the 'show JWS2 preference'
4300                   // if the discoverer is running then say so
4301                   // otherwise offer to trigger discovery if 'show JWS2' is not
4302                   // enabled
4303                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4304                   if (jws2servs != null)
4305                   {
4306                     if (jws2servs.hasServices())
4307                     {
4308                       jws2servs.attachWSMenuEntry(webService, me);
4309                       for (Jws2Instance sv : jws2servs.getServices())
4310                       {
4311                         if (sv.description.toLowerCase(Locale.ROOT)
4312                                 .contains("jpred"))
4313                         {
4314                           for (JMenuItem jmi : legacyItems)
4315                           {
4316                             jmi.setVisible(false);
4317                           }
4318                         }
4319                       }
4320                     }
4321
4322                     if (jws2servs.isRunning())
4323                     {
4324                       JMenuItem tm = new JMenuItem(
4325                               "Still discovering JABA Services");
4326                       tm.setEnabled(false);
4327                       webService.add(tm);
4328                     }
4329                     else if (!Cache.getDefault("SHOW_JWS2_SERVICES", true))
4330                     {
4331                       JMenuItem enableJws2 = new JMenuItem(
4332                               "Discover Web Services");
4333                       enableJws2.setToolTipText(
4334                               "Select to start JABA Web Service discovery (or enable option in Web Service preferences)");
4335                       enableJws2.setEnabled(true);
4336                       enableJws2.addActionListener(new ActionListener()
4337                       {
4338
4339                         @Override
4340                         public void actionPerformed(ActionEvent e)
4341                         {
4342                           // start service discoverer, but ignore preference
4343                           Desktop.instance.startServiceDiscovery(false,
4344                                   true);
4345                         }
4346                       });
4347                       webService.add(enableJws2);
4348                     }
4349                   }
4350                 }
4351                 build_urlServiceMenu(me.webService);
4352                 build_fetchdbmenu(webService);
4353                 for (JMenu item : wsmenu)
4354                 {
4355                   if (item.getItemCount() == 0)
4356                   {
4357                     item.setEnabled(false);
4358                   }
4359                   else
4360                   {
4361                     item.setEnabled(true);
4362                   }
4363                 }
4364               } catch (Exception e)
4365               {
4366                 Console.debug(
4367                         "Exception during web service menu building process.",
4368                         e);
4369               }
4370             }
4371           });
4372         } catch (Exception e)
4373         {
4374         }
4375         buildingMenu = false;
4376       }
4377     }).start();
4378
4379   }
4380
4381   /**
4382    * construct any groupURL type service menu entries.
4383    * 
4384    * @param webService
4385    */
4386   protected void build_urlServiceMenu(JMenu webService)
4387   {
4388     // TODO: remove this code when 2.7 is released
4389     // DEBUG - alignmentView
4390     /*
4391      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4392      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4393      * 
4394      * @Override public void actionPerformed(ActionEvent e) {
4395      * jalview.datamodel.AlignmentView
4396      * .testSelectionViews(af.viewport.getAlignment(),
4397      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4398      * 
4399      * }); webService.add(testAlView);
4400      */
4401     // TODO: refactor to RestClient discoverer and merge menu entries for
4402     // rest-style services with other types of analysis/calculation service
4403     // SHmmr test client - still being implemented.
4404     // DEBUG - alignmentView
4405
4406     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4407             .getRestClients())
4408     {
4409       client.attachWSMenuEntry(
4410               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4411               this);
4412     }
4413   }
4414
4415   /**
4416    * Searches the alignment sequences for xRefs and builds the Show
4417    * Cross-References menu (formerly called Show Products), with database
4418    * sources for which cross-references are found (protein sources for a
4419    * nucleotide alignment and vice versa)
4420    * 
4421    * @return true if Show Cross-references menu should be enabled
4422    */
4423   public boolean canShowProducts()
4424   {
4425     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4426     AlignmentI dataset = viewport.getAlignment().getDataset();
4427
4428     showProducts.removeAll();
4429     final boolean dna = viewport.getAlignment().isNucleotide();
4430
4431     if (seqs == null || seqs.length == 0)
4432     {
4433       // nothing to see here.
4434       return false;
4435     }
4436
4437     boolean showp = false;
4438     try
4439     {
4440       List<String> ptypes = new CrossRef(seqs, dataset)
4441               .findXrefSourcesForSequences(dna);
4442
4443       for (final String source : ptypes)
4444       {
4445         showp = true;
4446         final AlignFrame af = this;
4447         JMenuItem xtype = new JMenuItem(source);
4448         xtype.addActionListener(new ActionListener()
4449         {
4450           @Override
4451           public void actionPerformed(ActionEvent e)
4452           {
4453             showProductsFor(af.viewport.getSequenceSelection(), dna,
4454                     source);
4455           }
4456         });
4457         showProducts.add(xtype);
4458       }
4459       showProducts.setVisible(showp);
4460       showProducts.setEnabled(showp);
4461     } catch (Exception e)
4462     {
4463       Console.warn(
4464               "canShowProducts threw an exception - please report to help@jalview.org",
4465               e);
4466       return false;
4467     }
4468     return showp;
4469   }
4470
4471   public List<String> getProducts()
4472   {
4473     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4474     AlignmentI dataset = viewport.getAlignment().getDataset();
4475
4476     boolean dna = viewport.getAlignment().isNucleotide();
4477
4478     if (seqs == null || seqs.length == 0)
4479     {
4480       // nothing to see here.
4481       return null;
4482     }
4483
4484     return new CrossRef(seqs, dataset).findXrefSourcesForSequences(dna);
4485   }
4486
4487   /**
4488    * Finds and displays cross-references for the selected sequences (protein
4489    * products for nucleotide sequences, dna coding sequences for peptides).
4490    * 
4491    * @param sel
4492    *          the sequences to show cross-references for
4493    * @param dna
4494    *          true if from a nucleotide alignment (so showing proteins)
4495    * @param source
4496    *          the database to show cross-references for
4497    */
4498   /*
4499   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4500           final String source)
4501   {
4502     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4503             .start();
4504   }
4505   */
4506   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4507           final String source)
4508   {
4509     showProductsFor(sel, _odna, source, false, null);
4510   }
4511
4512   public CompletableFuture<Void> showProductsFor(final SequenceI[] sel,
4513           final boolean _odna, final String source, boolean returnFuture,
4514           String id)
4515   {
4516     CompletableFuture<Void> cf = CompletableFuture
4517             .runAsync(() -> runCrossRefActionAndCacheAlignFrame(sel, _odna,
4518                     source, returnFuture, id));
4519     return returnFuture ? cf : null;
4520   }
4521
4522   private void runCrossRefActionAndCacheAlignFrame(SequenceI[] sel,
4523           boolean _odna, String source, boolean cacheAlignFrame, String id)
4524   {
4525     final AlignFrame af = this;
4526     CrossRefAction.getHandlerFor(sel, _odna, source, af).run();
4527     af.cacheAlignFrameFromRestId(id);
4528   }
4529
4530   /**
4531    * Construct and display a new frame containing the translation of this
4532    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4533    */
4534   @Override
4535   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4536   {
4537     AlignmentI al = null;
4538     try
4539     {
4540       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4541
4542       al = dna.translateCdna(codeTable);
4543     } catch (Exception ex)
4544     {
4545       Console.error("Exception during translation. Please report this !",
4546               ex);
4547       final String msg = MessageManager.getString(
4548               "label.error_when_translating_sequences_submit_bug_report");
4549       final String errorTitle = MessageManager
4550               .getString("label.implementation_error")
4551               + MessageManager.getString("label.translation_failed");
4552       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4553               JvOptionPane.ERROR_MESSAGE);
4554       return;
4555     }
4556     if (al == null || al.getHeight() == 0)
4557     {
4558       final String msg = MessageManager.getString(
4559               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4560       final String errorTitle = MessageManager
4561               .getString("label.translation_failed");
4562       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4563               JvOptionPane.WARNING_MESSAGE);
4564     }
4565     else
4566     {
4567       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4568       af.setFileFormat(this.currentFileFormat);
4569       final String newTitle = MessageManager
4570               .formatMessage("label.translation_of_params", new Object[]
4571               { this.getTitle(), codeTable.getId() });
4572       af.setTitle(newTitle);
4573       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4574       {
4575         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4576         viewport.openSplitFrame(af, new Alignment(seqs));
4577       }
4578       else
4579       {
4580         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4581                 DEFAULT_HEIGHT);
4582       }
4583     }
4584   }
4585
4586   /**
4587    * Set the file format
4588    * 
4589    * @param format
4590    */
4591   public void setFileFormat(FileFormatI format)
4592   {
4593     this.currentFileFormat = format;
4594   }
4595
4596   /**
4597    * Try to load a features file onto the alignment.
4598    * 
4599    * @param file
4600    *          contents or path to retrieve file or a File object
4601    * @param sourceType
4602    *          access mode of file (see jalview.io.AlignFile)
4603    * @return true if features file was parsed correctly.
4604    */
4605   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4606   {
4607     // BH 2018
4608     return avc.parseFeaturesFile(file, sourceType,
4609             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4610
4611   }
4612
4613   @Override
4614   public void refreshFeatureUI(boolean enableIfNecessary)
4615   {
4616     // note - currently this is only still here rather than in the controller
4617     // because of the featureSettings hard reference that is yet to be
4618     // abstracted
4619     if (enableIfNecessary)
4620     {
4621       viewport.setShowSequenceFeatures(true);
4622       showSeqFeatures.setSelected(true);
4623     }
4624
4625   }
4626
4627   @Override
4628   public void dragEnter(DropTargetDragEvent evt)
4629   {
4630   }
4631
4632   @Override
4633   public void dragExit(DropTargetEvent evt)
4634   {
4635   }
4636
4637   @Override
4638   public void dragOver(DropTargetDragEvent evt)
4639   {
4640   }
4641
4642   @Override
4643   public void dropActionChanged(DropTargetDragEvent evt)
4644   {
4645   }
4646
4647   @Override
4648   public void drop(DropTargetDropEvent evt)
4649   {
4650     // JAL-1552 - acceptDrop required before getTransferable call for
4651     // Java's Transferable for native dnd
4652     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4653     Transferable t = evt.getTransferable();
4654
4655     final AlignFrame thisaf = this;
4656     final List<Object> files = new ArrayList<>();
4657     List<DataSourceType> protocols = new ArrayList<>();
4658
4659     try
4660     {
4661       Desktop.transferFromDropTarget(files, protocols, evt, t);
4662     } catch (Exception e)
4663     {
4664       e.printStackTrace();
4665     }
4666     if (files != null)
4667     {
4668       new Thread(new Runnable()
4669       {
4670         @Override
4671         public void run()
4672         {
4673           try
4674           {
4675             // check to see if any of these files have names matching sequences
4676             // in
4677             // the alignment
4678             SequenceIdMatcher idm = new SequenceIdMatcher(
4679                     viewport.getAlignment().getSequencesArray());
4680             /**
4681              * Object[] { String,SequenceI}
4682              */
4683             ArrayList<Object[]> filesmatched = new ArrayList<>();
4684             ArrayList<Object> filesnotmatched = new ArrayList<>();
4685             for (int i = 0; i < files.size(); i++)
4686             {
4687               // BH 2018
4688               Object file = files.get(i);
4689               String fileName = file.toString();
4690               String pdbfn = "";
4691               DataSourceType protocol = (file instanceof File
4692                       ? DataSourceType.FILE
4693                       : FormatAdapter.checkProtocol(fileName));
4694               if (protocol == DataSourceType.FILE)
4695               {
4696                 File fl;
4697                 if (file instanceof File)
4698                 {
4699                   fl = (File) file;
4700                   Platform.cacheFileData(fl);
4701                 }
4702                 else
4703                 {
4704                   fl = new File(fileName);
4705                 }
4706                 pdbfn = fl.getName();
4707               }
4708               else if (protocol == DataSourceType.URL)
4709               {
4710                 URL url = new URL(fileName);
4711                 pdbfn = url.getFile();
4712               }
4713               if (pdbfn.length() > 0)
4714               {
4715                 // attempt to find a match in the alignment
4716                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4717                 int l = 0, c = pdbfn.indexOf(".");
4718                 while (mtch == null && c != -1)
4719                 {
4720                   do
4721                   {
4722                     l = c;
4723                   } while ((c = pdbfn.indexOf(".", l)) > l);
4724                   if (l > -1)
4725                   {
4726                     pdbfn = pdbfn.substring(0, l);
4727                   }
4728                   mtch = idm.findAllIdMatches(pdbfn);
4729                 }
4730                 if (mtch != null)
4731                 {
4732                   FileFormatI type;
4733                   try
4734                   {
4735                     type = new IdentifyFile().identify(file, protocol);
4736                   } catch (Exception ex)
4737                   {
4738                     type = null;
4739                   }
4740                   if (type != null && type.isStructureFile())
4741                   {
4742                     filesmatched.add(new Object[] { file, protocol, mtch });
4743                     continue;
4744                   }
4745                 }
4746                 // File wasn't named like one of the sequences or wasn't a PDB
4747                 // file.
4748                 filesnotmatched.add(file);
4749               }
4750             }
4751             int assocfiles = 0;
4752             if (filesmatched.size() > 0)
4753             {
4754               boolean autoAssociate = Cache
4755                       .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4756               if (!autoAssociate)
4757               {
4758                 String msg = MessageManager.formatMessage(
4759                         "label.automatically_associate_structure_files_with_sequences_same_name",
4760                         new Object[]
4761                         { Integer.valueOf(filesmatched.size())
4762                                 .toString() });
4763                 String ttl = MessageManager.getString(
4764                         "label.automatically_associate_structure_files_by_name");
4765                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4766                         ttl, JvOptionPane.YES_NO_OPTION);
4767                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4768               }
4769               if (autoAssociate)
4770               {
4771                 for (Object[] fm : filesmatched)
4772                 {
4773                   // try and associate
4774                   // TODO: may want to set a standard ID naming formalism for
4775                   // associating PDB files which have no IDs.
4776                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4777                   {
4778                     PDBEntry pe = new AssociatePdbFileWithSeq()
4779                             .associatePdbWithSeq(fm[0].toString(),
4780                                     (DataSourceType) fm[1], toassoc, false,
4781                                     Desktop.instance);
4782                     if (pe != null)
4783                     {
4784                       System.err.println("Associated file : "
4785                               + (fm[0].toString()) + " with "
4786                               + toassoc.getDisplayId(true));
4787                       assocfiles++;
4788                     }
4789                   }
4790                   // TODO: do we need to update overview ? only if features are
4791                   // shown I guess
4792                   alignPanel.paintAlignment(true, false);
4793                 }
4794               }
4795               else
4796               {
4797                 /*
4798                  * add declined structures as sequences
4799                  */
4800                 for (Object[] o : filesmatched)
4801                 {
4802                   filesnotmatched.add(o[0]);
4803                 }
4804               }
4805             }
4806             if (filesnotmatched.size() > 0)
4807             {
4808               if (assocfiles > 0 && (Cache.getDefault(
4809                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4810                       || JvOptionPane.showConfirmDialog(thisaf,
4811                               "<html>" + MessageManager.formatMessage(
4812                                       "label.ignore_unmatched_dropped_files_info",
4813                                       new Object[]
4814                                       { Integer.valueOf(
4815                                               filesnotmatched.size())
4816                                               .toString() })
4817                                       + "</html>",
4818                               MessageManager.getString(
4819                                       "label.ignore_unmatched_dropped_files"),
4820                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4821               {
4822                 return;
4823               }
4824               for (Object fn : filesnotmatched)
4825               {
4826                 loadJalviewDataFile(fn, null, null, null);
4827               }
4828
4829             }
4830           } catch (Exception ex)
4831           {
4832             ex.printStackTrace();
4833           }
4834         }
4835       }).start();
4836     }
4837   }
4838
4839   /**
4840    * Attempt to load a "dropped" file or URL string, by testing in turn for
4841    * <ul>
4842    * <li>an Annotation file</li>
4843    * <li>a JNet file</li>
4844    * <li>a features file</li>
4845    * <li>else try to interpret as an alignment file</li>
4846    * </ul>
4847    * 
4848    * @param file
4849    *          either a filename or a URL string.
4850    */
4851   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4852           FileFormatI format, SequenceI assocSeq)
4853   {
4854     // BH 2018 was String file
4855     try
4856     {
4857       if (sourceType == null)
4858       {
4859         sourceType = FormatAdapter.checkProtocol(file);
4860       }
4861       // if the file isn't identified, or not positively identified as some
4862       // other filetype (PFAM is default unidentified alignment file type) then
4863       // try to parse as annotation.
4864       boolean isAnnotation = (format == null
4865               || FileFormat.Pfam.equals(format))
4866                       ? new AnnotationFile().annotateAlignmentView(viewport,
4867                               file, sourceType)
4868                       : false;
4869
4870       if (!isAnnotation)
4871       {
4872         // first see if its a T-COFFEE score file
4873         TCoffeeScoreFile tcf = null;
4874         try
4875         {
4876           tcf = new TCoffeeScoreFile(file, sourceType);
4877           if (tcf.isValid())
4878           {
4879             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4880             {
4881               buildColourMenu();
4882               changeColour(
4883                       new TCoffeeColourScheme(viewport.getAlignment()));
4884               isAnnotation = true;
4885               setStatus(MessageManager.getString(
4886                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4887             }
4888             else
4889             {
4890               // some problem - if no warning its probable that the ID matching
4891               // process didn't work
4892               JvOptionPane.showMessageDialog(Desktop.desktop,
4893                       tcf.getWarningMessage() == null
4894                               ? MessageManager.getString(
4895                                       "label.check_file_matches_sequence_ids_alignment")
4896                               : tcf.getWarningMessage(),
4897                       MessageManager.getString(
4898                               "label.problem_reading_tcoffee_score_file"),
4899                       JvOptionPane.WARNING_MESSAGE);
4900             }
4901           }
4902           else
4903           {
4904             tcf = null;
4905           }
4906         } catch (Exception x)
4907         {
4908           Console.debug(
4909                   "Exception when processing data source as T-COFFEE score file",
4910                   x);
4911           tcf = null;
4912         }
4913         if (tcf == null)
4914         {
4915           // try to see if its a JNet 'concise' style annotation file *before*
4916           // we
4917           // try to parse it as a features file
4918           if (format == null)
4919           {
4920             format = new IdentifyFile().identify(file, sourceType);
4921           }
4922           if (FileFormat.ScoreMatrix == format)
4923           {
4924             ScoreMatrixFile sm = new ScoreMatrixFile(
4925                     new FileParse(file, sourceType));
4926             sm.parse();
4927             // todo: i18n this message
4928             setStatus(MessageManager.formatMessage(
4929                     "label.successfully_loaded_matrix",
4930                     sm.getMatrixName()));
4931           }
4932           else if (FileFormat.Jnet.equals(format))
4933           {
4934             JPredFile predictions = new JPredFile(file, sourceType);
4935             new JnetAnnotationMaker();
4936             JnetAnnotationMaker.add_annotation(predictions,
4937                     viewport.getAlignment(), 0, false);
4938             viewport.getAlignment().setupJPredAlignment();
4939             isAnnotation = true;
4940           }
4941           // else if (IdentifyFile.FeaturesFile.equals(format))
4942           else if (FileFormat.Features.equals(format))
4943           {
4944             if (parseFeaturesFile(file, sourceType))
4945             {
4946               SplitFrame splitFrame = (SplitFrame) getSplitViewContainer();
4947               if (splitFrame != null)
4948               {
4949                 splitFrame.repaint();
4950               }
4951               else
4952               {
4953                 alignPanel.paintAlignment(true, true);
4954               }
4955             }
4956           }
4957           else
4958           {
4959             new FileLoader().LoadFile(viewport, file, sourceType, format);
4960           }
4961         }
4962       }
4963       if (isAnnotation)
4964       {
4965
4966         alignPanel.adjustAnnotationHeight();
4967         viewport.updateSequenceIdColours();
4968         buildSortByAnnotationScoresMenu();
4969         alignPanel.paintAlignment(true, true);
4970       }
4971     } catch (Exception ex)
4972     {
4973       ex.printStackTrace();
4974     } catch (OutOfMemoryError oom)
4975     {
4976       try
4977       {
4978         System.gc();
4979       } catch (Exception x)
4980       {
4981       }
4982       new OOMWarning(
4983               "loading data "
4984                       + (sourceType != null
4985                               ? (sourceType == DataSourceType.PASTE
4986                                       ? "from clipboard."
4987                                       : "using " + sourceType + " from "
4988                                               + file)
4989                               : ".")
4990                       + (format != null
4991                               ? "(parsing as '" + format + "' file)"
4992                               : ""),
4993               oom, Desktop.desktop);
4994     }
4995   }
4996
4997   /**
4998    * Method invoked by the ChangeListener on the tabbed pane, in other words
4999    * when a different tabbed pane is selected by the user or programmatically.
5000    */
5001   @Override
5002   public void tabSelectionChanged(int index)
5003   {
5004     if (index > -1)
5005     {
5006       alignPanel = alignPanels.get(index);
5007       viewport = alignPanel.av;
5008       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5009       setMenusFromViewport(viewport);
5010       if (featureSettings != null && featureSettings.isOpen()
5011               && featureSettings.fr.getViewport() != viewport)
5012       {
5013         if (viewport.isShowSequenceFeatures())
5014         {
5015           // refresh the featureSettings to reflect UI change
5016           showFeatureSettingsUI();
5017         }
5018         else
5019         {
5020           // close feature settings for this view.
5021           featureSettings.close();
5022         }
5023       }
5024
5025     }
5026
5027     /*
5028      * 'focus' any colour slider that is open to the selected viewport
5029      */
5030     if (viewport.getConservationSelected())
5031     {
5032       SliderPanel.setConservationSlider(alignPanel,
5033               viewport.getResidueShading(), alignPanel.getViewName());
5034     }
5035     else
5036     {
5037       SliderPanel.hideConservationSlider();
5038     }
5039     if (viewport.getAbovePIDThreshold())
5040     {
5041       SliderPanel.setPIDSliderSource(alignPanel,
5042               viewport.getResidueShading(), alignPanel.getViewName());
5043     }
5044     else
5045     {
5046       SliderPanel.hidePIDSlider();
5047     }
5048
5049     /*
5050      * If there is a frame linked to this one in a SplitPane, switch it to the
5051      * same view tab index. No infinite recursion of calls should happen, since
5052      * tabSelectionChanged() should not get invoked on setting the selected
5053      * index to an unchanged value. Guard against setting an invalid index
5054      * before the new view peer tab has been created.
5055      */
5056     final AlignViewportI peer = viewport.getCodingComplement();
5057     if (peer != null)
5058     {
5059       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
5060               .getAlignPanel().alignFrame;
5061       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5062       {
5063         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5064       }
5065     }
5066   }
5067
5068   /**
5069    * On right mouse click on view tab, prompt for and set new view name.
5070    */
5071   @Override
5072   public void tabbedPane_mousePressed(MouseEvent e)
5073   {
5074     if (e.isPopupTrigger())
5075     {
5076       String msg = MessageManager.getString("label.enter_view_name");
5077       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
5078       String reply = JvOptionPane.showInputDialog(msg, ttl);
5079
5080       if (reply != null)
5081       {
5082         viewport.setViewName(reply);
5083         // TODO warn if reply is in getExistingViewNames()?
5084         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5085       }
5086     }
5087   }
5088
5089   public AlignViewport getCurrentView()
5090   {
5091     return viewport;
5092   }
5093
5094   /**
5095    * Open the dialog for regex description parsing.
5096    */
5097   @Override
5098   protected void extractScores_actionPerformed(ActionEvent e)
5099   {
5100     ParseProperties pp = new jalview.analysis.ParseProperties(
5101             viewport.getAlignment());
5102     // TODO: verify regex and introduce GUI dialog for version 2.5
5103     // if (pp.getScoresFromDescription("col", "score column ",
5104     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5105     // true)>0)
5106     if (pp.getScoresFromDescription("description column",
5107             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5108     {
5109       buildSortByAnnotationScoresMenu();
5110     }
5111   }
5112
5113   /*
5114    * (non-Javadoc)
5115    * 
5116    * @see
5117    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5118    * )
5119    */
5120   @Override
5121   protected void showDbRefs_actionPerformed(ActionEvent e)
5122   {
5123     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
5124   }
5125
5126   /*
5127    * (non-Javadoc)
5128    * 
5129    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5130    * ActionEvent)
5131    */
5132   @Override
5133   protected void showNpFeats_actionPerformed(ActionEvent e)
5134   {
5135     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
5136   }
5137
5138   /**
5139    * find the viewport amongst the tabs in this alignment frame and close that
5140    * tab
5141    * 
5142    * @param av
5143    */
5144   public boolean closeView(AlignViewportI av)
5145   {
5146     if (viewport == av)
5147     {
5148       this.closeMenuItem_actionPerformed(false);
5149       return true;
5150     }
5151     Component[] comp = tabbedPane.getComponents();
5152     for (int i = 0; comp != null && i < comp.length; i++)
5153     {
5154       if (comp[i] instanceof AlignmentPanel)
5155       {
5156         if (((AlignmentPanel) comp[i]).av == av)
5157         {
5158           // close the view.
5159           closeView((AlignmentPanel) comp[i]);
5160           return true;
5161         }
5162       }
5163     }
5164     return false;
5165   }
5166
5167   protected void build_fetchdbmenu(JMenu webService)
5168   {
5169     // Temporary hack - DBRef Fetcher always top level ws entry.
5170     // TODO We probably want to store a sequence database checklist in
5171     // preferences and have checkboxes.. rather than individual sources selected
5172     // here
5173     final JMenu rfetch = new JMenu(
5174             MessageManager.getString("action.fetch_db_references"));
5175     rfetch.setToolTipText(MessageManager.getString(
5176             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5177     webService.add(rfetch);
5178
5179     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5180             MessageManager.getString("option.trim_retrieved_seqs"));
5181     trimrs.setToolTipText(
5182             MessageManager.getString("label.trim_retrieved_sequences"));
5183     trimrs.setSelected(
5184             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5185     trimrs.addActionListener(new ActionListener()
5186     {
5187       @Override
5188       public void actionPerformed(ActionEvent e)
5189       {
5190         trimrs.setSelected(trimrs.isSelected());
5191         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5192                 Boolean.valueOf(trimrs.isSelected()).toString());
5193       }
5194     });
5195     rfetch.add(trimrs);
5196     JMenuItem fetchr = new JMenuItem(
5197             MessageManager.getString("label.standard_databases"));
5198     fetchr.setToolTipText(
5199             MessageManager.getString("label.fetch_embl_uniprot"));
5200     fetchr.addActionListener(new ActionListener()
5201     {
5202
5203       @Override
5204       public void actionPerformed(ActionEvent e)
5205       {
5206         new Thread(new Runnable()
5207         {
5208           @Override
5209           public void run()
5210           {
5211             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5212                     .getAlignment().isNucleotide();
5213             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5214                     alignPanel.av.getSequenceSelection(),
5215                     alignPanel.alignFrame, null,
5216                     alignPanel.alignFrame.featureSettings, isNucleotide);
5217             dbRefFetcher.addListener(new FetchFinishedListenerI()
5218             {
5219               @Override
5220               public void finished()
5221               {
5222
5223                 for (FeatureSettingsModelI srcSettings : dbRefFetcher
5224                         .getFeatureSettingsModels())
5225                 {
5226
5227                   alignPanel.av.mergeFeaturesStyle(srcSettings);
5228                 }
5229                 AlignFrame.this.setMenusForViewport();
5230               }
5231             });
5232             dbRefFetcher.fetchDBRefs(false);
5233           }
5234         }).start();
5235
5236       }
5237
5238     });
5239     rfetch.add(fetchr);
5240     new Thread(new Runnable()
5241     {
5242       @Override
5243       public void run()
5244       {
5245         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5246                 .getSequenceFetcherSingleton();
5247         javax.swing.SwingUtilities.invokeLater(new Runnable()
5248         {
5249           @Override
5250           public void run()
5251           {
5252             String[] dbclasses = sf.getNonAlignmentSources();
5253             List<DbSourceProxy> otherdb;
5254             JMenu dfetch = new JMenu();
5255             JMenu ifetch = new JMenu();
5256             JMenuItem fetchr = null;
5257             int comp = 0, icomp = 0, mcomp = 15;
5258             String mname = null;
5259             int dbi = 0;
5260             for (String dbclass : dbclasses)
5261             {
5262               otherdb = sf.getSourceProxy(dbclass);
5263               // add a single entry for this class, or submenu allowing 'fetch
5264               // all' or pick one
5265               if (otherdb == null || otherdb.size() < 1)
5266               {
5267                 continue;
5268               }
5269               if (mname == null)
5270               {
5271                 mname = "From " + dbclass;
5272               }
5273               if (otherdb.size() == 1)
5274               {
5275                 final DbSourceProxy[] dassource = otherdb
5276                         .toArray(new DbSourceProxy[0]);
5277                 DbSourceProxy src = otherdb.get(0);
5278                 fetchr = new JMenuItem(src.getDbSource());
5279                 fetchr.addActionListener(new ActionListener()
5280                 {
5281
5282                   @Override
5283                   public void actionPerformed(ActionEvent e)
5284                   {
5285                     new Thread(new Runnable()
5286                     {
5287
5288                       @Override
5289                       public void run()
5290                       {
5291                         boolean isNucleotide = alignPanel.alignFrame
5292                                 .getViewport().getAlignment()
5293                                 .isNucleotide();
5294                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5295                                 alignPanel.av.getSequenceSelection(),
5296                                 alignPanel.alignFrame, dassource,
5297                                 alignPanel.alignFrame.featureSettings,
5298                                 isNucleotide);
5299                         dbRefFetcher
5300                                 .addListener(new FetchFinishedListenerI()
5301                                 {
5302                                   @Override
5303                                   public void finished()
5304                                   {
5305                                     FeatureSettingsModelI srcSettings = dassource[0]
5306                                             .getFeatureColourScheme();
5307                                     alignPanel.av.mergeFeaturesStyle(
5308                                             srcSettings);
5309                                     AlignFrame.this.setMenusForViewport();
5310                                   }
5311                                 });
5312                         dbRefFetcher.fetchDBRefs(false);
5313                       }
5314                     }).start();
5315                   }
5316
5317                 });
5318                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5319                         MessageManager.formatMessage(
5320                                 "label.fetch_retrieve_from", new Object[]
5321                                 { src.getDbName() })));
5322                 dfetch.add(fetchr);
5323                 comp++;
5324               }
5325               else
5326               {
5327                 final DbSourceProxy[] dassource = otherdb
5328                         .toArray(new DbSourceProxy[0]);
5329                 // fetch all entry
5330                 DbSourceProxy src = otherdb.get(0);
5331                 fetchr = new JMenuItem(MessageManager
5332                         .formatMessage("label.fetch_all_param", new Object[]
5333                         { src.getDbSource() }));
5334                 fetchr.addActionListener(new ActionListener()
5335                 {
5336                   @Override
5337                   public void actionPerformed(ActionEvent e)
5338                   {
5339                     new Thread(new Runnable()
5340                     {
5341
5342                       @Override
5343                       public void run()
5344                       {
5345                         boolean isNucleotide = alignPanel.alignFrame
5346                                 .getViewport().getAlignment()
5347                                 .isNucleotide();
5348                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5349                                 alignPanel.av.getSequenceSelection(),
5350                                 alignPanel.alignFrame, dassource,
5351                                 alignPanel.alignFrame.featureSettings,
5352                                 isNucleotide);
5353                         dbRefFetcher
5354                                 .addListener(new FetchFinishedListenerI()
5355                                 {
5356                                   @Override
5357                                   public void finished()
5358                                   {
5359                                     AlignFrame.this.setMenusForViewport();
5360                                   }
5361                                 });
5362                         dbRefFetcher.fetchDBRefs(false);
5363                       }
5364                     }).start();
5365                   }
5366                 });
5367
5368                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5369                         MessageManager.formatMessage(
5370                                 "label.fetch_retrieve_from_all_sources",
5371                                 new Object[]
5372                                 { Integer.valueOf(otherdb.size())
5373                                         .toString(),
5374                                     src.getDbSource(), src.getDbName() })));
5375                 dfetch.add(fetchr);
5376                 comp++;
5377                 // and then build the rest of the individual menus
5378                 ifetch = new JMenu(MessageManager.formatMessage(
5379                         "label.source_from_db_source", new Object[]
5380                         { src.getDbSource() }));
5381                 icomp = 0;
5382                 String imname = null;
5383                 int i = 0;
5384                 for (DbSourceProxy sproxy : otherdb)
5385                 {
5386                   String dbname = sproxy.getDbName();
5387                   String sname = dbname.length() > 5
5388                           ? dbname.substring(0, 5) + "..."
5389                           : dbname;
5390                   String msname = dbname.length() > 10
5391                           ? dbname.substring(0, 10) + "..."
5392                           : dbname;
5393                   if (imname == null)
5394                   {
5395                     imname = MessageManager
5396                             .formatMessage("label.from_msname", new Object[]
5397                             { sname });
5398                   }
5399                   fetchr = new JMenuItem(msname);
5400                   final DbSourceProxy[] dassrc = { sproxy };
5401                   fetchr.addActionListener(new ActionListener()
5402                   {
5403
5404                     @Override
5405                     public void actionPerformed(ActionEvent e)
5406                     {
5407                       new Thread(new Runnable()
5408                       {
5409
5410                         @Override
5411                         public void run()
5412                         {
5413                           boolean isNucleotide = alignPanel.alignFrame
5414                                   .getViewport().getAlignment()
5415                                   .isNucleotide();
5416                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5417                                   alignPanel.av.getSequenceSelection(),
5418                                   alignPanel.alignFrame, dassrc,
5419                                   alignPanel.alignFrame.featureSettings,
5420                                   isNucleotide);
5421                           dbRefFetcher
5422                                   .addListener(new FetchFinishedListenerI()
5423                                   {
5424                                     @Override
5425                                     public void finished()
5426                                     {
5427                                       AlignFrame.this.setMenusForViewport();
5428                                     }
5429                                   });
5430                           dbRefFetcher.fetchDBRefs(false);
5431                         }
5432                       }).start();
5433                     }
5434
5435                   });
5436                   fetchr.setToolTipText(
5437                           "<html>" + MessageManager.formatMessage(
5438                                   "label.fetch_retrieve_from", new Object[]
5439                                   { dbname }));
5440                   ifetch.add(fetchr);
5441                   ++i;
5442                   if (++icomp >= mcomp || i == (otherdb.size()))
5443                   {
5444                     ifetch.setText(MessageManager.formatMessage(
5445                             "label.source_to_target", imname, sname));
5446                     dfetch.add(ifetch);
5447                     ifetch = new JMenu();
5448                     imname = null;
5449                     icomp = 0;
5450                     comp++;
5451                   }
5452                 }
5453               }
5454               ++dbi;
5455               if (comp >= mcomp || dbi >= (dbclasses.length))
5456               {
5457                 dfetch.setText(MessageManager.formatMessage(
5458                         "label.source_to_target", mname, dbclass));
5459                 rfetch.add(dfetch);
5460                 dfetch = new JMenu();
5461                 mname = null;
5462                 comp = 0;
5463               }
5464             }
5465           }
5466
5467         });
5468       }
5469     }).start();
5470
5471   }
5472
5473   /**
5474    * Left justify the whole alignment.
5475    */
5476   @Override
5477   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5478   {
5479     AlignmentI al = viewport.getAlignment();
5480     al.justify(false);
5481     viewport.firePropertyChange("alignment", null, al);
5482   }
5483
5484   /**
5485    * Right justify the whole alignment.
5486    */
5487   @Override
5488   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5489   {
5490     AlignmentI al = viewport.getAlignment();
5491     al.justify(true);
5492     viewport.firePropertyChange("alignment", null, al);
5493   }
5494
5495   @Override
5496   public void setShowSeqFeatures(boolean b)
5497   {
5498     showSeqFeatures.setSelected(b);
5499     viewport.setShowSequenceFeatures(b);
5500   }
5501
5502   /*
5503    * (non-Javadoc)
5504    * 
5505    * @see
5506    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5507    * awt.event.ActionEvent)
5508    */
5509   @Override
5510   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5511   {
5512     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5513     alignPanel.paintAlignment(false, false);
5514   }
5515
5516   /*
5517    * (non-Javadoc)
5518    * 
5519    * @see
5520    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5521    * .ActionEvent)
5522    */
5523   @Override
5524   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5525   {
5526     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5527     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5528
5529   }
5530
5531   /*
5532    * (non-Javadoc)
5533    * 
5534    * @see
5535    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5536    * .event.ActionEvent)
5537    */
5538   @Override
5539   protected void showGroupConservation_actionPerformed(ActionEvent e)
5540   {
5541     viewport.setShowGroupConservation(showGroupConservation.getState());
5542     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5543   }
5544
5545   /*
5546    * (non-Javadoc)
5547    * 
5548    * @see
5549    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5550    * .event.ActionEvent)
5551    */
5552   @Override
5553   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5554   {
5555     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5556     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5557   }
5558
5559   /*
5560    * (non-Javadoc)
5561    * 
5562    * @see
5563    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5564    * .event.ActionEvent)
5565    */
5566   @Override
5567   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5568   {
5569     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5570     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5571   }
5572
5573   @Override
5574   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5575   {
5576     showSequenceLogo.setState(true);
5577     viewport.setShowSequenceLogo(true);
5578     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5579     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5580   }
5581
5582   @Override
5583   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5584   {
5585     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5586   }
5587
5588   /*
5589    * (non-Javadoc)
5590    * 
5591    * @see
5592    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5593    * .event.ActionEvent)
5594    */
5595   @Override
5596   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5597   {
5598     if (avc.makeGroupsFromSelection())
5599     {
5600       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5601       alignPanel.updateAnnotation();
5602       alignPanel.paintAlignment(true,
5603               viewport.needToUpdateStructureViews());
5604     }
5605   }
5606
5607   public void clearAlignmentSeqRep()
5608   {
5609     // TODO refactor alignmentseqrep to controller
5610     if (viewport.getAlignment().hasSeqrep())
5611     {
5612       viewport.getAlignment().setSeqrep(null);
5613       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5614       alignPanel.updateAnnotation();
5615       alignPanel.paintAlignment(true, true);
5616     }
5617   }
5618
5619   @Override
5620   protected void createGroup_actionPerformed(ActionEvent e)
5621   {
5622     if (avc.createGroup())
5623     {
5624       if (applyAutoAnnotationSettings.isSelected())
5625       {
5626         alignPanel.updateAnnotation(true, false);
5627       }
5628       alignPanel.alignmentChanged();
5629     }
5630   }
5631
5632   @Override
5633   protected void unGroup_actionPerformed(ActionEvent e)
5634   {
5635     if (avc.unGroup())
5636     {
5637       alignPanel.alignmentChanged();
5638     }
5639   }
5640
5641   /**
5642    * make the given alignmentPanel the currently selected tab
5643    * 
5644    * @param alignmentPanel
5645    */
5646   public void setDisplayedView(AlignmentPanel alignmentPanel)
5647   {
5648     if (!viewport.getSequenceSetId()
5649             .equals(alignmentPanel.av.getSequenceSetId()))
5650     {
5651       throw new Error(MessageManager.getString(
5652               "error.implementation_error_cannot_show_view_alignment_frame"));
5653     }
5654     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5655             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5656     {
5657       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5658     }
5659   }
5660
5661   /**
5662    * Action on selection of menu options to Show or Hide annotations.
5663    * 
5664    * @param visible
5665    * @param forSequences
5666    *          update sequence-related annotations
5667    * @param forAlignment
5668    *          update non-sequence-related annotations
5669    */
5670   @Override
5671   protected void setAnnotationsVisibility(boolean visible,
5672           boolean forSequences, boolean forAlignment)
5673   {
5674     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5675             .getAlignmentAnnotation();
5676     if (anns == null)
5677     {
5678       return;
5679     }
5680     for (AlignmentAnnotation aa : anns)
5681     {
5682       /*
5683        * don't display non-positional annotations on an alignment
5684        */
5685       if (aa.annotations == null)
5686       {
5687         continue;
5688       }
5689       boolean apply = (aa.sequenceRef == null && forAlignment)
5690               || (aa.sequenceRef != null && forSequences);
5691       if (apply)
5692       {
5693         aa.visible = visible;
5694       }
5695     }
5696     alignPanel.validateAnnotationDimensions(true);
5697     alignPanel.alignmentChanged();
5698   }
5699
5700   /**
5701    * Store selected annotation sort order for the view and repaint.
5702    */
5703   @Override
5704   protected void sortAnnotations_actionPerformed()
5705   {
5706     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5707     this.alignPanel.av
5708             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5709     alignPanel.paintAlignment(false, false);
5710   }
5711
5712   /**
5713    * 
5714    * @return alignment panels in this alignment frame
5715    */
5716   public List<? extends AlignmentViewPanel> getAlignPanels()
5717   {
5718     // alignPanels is never null
5719     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5720     return alignPanels;
5721   }
5722
5723   /**
5724    * Open a new alignment window, with the cDNA associated with this (protein)
5725    * alignment, aligned as is the protein.
5726    */
5727   protected void viewAsCdna_actionPerformed()
5728   {
5729     // TODO no longer a menu action - refactor as required
5730     final AlignmentI alignment = getViewport().getAlignment();
5731     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5732     if (mappings == null)
5733     {
5734       return;
5735     }
5736     List<SequenceI> cdnaSeqs = new ArrayList<>();
5737     for (SequenceI aaSeq : alignment.getSequences())
5738     {
5739       for (AlignedCodonFrame acf : mappings)
5740       {
5741         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5742         if (dnaSeq != null)
5743         {
5744           /*
5745            * There is a cDNA mapping for this protein sequence - add to new
5746            * alignment. It will share the same dataset sequence as other mapped
5747            * cDNA (no new mappings need to be created).
5748            */
5749           final Sequence newSeq = new Sequence(dnaSeq);
5750           newSeq.setDatasetSequence(dnaSeq);
5751           cdnaSeqs.add(newSeq);
5752         }
5753       }
5754     }
5755     if (cdnaSeqs.size() == 0)
5756     {
5757       // show a warning dialog no mapped cDNA
5758       return;
5759     }
5760     AlignmentI cdna = new Alignment(
5761             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5762     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5763             AlignFrame.DEFAULT_HEIGHT);
5764     cdna.alignAs(alignment);
5765     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5766             + this.title;
5767     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5768             AlignFrame.DEFAULT_HEIGHT);
5769   }
5770
5771   /**
5772    * Set visibility of dna/protein complement view (available when shown in a
5773    * split frame).
5774    * 
5775    * @param show
5776    */
5777   @Override
5778   protected void showComplement_actionPerformed(boolean show)
5779   {
5780     SplitContainerI sf = getSplitViewContainer();
5781     if (sf != null)
5782     {
5783       sf.setComplementVisible(this, show);
5784     }
5785   }
5786
5787   /**
5788    * Generate the reverse (optionally complemented) of the selected sequences,
5789    * and add them to the alignment
5790    */
5791   @Override
5792   protected void showReverse_actionPerformed(boolean complement)
5793   {
5794     AlignmentI al = null;
5795     try
5796     {
5797       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5798       al = dna.reverseCdna(complement);
5799       viewport.addAlignment(al, "");
5800       addHistoryItem(new EditCommand(
5801               MessageManager.getString("label.add_sequences"), Action.PASTE,
5802               al.getSequencesArray(), 0, al.getWidth(),
5803               viewport.getAlignment()));
5804     } catch (Exception ex)
5805     {
5806       System.err.println(ex.getMessage());
5807       return;
5808     }
5809   }
5810
5811   /**
5812    * Try to run a script in the Groovy console, having first ensured that this
5813    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5814    * be targeted at this alignment.
5815    */
5816   @Override
5817   protected void runGroovy_actionPerformed()
5818   {
5819     Jalview.setCurrentAlignFrame(this);
5820     groovy.ui.Console console = Desktop.getGroovyConsole();
5821     if (console != null)
5822     {
5823       try
5824       {
5825         console.runScript();
5826       } catch (Exception ex)
5827       {
5828         System.err.println((ex.toString()));
5829         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5830                 MessageManager.getString("label.couldnt_run_groovy_script"),
5831                 MessageManager.getString("label.groovy_support_failed"),
5832                 JvOptionPane.ERROR_MESSAGE);
5833       }
5834     }
5835     else
5836     {
5837       System.err.println("Can't run Groovy script as console not found");
5838     }
5839   }
5840
5841   /**
5842    * Hides columns containing (or not containing) a specified feature, provided
5843    * that would not leave all columns hidden
5844    * 
5845    * @param featureType
5846    * @param columnsContaining
5847    * @return
5848    */
5849   public boolean hideFeatureColumns(String featureType,
5850           boolean columnsContaining)
5851   {
5852     boolean notForHiding = avc.markColumnsContainingFeatures(
5853             columnsContaining, false, false, featureType);
5854     if (notForHiding)
5855     {
5856       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5857               false, featureType))
5858       {
5859         getViewport().hideSelectedColumns();
5860         return true;
5861       }
5862     }
5863     return false;
5864   }
5865
5866   @Override
5867   protected void selectHighlightedColumns_actionPerformed(
5868           ActionEvent actionEvent)
5869   {
5870     // include key modifier check in case user selects from menu
5871     avc.markHighlightedColumns(
5872             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5873             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5874                     | ActionEvent.CTRL_MASK)) != 0);
5875   }
5876
5877   /**
5878    * Rebuilds the Colour menu, including any user-defined colours which have
5879    * been loaded either on startup or during the session
5880    */
5881   public void buildColourMenu()
5882   {
5883     colourMenu.removeAll();
5884
5885     colourMenu.add(applyToAllGroups);
5886     colourMenu.add(textColour);
5887     colourMenu.addSeparator();
5888
5889     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5890             viewport.getAlignment(), false);
5891
5892     colourMenu.add(annotationColour);
5893     bg.add(annotationColour);
5894     colourMenu.addSeparator();
5895     colourMenu.add(conservationMenuItem);
5896     colourMenu.add(modifyConservation);
5897     colourMenu.add(abovePIDThreshold);
5898     colourMenu.add(modifyPID);
5899
5900     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5901     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5902   }
5903
5904   /**
5905    * Open a dialog (if not already open) that allows the user to select and
5906    * calculate PCA or Tree analysis
5907    */
5908   protected void openTreePcaDialog()
5909   {
5910     if (alignPanel.getCalculationDialog() == null)
5911     {
5912       new CalculationChooser(AlignFrame.this);
5913     }
5914   }
5915
5916   @Override
5917   protected void loadVcf_actionPerformed()
5918   {
5919     JalviewFileChooser chooser = new JalviewFileChooser(
5920             Cache.getProperty("LAST_DIRECTORY"));
5921     chooser.setFileView(new JalviewFileView());
5922     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5923     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5924     final AlignFrame us = this;
5925     chooser.setResponseHandler(0, new Runnable()
5926     {
5927       @Override
5928       public void run()
5929       {
5930         String choice = chooser.getSelectedFile().getPath();
5931         Cache.setProperty("LAST_DIRECTORY", choice);
5932         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5933         new VCFLoader(choice).loadVCF(seqs, us);
5934       }
5935     });
5936     chooser.showOpenDialog(null);
5937
5938   }
5939
5940   private Rectangle lastFeatureSettingsBounds = null;
5941
5942   @Override
5943   public void setFeatureSettingsGeometry(Rectangle bounds)
5944   {
5945     lastFeatureSettingsBounds = bounds;
5946   }
5947
5948   @Override
5949   public Rectangle getFeatureSettingsGeometry()
5950   {
5951     return lastFeatureSettingsBounds;
5952   }
5953
5954   /*
5955    * Caching hashmaps for jalview.rest.API
5956    */
5957   private static Map<String, AlignFrame> alignFrameMap = null;
5958
5959   public static AlignFrame getAlignFrameFromRestId(String id)
5960   {
5961     if (id == null || alignFrameMap == null)
5962       return null;
5963     return alignFrameMap.get(id);
5964   }
5965
5966   public void cacheAlignFrameFromRestId(String id)
5967   {
5968     if (id == null)
5969       return;
5970     if (alignFrameMap == null)
5971       alignFrameMap = new HashMap<>();
5972     alignFrameMap.put(id, this);
5973   }
5974 }
5975
5976 class PrintThread extends Thread
5977 {
5978   AlignmentPanel ap;
5979
5980   public PrintThread(AlignmentPanel ap)
5981   {
5982     this.ap = ap;
5983   }
5984
5985   static PageFormat pf;
5986
5987   @Override
5988   public void run()
5989   {
5990     PrinterJob printJob = PrinterJob.getPrinterJob();
5991
5992     if (pf != null)
5993     {
5994       printJob.setPrintable(ap, pf);
5995     }
5996     else
5997     {
5998       printJob.setPrintable(ap);
5999     }
6000
6001     if (printJob.printDialog())
6002     {
6003       try
6004       {
6005         printJob.print();
6006       } catch (Exception PrintException)
6007       {
6008         PrintException.printStackTrace();
6009       }
6010     }
6011   }
6012 }