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