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