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