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