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