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