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