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