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