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