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