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