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