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