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