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