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