JAL-3210 JAL-3141 JAL-3056 disable backups in JalviewJS
[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 = true;
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           boolean doBackup = BackupFiles.getEnabled();
1293           BackupFiles backupfiles = doBackup ? new BackupFiles(file) : null;
1294           try
1295           {
1296             String tempFilePath = doBackup ? backupfiles.getTempFilePath() : file;
1297                         PrintWriter out = new PrintWriter(
1298                     new FileWriter(tempFilePath));
1299
1300             out.print(output);
1301             out.close();
1302             AlignFrame.this.setTitle(file);
1303             statusBar.setText(MessageManager.formatMessage(
1304                   "label.successfully_saved_to_file_in_format", new Object[]
1305                   { fileName, format.getName() }));
1306             lastSaveSuccessful = true;
1307           } catch (Exception ex)
1308           {
1309             lastSaveSuccessful = false;
1310             ex.printStackTrace();
1311           }
1312
1313           if (doBackup)
1314           {
1315             backupfiles.setWriteSuccess(lastSaveSuccessful);
1316             // do the backup file roll and rename the temp file to actual file
1317             lastSaveSuccessful = backupfiles.rollBackupsAndRenameTempFile();
1318           }
1319         }
1320       }
1321     };
1322
1323     /*
1324      * show dialog with export options if applicable; else just do it
1325      */
1326     if (AlignExportOptions.isNeeded(viewport, format))
1327     {
1328       AlignExportOptions choices = new AlignExportOptions(
1329               alignPanel.getAlignViewport(), format, options);
1330       choices.setResponseAction(0, outputAction);
1331       choices.setResponseAction(1, cancelAction);
1332       choices.showDialog();
1333     }
1334     else
1335     {
1336       outputAction.run();
1337     }
1338   }
1339
1340   /**
1341    * Outputs the alignment to textbox in the requested format, if necessary
1342    * first prompting the user for whether to include hidden regions or
1343    * non-sequence data
1344    * 
1345    * @param fileFormatName
1346    */
1347   @Override
1348   protected void outputText_actionPerformed(String fileFormatName)
1349   {
1350     FileFormatI fileFormat = FileFormats.getInstance()
1351             .forName(fileFormatName);
1352     AlignExportSettingsI options = new AlignExportSettingsAdapter(false);
1353     Runnable outputAction = new Runnable()
1354     {
1355       @Override
1356       public void run()
1357       {
1358         // todo defer this to inside formatSequences (or later)
1359         AlignmentExportData exportData = viewport
1360                 .getAlignExportData(options);
1361         CutAndPasteTransfer cap = new CutAndPasteTransfer();
1362         cap.setForInput(null);
1363         try
1364         {
1365           FileFormatI format = fileFormat;
1366           cap.setText(new FormatAdapter(alignPanel, options)
1367                   .formatSequences(format, exportData.getAlignment(),
1368                           exportData.getOmitHidden(),
1369                           exportData.getStartEndPostions(),
1370                           viewport.getAlignment().getHiddenColumns()));
1371           Desktop.addInternalFrame(cap, MessageManager.formatMessage(
1372                   "label.alignment_output_command", new Object[]
1373                   { fileFormat.getName() }), 600, 500);
1374         } catch (OutOfMemoryError oom)
1375         {
1376           new OOMWarning("Outputting alignment as " + fileFormat.getName(),
1377                   oom);
1378           cap.dispose();
1379         }
1380       }
1381     };
1382
1383     /*
1384      * show dialog with export options if applicable; else just do it
1385      */
1386     if (AlignExportOptions.isNeeded(viewport, fileFormat))
1387     {
1388       AlignExportOptions choices = new AlignExportOptions(
1389               alignPanel.getAlignViewport(), fileFormat, options);
1390       choices.setResponseAction(0, outputAction);
1391       choices.showDialog();
1392     }
1393     else
1394     {
1395       outputAction.run();
1396     }
1397   }
1398
1399   /**
1400    * DOCUMENT ME!
1401    * 
1402    * @param e
1403    *          DOCUMENT ME!
1404    */
1405   @Override
1406   protected void htmlMenuItem_actionPerformed(ActionEvent e)
1407   {
1408     HtmlSvgOutput htmlSVG = new HtmlSvgOutput(alignPanel);
1409     htmlSVG.exportHTML(null);
1410   }
1411
1412   @Override
1413   public void bioJSMenuItem_actionPerformed(ActionEvent e)
1414   {
1415     BioJsHTMLOutput bjs = new BioJsHTMLOutput(alignPanel);
1416     bjs.exportHTML(null);
1417   }
1418
1419   public void createImageMap(File file, String image)
1420   {
1421     alignPanel.makePNGImageMap(file, image);
1422   }
1423
1424   /**
1425    * Creates a PNG image of the alignment and writes it to the given file. If
1426    * the file is null, the user is prompted to choose a file.
1427    * 
1428    * @param f
1429    */
1430   @Override
1431   public void createPNG(File f)
1432   {
1433     alignPanel.makeAlignmentImage(TYPE.PNG, f);
1434   }
1435
1436   /**
1437    * Creates an EPS image of the alignment and writes it to the given file. If
1438    * the file is null, the user is prompted to choose a file.
1439    * 
1440    * @param f
1441    */
1442   @Override
1443   public void createEPS(File f)
1444   {
1445     alignPanel.makeAlignmentImage(TYPE.EPS, f);
1446   }
1447
1448   /**
1449    * Creates an SVG image of the alignment and writes it to the given file. If
1450    * the file is null, the user is prompted to choose a file.
1451    * 
1452    * @param f
1453    */
1454   @Override
1455   public void createSVG(File f)
1456   {
1457     alignPanel.makeAlignmentImage(TYPE.SVG, f);
1458   }
1459
1460   @Override
1461   public void pageSetup_actionPerformed(ActionEvent e)
1462   {
1463     PrinterJob printJob = PrinterJob.getPrinterJob();
1464     PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
1465   }
1466
1467   /**
1468    * DOCUMENT ME!
1469    * 
1470    * @param e
1471    *          DOCUMENT ME!
1472    */
1473   @Override
1474   public void printMenuItem_actionPerformed(ActionEvent e)
1475   {
1476     // Putting in a thread avoids Swing painting problems
1477     PrintThread thread = new PrintThread(alignPanel);
1478     thread.start();
1479   }
1480
1481   @Override
1482   public void exportFeatures_actionPerformed(ActionEvent e)
1483   {
1484     new AnnotationExporter(alignPanel).exportFeatures();
1485   }
1486
1487   @Override
1488   public void exportAnnotations_actionPerformed(ActionEvent e)
1489   {
1490     new AnnotationExporter(alignPanel).exportAnnotations();
1491   }
1492
1493   @Override
1494   public void associatedData_actionPerformed(ActionEvent e)
1495   {
1496     final JalviewFileChooser chooser = new JalviewFileChooser(
1497             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1498     chooser.setFileView(new JalviewFileView());
1499     chooser.setDialogTitle(
1500             MessageManager.getString("label.load_jalview_annotations"));
1501     chooser.setToolTipText(
1502             MessageManager.getString("label.load_jalview_annotations"));
1503     chooser.setResponseHandler(0, new Runnable()
1504     {
1505       @Override
1506       public void run()
1507       {
1508         String choice = chooser.getSelectedFile().getPath();
1509         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
1510         loadJalviewDataFile(chooser.getSelectedFile(), null, null, null);
1511       }
1512     });
1513
1514     chooser.showOpenDialog(this);
1515   }
1516
1517   /**
1518    * Close the current view or all views in the alignment frame. If the frame
1519    * only contains one view then the alignment will be removed from memory.
1520    * 
1521    * @param closeAllTabs
1522    */
1523   @Override
1524   public void closeMenuItem_actionPerformed(boolean closeAllTabs)
1525   {
1526     if (alignPanels != null && alignPanels.size() < 2)
1527     {
1528       closeAllTabs = true;
1529     }
1530
1531     try
1532     {
1533       if (alignPanels != null)
1534       {
1535         if (closeAllTabs)
1536         {
1537           if (this.isClosed())
1538           {
1539             // really close all the windows - otherwise wait till
1540             // setClosed(true) is called
1541             for (int i = 0; i < alignPanels.size(); i++)
1542             {
1543               AlignmentPanel ap = alignPanels.get(i);
1544               ap.closePanel();
1545             }
1546           }
1547         }
1548         else
1549         {
1550           closeView(alignPanel);
1551         }
1552       }
1553
1554       if (closeAllTabs)
1555       {
1556         /*
1557          * this will raise an INTERNAL_FRAME_CLOSED event and this method will
1558          * be called recursively, with the frame now in 'closed' state
1559          */
1560         this.setClosed(true);
1561       }
1562     } catch (Exception ex)
1563     {
1564       ex.printStackTrace();
1565     }
1566   }
1567
1568   /**
1569    * Close the specified panel and close up tabs appropriately.
1570    * 
1571    * @param panelToClose
1572    */
1573   public void closeView(AlignmentPanel panelToClose)
1574   {
1575     int index = tabbedPane.getSelectedIndex();
1576     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1577     alignPanels.remove(panelToClose);
1578     panelToClose.closePanel();
1579     panelToClose = null;
1580
1581     tabbedPane.removeTabAt(closedindex);
1582     tabbedPane.validate();
1583
1584     if (index > closedindex || index == tabbedPane.getTabCount())
1585     {
1586       // modify currently selected tab index if necessary.
1587       index--;
1588     }
1589
1590     this.tabSelectionChanged(index);
1591   }
1592
1593   /**
1594    * DOCUMENT ME!
1595    */
1596   void updateEditMenuBar()
1597   {
1598
1599     if (viewport.getHistoryList().size() > 0)
1600     {
1601       undoMenuItem.setEnabled(true);
1602       CommandI command = viewport.getHistoryList().peek();
1603       undoMenuItem.setText(MessageManager
1604               .formatMessage("label.undo_command", new Object[]
1605               { command.getDescription() }));
1606     }
1607     else
1608     {
1609       undoMenuItem.setEnabled(false);
1610       undoMenuItem.setText(MessageManager.getString("action.undo"));
1611     }
1612
1613     if (viewport.getRedoList().size() > 0)
1614     {
1615       redoMenuItem.setEnabled(true);
1616
1617       CommandI command = viewport.getRedoList().peek();
1618       redoMenuItem.setText(MessageManager
1619               .formatMessage("label.redo_command", new Object[]
1620               { command.getDescription() }));
1621     }
1622     else
1623     {
1624       redoMenuItem.setEnabled(false);
1625       redoMenuItem.setText(MessageManager.getString("action.redo"));
1626     }
1627   }
1628
1629   @Override
1630   public void addHistoryItem(CommandI command)
1631   {
1632     if (command.getSize() > 0)
1633     {
1634       viewport.addToHistoryList(command);
1635       viewport.clearRedoList();
1636       updateEditMenuBar();
1637       viewport.updateHiddenColumns();
1638       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1639       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1640       // viewport.getColumnSelection()
1641       // .getHiddenColumns().size() > 0);
1642     }
1643   }
1644
1645   /**
1646    * 
1647    * @return alignment objects for all views
1648    */
1649   AlignmentI[] getViewAlignments()
1650   {
1651     if (alignPanels != null)
1652     {
1653       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1654       int i = 0;
1655       for (AlignmentPanel ap : alignPanels)
1656       {
1657         als[i++] = ap.av.getAlignment();
1658       }
1659       return als;
1660     }
1661     if (viewport != null)
1662     {
1663       return new AlignmentI[] { viewport.getAlignment() };
1664     }
1665     return null;
1666   }
1667
1668   /**
1669    * DOCUMENT ME!
1670    * 
1671    * @param e
1672    *          DOCUMENT ME!
1673    */
1674   @Override
1675   protected void undoMenuItem_actionPerformed(ActionEvent e)
1676   {
1677     if (viewport.getHistoryList().isEmpty())
1678     {
1679       return;
1680     }
1681     CommandI command = viewport.getHistoryList().pop();
1682     viewport.addToRedoList(command);
1683     command.undoCommand(getViewAlignments());
1684
1685     AlignmentViewport originalSource = getOriginatingSource(command);
1686     updateEditMenuBar();
1687
1688     if (originalSource != null)
1689     {
1690       if (originalSource != viewport)
1691       {
1692         Cache.log.warn(
1693                 "Implementation worry: mismatch of viewport origin for undo");
1694       }
1695       originalSource.updateHiddenColumns();
1696       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1697       // null
1698       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1699       // viewport.getColumnSelection()
1700       // .getHiddenColumns().size() > 0);
1701       originalSource.firePropertyChange("alignment", null,
1702               originalSource.getAlignment().getSequences());
1703     }
1704   }
1705
1706   /**
1707    * DOCUMENT ME!
1708    * 
1709    * @param e
1710    *          DOCUMENT ME!
1711    */
1712   @Override
1713   protected void redoMenuItem_actionPerformed(ActionEvent e)
1714   {
1715     if (viewport.getRedoList().size() < 1)
1716     {
1717       return;
1718     }
1719
1720     CommandI command = viewport.getRedoList().pop();
1721     viewport.addToHistoryList(command);
1722     command.doCommand(getViewAlignments());
1723
1724     AlignmentViewport originalSource = getOriginatingSource(command);
1725     updateEditMenuBar();
1726
1727     if (originalSource != null)
1728     {
1729
1730       if (originalSource != viewport)
1731       {
1732         Cache.log.warn(
1733                 "Implementation worry: mismatch of viewport origin for redo");
1734       }
1735       originalSource.updateHiddenColumns();
1736       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1737       // null
1738       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1739       // viewport.getColumnSelection()
1740       // .getHiddenColumns().size() > 0);
1741       originalSource.firePropertyChange("alignment", null,
1742               originalSource.getAlignment().getSequences());
1743     }
1744   }
1745
1746   AlignmentViewport getOriginatingSource(CommandI command)
1747   {
1748     AlignmentViewport originalSource = null;
1749     // For sequence removal and addition, we need to fire
1750     // the property change event FROM the viewport where the
1751     // original alignment was altered
1752     AlignmentI al = null;
1753     if (command instanceof EditCommand)
1754     {
1755       EditCommand editCommand = (EditCommand) command;
1756       al = editCommand.getAlignment();
1757       List<Component> comps = PaintRefresher.components
1758               .get(viewport.getSequenceSetId());
1759
1760       for (Component comp : comps)
1761       {
1762         if (comp instanceof AlignmentPanel)
1763         {
1764           if (al == ((AlignmentPanel) comp).av.getAlignment())
1765           {
1766             originalSource = ((AlignmentPanel) comp).av;
1767             break;
1768           }
1769         }
1770       }
1771     }
1772
1773     if (originalSource == null)
1774     {
1775       // The original view is closed, we must validate
1776       // the current view against the closed view first
1777       if (al != null)
1778       {
1779         PaintRefresher.validateSequences(al, viewport.getAlignment());
1780       }
1781
1782       originalSource = viewport;
1783     }
1784
1785     return originalSource;
1786   }
1787
1788   /**
1789    * DOCUMENT ME!
1790    * 
1791    * @param up
1792    *          DOCUMENT ME!
1793    */
1794   public void moveSelectedSequences(boolean up)
1795   {
1796     SequenceGroup sg = viewport.getSelectionGroup();
1797
1798     if (sg == null)
1799     {
1800       return;
1801     }
1802     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1803             viewport.getHiddenRepSequences(), up);
1804     alignPanel.paintAlignment(true, false);
1805   }
1806
1807   synchronized void slideSequences(boolean right, int size)
1808   {
1809     List<SequenceI> sg = new ArrayList<>();
1810     if (viewport.cursorMode)
1811     {
1812       sg.add(viewport.getAlignment()
1813               .getSequenceAt(alignPanel.getSeqPanel().seqCanvas.cursorY));
1814     }
1815     else if (viewport.getSelectionGroup() != null
1816             && viewport.getSelectionGroup().getSize() != viewport
1817                     .getAlignment().getHeight())
1818     {
1819       sg = viewport.getSelectionGroup()
1820               .getSequences(viewport.getHiddenRepSequences());
1821     }
1822
1823     if (sg.size() < 1)
1824     {
1825       return;
1826     }
1827
1828     List<SequenceI> invertGroup = new ArrayList<>();
1829
1830     for (SequenceI seq : viewport.getAlignment().getSequences())
1831     {
1832       if (!sg.contains(seq))
1833       {
1834         invertGroup.add(seq);
1835       }
1836     }
1837
1838     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1839
1840     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1841     for (int i = 0; i < invertGroup.size(); i++)
1842     {
1843       seqs2[i] = invertGroup.get(i);
1844     }
1845
1846     SlideSequencesCommand ssc;
1847     if (right)
1848     {
1849       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1, size,
1850               viewport.getGapCharacter());
1851     }
1852     else
1853     {
1854       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2, size,
1855               viewport.getGapCharacter());
1856     }
1857
1858     int groupAdjustment = 0;
1859     if (ssc.getGapsInsertedBegin() && right)
1860     {
1861       if (viewport.cursorMode)
1862       {
1863         alignPanel.getSeqPanel().moveCursor(size, 0);
1864       }
1865       else
1866       {
1867         groupAdjustment = size;
1868       }
1869     }
1870     else if (!ssc.getGapsInsertedBegin() && !right)
1871     {
1872       if (viewport.cursorMode)
1873       {
1874         alignPanel.getSeqPanel().moveCursor(-size, 0);
1875       }
1876       else
1877       {
1878         groupAdjustment = -size;
1879       }
1880     }
1881
1882     if (groupAdjustment != 0)
1883     {
1884       viewport.getSelectionGroup().setStartRes(
1885               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1886       viewport.getSelectionGroup().setEndRes(
1887               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1888     }
1889
1890     /*
1891      * just extend the last slide command if compatible; but not if in
1892      * SplitFrame mode (to ensure all edits are broadcast - JAL-1802)
1893      */
1894     boolean appendHistoryItem = false;
1895     Deque<CommandI> historyList = viewport.getHistoryList();
1896     boolean inSplitFrame = getSplitViewContainer() != null;
1897     if (!inSplitFrame && historyList != null && historyList.size() > 0
1898             && historyList.peek() instanceof SlideSequencesCommand)
1899     {
1900       appendHistoryItem = ssc.appendSlideCommand(
1901               (SlideSequencesCommand) historyList.peek());
1902     }
1903
1904     if (!appendHistoryItem)
1905     {
1906       addHistoryItem(ssc);
1907     }
1908
1909     repaint();
1910   }
1911
1912   /**
1913    * DOCUMENT ME!
1914    * 
1915    * @param e
1916    *          DOCUMENT ME!
1917    */
1918   @Override
1919   protected void copy_actionPerformed()
1920   {
1921     if (viewport.getSelectionGroup() == null)
1922     {
1923       return;
1924     }
1925     // TODO: preserve the ordering of displayed alignment annotation in any
1926     // internal paste (particularly sequence associated annotation)
1927     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1928     String[] omitHidden = null;
1929
1930     if (viewport.hasHiddenColumns())
1931     {
1932       omitHidden = viewport.getViewAsString(true);
1933     }
1934
1935     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1936             seqs, omitHidden, null);
1937
1938     StringSelection ss = new StringSelection(output);
1939
1940     try
1941     {
1942       jalview.gui.Desktop.internalCopy = true;
1943       // Its really worth setting the clipboard contents
1944       // to empty before setting the large StringSelection!!
1945       Toolkit.getDefaultToolkit().getSystemClipboard()
1946               .setContents(new StringSelection(""), null);
1947
1948       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,
1949               Desktop.instance);
1950     } catch (OutOfMemoryError er)
1951     {
1952       new OOMWarning("copying region", er);
1953       return;
1954     }
1955
1956     HiddenColumns hiddenColumns = null;
1957     if (viewport.hasHiddenColumns())
1958     {
1959       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
1960       int hiddenCutoff = viewport.getSelectionGroup().getEndRes();
1961
1962       // create new HiddenColumns object with copy of hidden regions
1963       // between startRes and endRes, offset by startRes
1964       hiddenColumns = new HiddenColumns(
1965               viewport.getAlignment().getHiddenColumns(), hiddenOffset,
1966               hiddenCutoff, hiddenOffset);
1967     }
1968
1969     Desktop.jalviewClipboard = new Object[] { seqs,
1970         viewport.getAlignment().getDataset(), hiddenColumns };
1971     setStatus(MessageManager.formatMessage(
1972             "label.copied_sequences_to_clipboard", new Object[]
1973             { Integer.valueOf(seqs.length).toString() }));
1974   }
1975
1976   /**
1977    * DOCUMENT ME!
1978    * 
1979    * @param e
1980    *          DOCUMENT ME!
1981    */
1982   @Override
1983   protected void pasteNew_actionPerformed(ActionEvent e)
1984   {
1985     paste(true);
1986   }
1987
1988   /**
1989    * DOCUMENT ME!
1990    * 
1991    * @param e
1992    *          DOCUMENT ME!
1993    */
1994   @Override
1995   protected void pasteThis_actionPerformed(ActionEvent e)
1996   {
1997     paste(false);
1998   }
1999
2000   /**
2001    * Paste contents of Jalview clipboard
2002    * 
2003    * @param newAlignment
2004    *          true to paste to a new alignment, otherwise add to this.
2005    */
2006   void paste(boolean newAlignment)
2007   {
2008     boolean externalPaste = true;
2009     try
2010     {
2011       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
2012       Transferable contents = c.getContents(this);
2013
2014       if (contents == null)
2015       {
2016         return;
2017       }
2018
2019       String str;
2020       FileFormatI format;
2021       try
2022       {
2023         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
2024         if (str.length() < 1)
2025         {
2026           return;
2027         }
2028
2029         format = new IdentifyFile().identify(str, DataSourceType.PASTE);
2030
2031       } catch (OutOfMemoryError er)
2032       {
2033         new OOMWarning("Out of memory pasting sequences!!", er);
2034         return;
2035       }
2036
2037       SequenceI[] sequences;
2038       boolean annotationAdded = false;
2039       AlignmentI alignment = null;
2040
2041       if (Desktop.jalviewClipboard != null)
2042       {
2043         // The clipboard was filled from within Jalview, we must use the
2044         // sequences
2045         // And dataset from the copied alignment
2046         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
2047         // be doubly sure that we create *new* sequence objects.
2048         sequences = new SequenceI[newseq.length];
2049         for (int i = 0; i < newseq.length; i++)
2050         {
2051           sequences[i] = new Sequence(newseq[i]);
2052         }
2053         alignment = new Alignment(sequences);
2054         externalPaste = false;
2055       }
2056       else
2057       {
2058         // parse the clipboard as an alignment.
2059         alignment = new FormatAdapter().readFile(str, DataSourceType.PASTE,
2060                 format);
2061         sequences = alignment.getSequencesArray();
2062       }
2063
2064       int alwidth = 0;
2065       ArrayList<Integer> newGraphGroups = new ArrayList<>();
2066       int fgroup = -1;
2067
2068       if (newAlignment)
2069       {
2070
2071         if (Desktop.jalviewClipboard != null)
2072         {
2073           // dataset is inherited
2074           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
2075         }
2076         else
2077         {
2078           // new dataset is constructed
2079           alignment.setDataset(null);
2080         }
2081         alwidth = alignment.getWidth() + 1;
2082       }
2083       else
2084       {
2085         AlignmentI pastedal = alignment; // preserve pasted alignment object
2086         // Add pasted sequences and dataset into existing alignment.
2087         alignment = viewport.getAlignment();
2088         alwidth = alignment.getWidth() + 1;
2089         // decide if we need to import sequences from an existing dataset
2090         boolean importDs = Desktop.jalviewClipboard != null
2091                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2092         // importDs==true instructs us to copy over new dataset sequences from
2093         // an existing alignment
2094         Vector newDs = (importDs) ? new Vector() : null; // used to create
2095         // minimum dataset set
2096
2097         for (int i = 0; i < sequences.length; i++)
2098         {
2099           if (importDs)
2100           {
2101             newDs.addElement(null);
2102           }
2103           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2104           // paste
2105           if (importDs && ds != null)
2106           {
2107             if (!newDs.contains(ds))
2108             {
2109               newDs.setElementAt(ds, i);
2110               ds = new Sequence(ds);
2111               // update with new dataset sequence
2112               sequences[i].setDatasetSequence(ds);
2113             }
2114             else
2115             {
2116               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2117             }
2118           }
2119           else
2120           {
2121             // copy and derive new dataset sequence
2122             sequences[i] = sequences[i].deriveSequence();
2123             alignment.getDataset()
2124                     .addSequence(sequences[i].getDatasetSequence());
2125             // TODO: avoid creation of duplicate dataset sequences with a
2126             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2127           }
2128           alignment.addSequence(sequences[i]); // merges dataset
2129         }
2130         if (newDs != null)
2131         {
2132           newDs.clear(); // tidy up
2133         }
2134         if (alignment.getAlignmentAnnotation() != null)
2135         {
2136           for (AlignmentAnnotation alan : alignment
2137                   .getAlignmentAnnotation())
2138           {
2139             if (alan.graphGroup > fgroup)
2140             {
2141               fgroup = alan.graphGroup;
2142             }
2143           }
2144         }
2145         if (pastedal.getAlignmentAnnotation() != null)
2146         {
2147           // Add any annotation attached to alignment.
2148           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2149           for (int i = 0; i < alann.length; i++)
2150           {
2151             annotationAdded = true;
2152             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2153             {
2154               AlignmentAnnotation newann = new AlignmentAnnotation(
2155                       alann[i]);
2156               if (newann.graphGroup > -1)
2157               {
2158                 if (newGraphGroups.size() <= newann.graphGroup
2159                         || newGraphGroups.get(newann.graphGroup) == null)
2160                 {
2161                   for (int q = newGraphGroups
2162                           .size(); q <= newann.graphGroup; q++)
2163                   {
2164                     newGraphGroups.add(q, null);
2165                   }
2166                   newGraphGroups.set(newann.graphGroup,
2167                           new Integer(++fgroup));
2168                 }
2169                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2170                         .intValue();
2171               }
2172
2173               newann.padAnnotation(alwidth);
2174               alignment.addAnnotation(newann);
2175             }
2176           }
2177         }
2178       }
2179       if (!newAlignment)
2180       {
2181         // /////
2182         // ADD HISTORY ITEM
2183         //
2184         addHistoryItem(new EditCommand(
2185                 MessageManager.getString("label.add_sequences"),
2186                 Action.PASTE, sequences, 0, alignment.getWidth(),
2187                 alignment));
2188       }
2189       // Add any annotations attached to sequences
2190       for (int i = 0; i < sequences.length; i++)
2191       {
2192         if (sequences[i].getAnnotation() != null)
2193         {
2194           AlignmentAnnotation newann;
2195           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2196           {
2197             annotationAdded = true;
2198             newann = sequences[i].getAnnotation()[a];
2199             newann.adjustForAlignment();
2200             newann.padAnnotation(alwidth);
2201             if (newann.graphGroup > -1)
2202             {
2203               if (newann.graphGroup > -1)
2204               {
2205                 if (newGraphGroups.size() <= newann.graphGroup
2206                         || newGraphGroups.get(newann.graphGroup) == null)
2207                 {
2208                   for (int q = newGraphGroups
2209                           .size(); q <= newann.graphGroup; q++)
2210                   {
2211                     newGraphGroups.add(q, null);
2212                   }
2213                   newGraphGroups.set(newann.graphGroup,
2214                           new Integer(++fgroup));
2215                 }
2216                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2217                         .intValue();
2218               }
2219             }
2220             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2221             // was
2222             // duplicated
2223             // earlier
2224             alignment.setAnnotationIndex(sequences[i].getAnnotation()[a],
2225                     a);
2226           }
2227         }
2228       }
2229       if (!newAlignment)
2230       {
2231
2232         // propagate alignment changed.
2233         viewport.getRanges().setEndSeq(alignment.getHeight());
2234         if (annotationAdded)
2235         {
2236           // Duplicate sequence annotation in all views.
2237           AlignmentI[] alview = this.getViewAlignments();
2238           for (int i = 0; i < sequences.length; i++)
2239           {
2240             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2241             if (sann == null)
2242             {
2243               continue;
2244             }
2245             for (int avnum = 0; avnum < alview.length; avnum++)
2246             {
2247               if (alview[avnum] != alignment)
2248               {
2249                 // duplicate in a view other than the one with input focus
2250                 int avwidth = alview[avnum].getWidth() + 1;
2251                 // this relies on sann being preserved after we
2252                 // modify the sequence's annotation array for each duplication
2253                 for (int a = 0; a < sann.length; a++)
2254                 {
2255                   AlignmentAnnotation newann = new AlignmentAnnotation(
2256                           sann[a]);
2257                   sequences[i].addAlignmentAnnotation(newann);
2258                   newann.padAnnotation(avwidth);
2259                   alview[avnum].addAnnotation(newann); // annotation was
2260                   // duplicated earlier
2261                   // TODO JAL-1145 graphGroups are not updated for sequence
2262                   // annotation added to several views. This may cause
2263                   // strangeness
2264                   alview[avnum].setAnnotationIndex(newann, a);
2265                 }
2266               }
2267             }
2268           }
2269           buildSortByAnnotationScoresMenu();
2270         }
2271         viewport.firePropertyChange("alignment", null,
2272                 alignment.getSequences());
2273         if (alignPanels != null)
2274         {
2275           for (AlignmentPanel ap : alignPanels)
2276           {
2277             ap.validateAnnotationDimensions(false);
2278           }
2279         }
2280         else
2281         {
2282           alignPanel.validateAnnotationDimensions(false);
2283         }
2284
2285       }
2286       else
2287       {
2288         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2289                 DEFAULT_HEIGHT);
2290         String newtitle = new String("Copied sequences");
2291
2292         if (Desktop.jalviewClipboard != null
2293                 && Desktop.jalviewClipboard[2] != null)
2294         {
2295           HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2296           af.viewport.setHiddenColumns(hc);
2297         }
2298
2299         // >>>This is a fix for the moment, until a better solution is
2300         // found!!<<<
2301         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2302                 .transferSettings(alignPanel.getSeqPanel().seqCanvas
2303                         .getFeatureRenderer());
2304
2305         // TODO: maintain provenance of an alignment, rather than just make the
2306         // title a concatenation of operations.
2307         if (!externalPaste)
2308         {
2309           if (title.startsWith("Copied sequences"))
2310           {
2311             newtitle = title;
2312           }
2313           else
2314           {
2315             newtitle = newtitle.concat("- from " + title);
2316           }
2317         }
2318         else
2319         {
2320           newtitle = new String("Pasted sequences");
2321         }
2322
2323         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2324                 DEFAULT_HEIGHT);
2325
2326       }
2327
2328     } catch (Exception ex)
2329     {
2330       ex.printStackTrace();
2331       System.out.println("Exception whilst pasting: " + ex);
2332       // could be anything being pasted in here
2333     }
2334
2335   }
2336
2337   @Override
2338   protected void expand_newalign(ActionEvent e)
2339   {
2340     try
2341     {
2342       AlignmentI alignment = AlignmentUtils
2343               .expandContext(getViewport().getAlignment(), -1);
2344       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2345               DEFAULT_HEIGHT);
2346       String newtitle = new String("Flanking alignment");
2347
2348       if (Desktop.jalviewClipboard != null
2349               && Desktop.jalviewClipboard[2] != null)
2350       {
2351         HiddenColumns hc = (HiddenColumns) Desktop.jalviewClipboard[2];
2352         af.viewport.setHiddenColumns(hc);
2353       }
2354
2355       // >>>This is a fix for the moment, until a better solution is
2356       // found!!<<<
2357       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2358               .transferSettings(alignPanel.getSeqPanel().seqCanvas
2359                       .getFeatureRenderer());
2360
2361       // TODO: maintain provenance of an alignment, rather than just make the
2362       // title a concatenation of operations.
2363       {
2364         if (title.startsWith("Copied sequences"))
2365         {
2366           newtitle = title;
2367         }
2368         else
2369         {
2370           newtitle = newtitle.concat("- from " + title);
2371         }
2372       }
2373
2374       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2375
2376     } catch (Exception ex)
2377     {
2378       ex.printStackTrace();
2379       System.out.println("Exception whilst pasting: " + ex);
2380       // could be anything being pasted in here
2381     } catch (OutOfMemoryError oom)
2382     {
2383       new OOMWarning("Viewing flanking region of alignment", oom);
2384     }
2385   }
2386
2387   /**
2388    * Action Cut (delete and copy) the selected region
2389    */
2390   @Override
2391   protected void cut_actionPerformed()
2392   {
2393     copy_actionPerformed();
2394     delete_actionPerformed();
2395   }
2396
2397   /**
2398    * Performs menu option to Delete the currently selected region
2399    */
2400   @Override
2401   protected void delete_actionPerformed()
2402   {
2403
2404     SequenceGroup sg = viewport.getSelectionGroup();
2405     if (sg == null)
2406     {
2407       return;
2408     }
2409
2410     Runnable okAction = new Runnable() 
2411     {
2412                 @Override
2413                 public void run() 
2414                 {
2415                     SequenceI[] cut = sg.getSequences()
2416                             .toArray(new SequenceI[sg.getSize()]);
2417
2418                     addHistoryItem(new EditCommand(
2419                             MessageManager.getString("label.cut_sequences"), Action.CUT,
2420                             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2421                             viewport.getAlignment()));
2422
2423                     viewport.setSelectionGroup(null);
2424                     viewport.sendSelection();
2425                     viewport.getAlignment().deleteGroup(sg);
2426
2427                     viewport.firePropertyChange("alignment", null,
2428                             viewport.getAlignment().getSequences());
2429                     if (viewport.getAlignment().getHeight() < 1)
2430                     {
2431                       try
2432                       {
2433                         AlignFrame.this.setClosed(true);
2434                       } catch (Exception ex)
2435                       {
2436                       }
2437                     }
2438                 }};
2439
2440     /*
2441      * If the cut affects all sequences, prompt for confirmation
2442      */
2443     boolean wholeHeight = sg.getSize() == viewport.getAlignment().getHeight();
2444     boolean wholeWidth = (((sg.getEndRes() - sg.getStartRes())
2445             + 1) == viewport.getAlignment().getWidth()) ? true : false;
2446         if (wholeHeight && wholeWidth)
2447         {
2448             JvOptionPane dialog = JvOptionPane.newOptionDialog(Desktop.desktop);
2449                 dialog.setResponseHandler(0, okAction); // 0 = OK_OPTION
2450             Object[] options = new Object[] { MessageManager.getString("action.ok"),
2451                     MessageManager.getString("action.cancel") };
2452                 dialog.showDialog(MessageManager.getString("warn.delete_all"),
2453                     MessageManager.getString("label.delete_all"),
2454                     JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
2455                     options, options[0]);
2456         } else 
2457         {
2458                 okAction.run();
2459         }
2460   }
2461
2462   /**
2463    * DOCUMENT ME!
2464    * 
2465    * @param e
2466    *          DOCUMENT ME!
2467    */
2468   @Override
2469   protected void deleteGroups_actionPerformed(ActionEvent e)
2470   {
2471     if (avc.deleteGroups())
2472     {
2473       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2474       alignPanel.updateAnnotation();
2475       alignPanel.paintAlignment(true, true);
2476     }
2477   }
2478
2479   /**
2480    * DOCUMENT ME!
2481    * 
2482    * @param e
2483    *          DOCUMENT ME!
2484    */
2485   @Override
2486   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2487   {
2488     SequenceGroup sg = new SequenceGroup(
2489             viewport.getAlignment().getSequences());
2490
2491     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2492     viewport.setSelectionGroup(sg);
2493     viewport.isSelectionGroupChanged(true);
2494     viewport.sendSelection();
2495     // JAL-2034 - should delegate to
2496     // alignPanel to decide if overview needs
2497     // updating.
2498     alignPanel.paintAlignment(false, false);
2499     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2500   }
2501
2502   /**
2503    * DOCUMENT ME!
2504    * 
2505    * @param e
2506    *          DOCUMENT ME!
2507    */
2508   @Override
2509   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2510   {
2511     if (viewport.cursorMode)
2512     {
2513       alignPanel.getSeqPanel().keyboardNo1 = null;
2514       alignPanel.getSeqPanel().keyboardNo2 = null;
2515     }
2516     viewport.setSelectionGroup(null);
2517     viewport.getColumnSelection().clear();
2518     viewport.setSelectionGroup(null);
2519     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2520     // JAL-2034 - should delegate to
2521     // alignPanel to decide if overview needs
2522     // updating.
2523     alignPanel.paintAlignment(false, false);
2524     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2525     viewport.sendSelection();
2526   }
2527
2528   /**
2529    * DOCUMENT ME!
2530    * 
2531    * @param e
2532    *          DOCUMENT ME!
2533    */
2534   @Override
2535   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2536   {
2537     SequenceGroup sg = viewport.getSelectionGroup();
2538
2539     if (sg == null)
2540     {
2541       selectAllSequenceMenuItem_actionPerformed(null);
2542
2543       return;
2544     }
2545
2546     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2547     {
2548       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2549     }
2550     // JAL-2034 - should delegate to
2551     // alignPanel to decide if overview needs
2552     // updating.
2553
2554     alignPanel.paintAlignment(true, false);
2555     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2556     viewport.sendSelection();
2557   }
2558
2559   @Override
2560   public void invertColSel_actionPerformed(ActionEvent e)
2561   {
2562     viewport.invertColumnSelection();
2563     alignPanel.paintAlignment(true, false);
2564     viewport.sendSelection();
2565   }
2566
2567   /**
2568    * DOCUMENT ME!
2569    * 
2570    * @param e
2571    *          DOCUMENT ME!
2572    */
2573   @Override
2574   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2575   {
2576     trimAlignment(true);
2577   }
2578
2579   /**
2580    * DOCUMENT ME!
2581    * 
2582    * @param e
2583    *          DOCUMENT ME!
2584    */
2585   @Override
2586   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2587   {
2588     trimAlignment(false);
2589   }
2590
2591   void trimAlignment(boolean trimLeft)
2592   {
2593     ColumnSelection colSel = viewport.getColumnSelection();
2594     int column;
2595
2596     if (!colSel.isEmpty())
2597     {
2598       if (trimLeft)
2599       {
2600         column = colSel.getMin();
2601       }
2602       else
2603       {
2604         column = colSel.getMax();
2605       }
2606
2607       SequenceI[] seqs;
2608       if (viewport.getSelectionGroup() != null)
2609       {
2610         seqs = viewport.getSelectionGroup()
2611                 .getSequencesAsArray(viewport.getHiddenRepSequences());
2612       }
2613       else
2614       {
2615         seqs = viewport.getAlignment().getSequencesArray();
2616       }
2617
2618       TrimRegionCommand trimRegion;
2619       if (trimLeft)
2620       {
2621         trimRegion = new TrimRegionCommand("Remove Left", true, seqs,
2622                 column, viewport.getAlignment());
2623         viewport.getRanges().setStartRes(0);
2624       }
2625       else
2626       {
2627         trimRegion = new TrimRegionCommand("Remove Right", false, seqs,
2628                 column, viewport.getAlignment());
2629       }
2630
2631       setStatus(MessageManager
2632               .formatMessage("label.removed_columns", new String[]
2633               { Integer.valueOf(trimRegion.getSize()).toString() }));
2634
2635       addHistoryItem(trimRegion);
2636
2637       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2638       {
2639         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2640                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2641         {
2642           viewport.getAlignment().deleteGroup(sg);
2643         }
2644       }
2645
2646       viewport.firePropertyChange("alignment", null,
2647               viewport.getAlignment().getSequences());
2648     }
2649   }
2650
2651   /**
2652    * DOCUMENT ME!
2653    * 
2654    * @param e
2655    *          DOCUMENT ME!
2656    */
2657   @Override
2658   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2659   {
2660     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2661
2662     SequenceI[] seqs;
2663     if (viewport.getSelectionGroup() != null)
2664     {
2665       seqs = viewport.getSelectionGroup()
2666               .getSequencesAsArray(viewport.getHiddenRepSequences());
2667       start = viewport.getSelectionGroup().getStartRes();
2668       end = viewport.getSelectionGroup().getEndRes();
2669     }
2670     else
2671     {
2672       seqs = viewport.getAlignment().getSequencesArray();
2673     }
2674
2675     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2676             "Remove Gapped Columns", seqs, start, end,
2677             viewport.getAlignment());
2678
2679     addHistoryItem(removeGapCols);
2680
2681     setStatus(MessageManager
2682             .formatMessage("label.removed_empty_columns", new Object[]
2683             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2684
2685     // This is to maintain viewport position on first residue
2686     // of first sequence
2687     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2688     ViewportRanges ranges = viewport.getRanges();
2689     int startRes = seq.findPosition(ranges.getStartRes());
2690     // ShiftList shifts;
2691     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2692     // edit.alColumnChanges=shifts.getInverse();
2693     // if (viewport.hasHiddenColumns)
2694     // viewport.getColumnSelection().compensateForEdits(shifts);
2695     ranges.setStartRes(seq.findIndex(startRes) - 1);
2696     viewport.firePropertyChange("alignment", null,
2697             viewport.getAlignment().getSequences());
2698
2699   }
2700
2701   /**
2702    * DOCUMENT ME!
2703    * 
2704    * @param e
2705    *          DOCUMENT ME!
2706    */
2707   @Override
2708   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2709   {
2710     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2711
2712     SequenceI[] seqs;
2713     if (viewport.getSelectionGroup() != null)
2714     {
2715       seqs = viewport.getSelectionGroup()
2716               .getSequencesAsArray(viewport.getHiddenRepSequences());
2717       start = viewport.getSelectionGroup().getStartRes();
2718       end = viewport.getSelectionGroup().getEndRes();
2719     }
2720     else
2721     {
2722       seqs = viewport.getAlignment().getSequencesArray();
2723     }
2724
2725     // This is to maintain viewport position on first residue
2726     // of first sequence
2727     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2728     int startRes = seq.findPosition(viewport.getRanges().getStartRes());
2729
2730     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2731             viewport.getAlignment()));
2732
2733     viewport.getRanges().setStartRes(seq.findIndex(startRes) - 1);
2734
2735     viewport.firePropertyChange("alignment", null,
2736             viewport.getAlignment().getSequences());
2737
2738   }
2739
2740   /**
2741    * DOCUMENT ME!
2742    * 
2743    * @param e
2744    *          DOCUMENT ME!
2745    */
2746   @Override
2747   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2748   {
2749     viewport.setPadGaps(padGapsMenuitem.isSelected());
2750     viewport.firePropertyChange("alignment", null,
2751             viewport.getAlignment().getSequences());
2752   }
2753
2754   /**
2755    * DOCUMENT ME!
2756    * 
2757    * @param e
2758    *          DOCUMENT ME!
2759    */
2760   @Override
2761   public void findMenuItem_actionPerformed(ActionEvent e)
2762   {
2763     new Finder();
2764   }
2765
2766   /**
2767    * Create a new view of the current alignment.
2768    */
2769   @Override
2770   public void newView_actionPerformed(ActionEvent e)
2771   {
2772     newView(null, true);
2773   }
2774
2775   /**
2776    * Creates and shows a new view of the current alignment.
2777    * 
2778    * @param viewTitle
2779    *          title of newly created view; if null, one will be generated
2780    * @param copyAnnotation
2781    *          if true then duplicate all annnotation, groups and settings
2782    * @return new alignment panel, already displayed.
2783    */
2784   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2785   {
2786     /*
2787      * Create a new AlignmentPanel (with its own, new Viewport)
2788      */
2789     AlignmentPanel newap = new jalview.project.Jalview2XML()
2790             .copyAlignPanel(alignPanel);
2791     if (!copyAnnotation)
2792     {
2793       /*
2794        * remove all groups and annotation except for the automatic stuff
2795        */
2796       newap.av.getAlignment().deleteAllGroups();
2797       newap.av.getAlignment().deleteAllAnnotations(false);
2798     }
2799
2800     newap.av.setGatherViewsHere(false);
2801
2802     if (viewport.getViewName() == null)
2803     {
2804       viewport.setViewName(MessageManager
2805               .getString("label.view_name_original"));
2806     }
2807
2808     /*
2809      * Views share the same edits undo and redo stacks
2810      */
2811     newap.av.setHistoryList(viewport.getHistoryList());
2812     newap.av.setRedoList(viewport.getRedoList());
2813
2814     /*
2815      * copy any visualisation settings that are not saved in the project
2816      */
2817     newap.av.setColourAppliesToAllGroups(
2818             viewport.getColourAppliesToAllGroups());
2819
2820     /*
2821      * Views share the same mappings; need to deregister any new mappings
2822      * created by copyAlignPanel, and register the new reference to the shared
2823      * mappings
2824      */
2825     newap.av.replaceMappings(viewport.getAlignment());
2826
2827     /*
2828      * start up cDNA consensus (if applicable) now mappings are in place
2829      */
2830     if (newap.av.initComplementConsensus())
2831     {
2832       newap.refresh(true); // adjust layout of annotations
2833     }
2834
2835     newap.av.setViewName(getNewViewName(viewTitle));
2836
2837     addAlignmentPanel(newap, true);
2838     newap.alignmentChanged();
2839
2840     if (alignPanels.size() == 2)
2841     {
2842       viewport.setGatherViewsHere(true);
2843     }
2844     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2845     return newap;
2846   }
2847
2848   /**
2849    * Make a new name for the view, ensuring it is unique within the current
2850    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2851    * these now use viewId. Unique view names are still desirable for usability.)
2852    * 
2853    * @param viewTitle
2854    * @return
2855    */
2856   protected String getNewViewName(String viewTitle)
2857   {
2858     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2859     boolean addFirstIndex = false;
2860     if (viewTitle == null || viewTitle.trim().length() == 0)
2861     {
2862       viewTitle = MessageManager.getString("action.view");
2863       addFirstIndex = true;
2864     }
2865     else
2866     {
2867       index = 1;// we count from 1 if given a specific name
2868     }
2869     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2870
2871     List<Component> comps = PaintRefresher.components
2872             .get(viewport.getSequenceSetId());
2873
2874     List<String> existingNames = getExistingViewNames(comps);
2875
2876     while (existingNames.contains(newViewName))
2877     {
2878       newViewName = viewTitle + " " + (++index);
2879     }
2880     return newViewName;
2881   }
2882
2883   /**
2884    * Returns a list of distinct view names found in the given list of
2885    * components. View names are held on the viewport of an AlignmentPanel.
2886    * 
2887    * @param comps
2888    * @return
2889    */
2890   protected List<String> getExistingViewNames(List<Component> comps)
2891   {
2892     List<String> existingNames = new ArrayList<>();
2893     for (Component comp : comps)
2894     {
2895       if (comp instanceof AlignmentPanel)
2896       {
2897         AlignmentPanel ap = (AlignmentPanel) comp;
2898         if (!existingNames.contains(ap.av.getViewName()))
2899         {
2900           existingNames.add(ap.av.getViewName());
2901         }
2902       }
2903     }
2904     return existingNames;
2905   }
2906
2907   /**
2908    * Explode tabbed views into separate windows.
2909    */
2910   @Override
2911   public void expandViews_actionPerformed(ActionEvent e)
2912   {
2913     Desktop.explodeViews(this);
2914   }
2915
2916   /**
2917    * Gather views in separate windows back into a tabbed presentation.
2918    */
2919   @Override
2920   public void gatherViews_actionPerformed(ActionEvent e)
2921   {
2922     Desktop.instance.gatherViews(this);
2923   }
2924
2925   /**
2926    * DOCUMENT ME!
2927    * 
2928    * @param e
2929    *          DOCUMENT ME!
2930    */
2931   @Override
2932   public void font_actionPerformed(ActionEvent e)
2933   {
2934     new FontChooser(alignPanel);
2935   }
2936
2937   /**
2938    * DOCUMENT ME!
2939    * 
2940    * @param e
2941    *          DOCUMENT ME!
2942    */
2943   @Override
2944   protected void seqLimit_actionPerformed(ActionEvent e)
2945   {
2946     viewport.setShowJVSuffix(seqLimits.isSelected());
2947
2948     alignPanel.getIdPanel().getIdCanvas()
2949             .setPreferredSize(alignPanel.calculateIdWidth());
2950     alignPanel.paintAlignment(true, false);
2951   }
2952
2953   @Override
2954   public void idRightAlign_actionPerformed(ActionEvent e)
2955   {
2956     viewport.setRightAlignIds(idRightAlign.isSelected());
2957     alignPanel.paintAlignment(false, false);
2958   }
2959
2960   @Override
2961   public void centreColumnLabels_actionPerformed(ActionEvent e)
2962   {
2963     viewport.setCentreColumnLabels(centreColumnLabelsMenuItem.getState());
2964     alignPanel.paintAlignment(false, false);
2965   }
2966
2967   /*
2968    * (non-Javadoc)
2969    * 
2970    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2971    */
2972   @Override
2973   protected void followHighlight_actionPerformed()
2974   {
2975     /*
2976      * Set the 'follow' flag on the Viewport (and scroll to position if now
2977      * true).
2978      */
2979     final boolean state = this.followHighlightMenuItem.getState();
2980     viewport.setFollowHighlight(state);
2981     if (state)
2982     {
2983       alignPanel.scrollToPosition(viewport.getSearchResults());
2984     }
2985   }
2986
2987   /**
2988    * DOCUMENT ME!
2989    * 
2990    * @param e
2991    *          DOCUMENT ME!
2992    */
2993   @Override
2994   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2995   {
2996     viewport.setColourText(colourTextMenuItem.isSelected());
2997     alignPanel.paintAlignment(false, false);
2998   }
2999
3000   /**
3001    * DOCUMENT ME!
3002    * 
3003    * @param e
3004    *          DOCUMENT ME!
3005    */
3006   @Override
3007   public void wrapMenuItem_actionPerformed(ActionEvent e)
3008   {
3009     scaleAbove.setVisible(wrapMenuItem.isSelected());
3010     scaleLeft.setVisible(wrapMenuItem.isSelected());
3011     scaleRight.setVisible(wrapMenuItem.isSelected());
3012     viewport.setWrapAlignment(wrapMenuItem.isSelected());
3013     alignPanel.updateLayout();
3014   }
3015
3016   @Override
3017   public void showAllSeqs_actionPerformed(ActionEvent e)
3018   {
3019     viewport.showAllHiddenSeqs();
3020   }
3021
3022   @Override
3023   public void showAllColumns_actionPerformed(ActionEvent e)
3024   {
3025     viewport.showAllHiddenColumns();
3026     alignPanel.paintAlignment(true, true);
3027     viewport.sendSelection();
3028   }
3029
3030   @Override
3031   public void hideSelSequences_actionPerformed(ActionEvent e)
3032   {
3033     viewport.hideAllSelectedSeqs();
3034   }
3035
3036   /**
3037    * called by key handler and the hide all/show all menu items
3038    * 
3039    * @param toggleSeqs
3040    * @param toggleCols
3041    */
3042   private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
3043   {
3044
3045     boolean hide = false;
3046     SequenceGroup sg = viewport.getSelectionGroup();
3047     if (!toggleSeqs && !toggleCols)
3048     {
3049       // Hide everything by the current selection - this is a hack - we do the
3050       // invert and then hide
3051       // first check that there will be visible columns after the invert.
3052       if (viewport.hasSelectedColumns() || (sg != null && sg.getSize() > 0
3053               && sg.getStartRes() <= sg.getEndRes()))
3054       {
3055         // now invert the sequence set, if required - empty selection implies
3056         // that no hiding is required.
3057         if (sg != null)
3058         {
3059           invertSequenceMenuItem_actionPerformed(null);
3060           sg = viewport.getSelectionGroup();
3061           toggleSeqs = true;
3062
3063         }
3064         viewport.expandColSelection(sg, true);
3065         // finally invert the column selection and get the new sequence
3066         // selection.
3067         invertColSel_actionPerformed(null);
3068         toggleCols = true;
3069       }
3070     }
3071
3072     if (toggleSeqs)
3073     {
3074       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
3075       {
3076         hideSelSequences_actionPerformed(null);
3077         hide = true;
3078       }
3079       else if (!(toggleCols && viewport.hasSelectedColumns()))
3080       {
3081         showAllSeqs_actionPerformed(null);
3082       }
3083     }
3084
3085     if (toggleCols)
3086     {
3087       if (viewport.hasSelectedColumns())
3088       {
3089         hideSelColumns_actionPerformed(null);
3090         if (!toggleSeqs)
3091         {
3092           viewport.setSelectionGroup(sg);
3093         }
3094       }
3095       else if (!hide)
3096       {
3097         showAllColumns_actionPerformed(null);
3098       }
3099     }
3100   }
3101
3102   /*
3103    * (non-Javadoc)
3104    * 
3105    * @see
3106    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3107    * event.ActionEvent)
3108    */
3109   @Override
3110   public void hideAllButSelection_actionPerformed(ActionEvent e)
3111   {
3112     toggleHiddenRegions(false, false);
3113     viewport.sendSelection();
3114   }
3115
3116   /*
3117    * (non-Javadoc)
3118    * 
3119    * @see
3120    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3121    * .ActionEvent)
3122    */
3123   @Override
3124   public void hideAllSelection_actionPerformed(ActionEvent e)
3125   {
3126     SequenceGroup sg = viewport.getSelectionGroup();
3127     viewport.expandColSelection(sg, false);
3128     viewport.hideAllSelectedSeqs();
3129     viewport.hideSelectedColumns();
3130     alignPanel.updateLayout();
3131     alignPanel.paintAlignment(true, true);
3132     viewport.sendSelection();
3133   }
3134
3135   /*
3136    * (non-Javadoc)
3137    * 
3138    * @see
3139    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3140    * ActionEvent)
3141    */
3142   @Override
3143   public void showAllhidden_actionPerformed(ActionEvent e)
3144   {
3145     viewport.showAllHiddenColumns();
3146     viewport.showAllHiddenSeqs();
3147     alignPanel.paintAlignment(true, true);
3148     viewport.sendSelection();
3149   }
3150
3151   @Override
3152   public void hideSelColumns_actionPerformed(ActionEvent e)
3153   {
3154     viewport.hideSelectedColumns();
3155     alignPanel.updateLayout();
3156     alignPanel.paintAlignment(true, true);
3157     viewport.sendSelection();
3158   }
3159
3160   @Override
3161   public void hiddenMarkers_actionPerformed(ActionEvent e)
3162   {
3163     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3164     repaint();
3165   }
3166
3167   /**
3168    * DOCUMENT ME!
3169    * 
3170    * @param e
3171    *          DOCUMENT ME!
3172    */
3173   @Override
3174   protected void scaleAbove_actionPerformed(ActionEvent e)
3175   {
3176     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3177     // TODO: do we actually need to update overview for scale above change ?
3178     alignPanel.paintAlignment(true, false);
3179   }
3180
3181   /**
3182    * DOCUMENT ME!
3183    * 
3184    * @param e
3185    *          DOCUMENT ME!
3186    */
3187   @Override
3188   protected void scaleLeft_actionPerformed(ActionEvent e)
3189   {
3190     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3191     alignPanel.paintAlignment(true, false);
3192   }
3193
3194   /**
3195    * DOCUMENT ME!
3196    * 
3197    * @param e
3198    *          DOCUMENT ME!
3199    */
3200   @Override
3201   protected void scaleRight_actionPerformed(ActionEvent e)
3202   {
3203     viewport.setScaleRightWrapped(scaleRight.isSelected());
3204     alignPanel.paintAlignment(true, false);
3205   }
3206
3207   /**
3208    * DOCUMENT ME!
3209    * 
3210    * @param e
3211    *          DOCUMENT ME!
3212    */
3213   @Override
3214   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3215   {
3216     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3217     alignPanel.paintAlignment(false, false);
3218   }
3219
3220   /**
3221    * DOCUMENT ME!
3222    * 
3223    * @param e
3224    *          DOCUMENT ME!
3225    */
3226   @Override
3227   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3228   {
3229     viewport.setShowText(viewTextMenuItem.isSelected());
3230     alignPanel.paintAlignment(false, false);
3231   }
3232
3233   /**
3234    * DOCUMENT ME!
3235    * 
3236    * @param e
3237    *          DOCUMENT ME!
3238    */
3239   @Override
3240   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3241   {
3242     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3243     alignPanel.paintAlignment(false, false);
3244   }
3245
3246   public FeatureSettings featureSettings;
3247
3248   @Override
3249   public FeatureSettingsControllerI getFeatureSettingsUI()
3250   {
3251     return featureSettings;
3252   }
3253
3254   @Override
3255   public void featureSettings_actionPerformed(ActionEvent e)
3256   {
3257     if (featureSettings != null)
3258     {
3259       featureSettings.close();
3260       featureSettings = null;
3261     }
3262     if (!showSeqFeatures.isSelected())
3263     {
3264       // make sure features are actually displayed
3265       showSeqFeatures.setSelected(true);
3266       showSeqFeatures_actionPerformed(null);
3267     }
3268     featureSettings = new FeatureSettings(this);
3269   }
3270
3271   /**
3272    * Set or clear 'Show Sequence Features'
3273    * 
3274    * @param evt
3275    *          DOCUMENT ME!
3276    */
3277   @Override
3278   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3279   {
3280     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3281     alignPanel.paintAlignment(true, true);
3282   }
3283
3284   /**
3285    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3286    * the annotations panel as a whole.
3287    * 
3288    * The options to show/hide all annotations should be enabled when the panel
3289    * is shown, and disabled when the panel is hidden.
3290    * 
3291    * @param e
3292    */
3293   @Override
3294   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3295   {
3296     final boolean setVisible = annotationPanelMenuItem.isSelected();
3297     viewport.setShowAnnotation(setVisible);
3298     this.showAllSeqAnnotations.setEnabled(setVisible);
3299     this.hideAllSeqAnnotations.setEnabled(setVisible);
3300     this.showAllAlAnnotations.setEnabled(setVisible);
3301     this.hideAllAlAnnotations.setEnabled(setVisible);
3302     alignPanel.updateLayout();
3303   }
3304
3305   @Override
3306   public void alignmentProperties()
3307   {
3308     JComponent pane;
3309     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3310
3311             .formatAsHtml();
3312     String content = MessageManager.formatMessage("label.html_content",
3313             new Object[]
3314             { contents.toString() });
3315     contents = null;
3316
3317     if (Platform.isJS())
3318     {
3319       JLabel textLabel = new JLabel();
3320       textLabel.setText(content);
3321       textLabel.setBackground(Color.WHITE);
3322       
3323       pane = new JPanel(new BorderLayout());
3324       ((JPanel) pane).setOpaque(true);
3325       pane.setBackground(Color.WHITE);
3326       ((JPanel) pane).add(textLabel, BorderLayout.NORTH);
3327     }
3328     else
3329     {
3330       JEditorPane editPane = new JEditorPane("text/html", "");
3331       editPane.setEditable(false);
3332       editPane.setText(content);
3333       pane = editPane;
3334     }
3335
3336     JInternalFrame frame = new JInternalFrame();
3337
3338     frame.getContentPane().add(new JScrollPane(pane));
3339
3340     Desktop.addInternalFrame(frame, MessageManager
3341             .formatMessage("label.alignment_properties", new Object[]
3342             { getTitle() }), 500, 400);
3343   }
3344
3345   /**
3346    * DOCUMENT ME!
3347    * 
3348    * @param e
3349    *          DOCUMENT ME!
3350    */
3351   @Override
3352   public void overviewMenuItem_actionPerformed(ActionEvent e)
3353   {
3354     if (alignPanel.overviewPanel != null)
3355     {
3356       return;
3357     }
3358
3359     JInternalFrame frame = new JInternalFrame();
3360     final OverviewPanel overview = new OverviewPanel(alignPanel);
3361     frame.setContentPane(overview);
3362     Desktop.addInternalFrame(frame, MessageManager
3363             .formatMessage("label.overview_params", new Object[]
3364             { this.getTitle() }), true, frame.getWidth(), frame.getHeight(),
3365             true, true);
3366     frame.pack();
3367     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3368     frame.addInternalFrameListener(
3369             new javax.swing.event.InternalFrameAdapter()
3370             {
3371               @Override
3372               public void internalFrameClosed(
3373                       javax.swing.event.InternalFrameEvent evt)
3374               {
3375                 overview.dispose();
3376                 alignPanel.setOverviewPanel(null);
3377               };
3378             });
3379     if (getKeyListeners().length > 0)
3380     {
3381       frame.addKeyListener(getKeyListeners()[0]);
3382     }
3383
3384     alignPanel.setOverviewPanel(overview);
3385   }
3386
3387   @Override
3388   public void textColour_actionPerformed()
3389   {
3390     new TextColourChooser().chooseColour(alignPanel, null);
3391   }
3392
3393   /*
3394    * public void covariationColour_actionPerformed() {
3395    * changeColour(new
3396    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3397    * ()[0])); }
3398    */
3399   @Override
3400   public void annotationColour_actionPerformed()
3401   {
3402     new AnnotationColourChooser(viewport, alignPanel);
3403   }
3404
3405   @Override
3406   public void annotationColumn_actionPerformed(ActionEvent e)
3407   {
3408     new AnnotationColumnChooser(viewport, alignPanel);
3409   }
3410
3411   /**
3412    * Action on the user checking or unchecking the option to apply the selected
3413    * colour scheme to all groups. If unchecked, groups may have their own
3414    * independent colour schemes.
3415    * 
3416    * @param selected
3417    */
3418   @Override
3419   public void applyToAllGroups_actionPerformed(boolean selected)
3420   {
3421     viewport.setColourAppliesToAllGroups(selected);
3422   }
3423
3424   /**
3425    * Action on user selecting a colour from the colour menu
3426    * 
3427    * @param name
3428    *          the name (not the menu item label!) of the colour scheme
3429    */
3430   @Override
3431   public void changeColour_actionPerformed(String name)
3432   {
3433     /*
3434      * 'User Defined' opens a panel to configure or load a
3435      * user-defined colour scheme
3436      */
3437     if (ResidueColourScheme.USER_DEFINED_MENU.equals(name))
3438     {
3439       new UserDefinedColours(alignPanel);
3440       return;
3441     }
3442
3443     /*
3444      * otherwise set the chosen colour scheme (or null for 'None')
3445      */
3446     ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(name,
3447             viewport,
3448             viewport.getAlignment(), viewport.getHiddenRepSequences());
3449     changeColour(cs);
3450   }
3451
3452   /**
3453    * Actions on setting or changing the alignment colour scheme
3454    * 
3455    * @param cs
3456    */
3457   @Override
3458   public void changeColour(ColourSchemeI cs)
3459   {
3460     // TODO: pull up to controller method
3461     ColourMenuHelper.setColourSelected(colourMenu, cs);
3462
3463     viewport.setGlobalColourScheme(cs);
3464
3465     alignPanel.paintAlignment(true, true);
3466   }
3467
3468   /**
3469    * Show the PID threshold slider panel
3470    */
3471   @Override
3472   protected void modifyPID_actionPerformed()
3473   {
3474     SliderPanel.setPIDSliderSource(alignPanel, viewport.getResidueShading(),
3475             alignPanel.getViewName());
3476     SliderPanel.showPIDSlider();
3477   }
3478
3479   /**
3480    * Show the Conservation slider panel
3481    */
3482   @Override
3483   protected void modifyConservation_actionPerformed()
3484   {
3485     SliderPanel.setConservationSlider(alignPanel,
3486             viewport.getResidueShading(), alignPanel.getViewName());
3487     SliderPanel.showConservationSlider();
3488   }
3489
3490   /**
3491    * Action on selecting or deselecting (Colour) By Conservation
3492    */
3493   @Override
3494   public void conservationMenuItem_actionPerformed(boolean selected)
3495   {
3496     modifyConservation.setEnabled(selected);
3497     viewport.setConservationSelected(selected);
3498     viewport.getResidueShading().setConservationApplied(selected);
3499
3500     changeColour(viewport.getGlobalColourScheme());
3501     if (selected)
3502     {
3503       modifyConservation_actionPerformed();
3504     }
3505     else
3506     {
3507       SliderPanel.hideConservationSlider();
3508     }
3509   }
3510
3511   /**
3512    * Action on selecting or deselecting (Colour) Above PID Threshold
3513    */
3514   @Override
3515   public void abovePIDThreshold_actionPerformed(boolean selected)
3516   {
3517     modifyPID.setEnabled(selected);
3518     viewport.setAbovePIDThreshold(selected);
3519     if (!selected)
3520     {
3521       viewport.getResidueShading().setThreshold(0,
3522               viewport.isIgnoreGapsConsensus());
3523     }
3524
3525     changeColour(viewport.getGlobalColourScheme());
3526     if (selected)
3527     {
3528       modifyPID_actionPerformed();
3529     }
3530     else
3531     {
3532       SliderPanel.hidePIDSlider();
3533     }
3534   }
3535
3536   /**
3537    * DOCUMENT ME!
3538    * 
3539    * @param e
3540    *          DOCUMENT ME!
3541    */
3542   @Override
3543   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3544   {
3545     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3546     AlignmentSorter.sortByPID(viewport.getAlignment(),
3547             viewport.getAlignment().getSequenceAt(0));
3548     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3549             viewport.getAlignment()));
3550     alignPanel.paintAlignment(true, false);
3551   }
3552
3553   /**
3554    * DOCUMENT ME!
3555    * 
3556    * @param e
3557    *          DOCUMENT ME!
3558    */
3559   @Override
3560   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3561   {
3562     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3563     AlignmentSorter.sortByID(viewport.getAlignment());
3564     addHistoryItem(
3565             new OrderCommand("ID Sort", oldOrder, viewport.getAlignment()));
3566     alignPanel.paintAlignment(true, false);
3567   }
3568
3569   /**
3570    * DOCUMENT ME!
3571    * 
3572    * @param e
3573    *          DOCUMENT ME!
3574    */
3575   @Override
3576   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3577   {
3578     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3579     AlignmentSorter.sortByLength(viewport.getAlignment());
3580     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3581             viewport.getAlignment()));
3582     alignPanel.paintAlignment(true, false);
3583   }
3584
3585   /**
3586    * DOCUMENT ME!
3587    * 
3588    * @param e
3589    *          DOCUMENT ME!
3590    */
3591   @Override
3592   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3593   {
3594     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3595     AlignmentSorter.sortByGroup(viewport.getAlignment());
3596     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3597             viewport.getAlignment()));
3598
3599     alignPanel.paintAlignment(true, false);
3600   }
3601
3602   /**
3603    * DOCUMENT ME!
3604    * 
3605    * @param e
3606    *          DOCUMENT ME!
3607    */
3608   @Override
3609   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3610   {
3611     new RedundancyPanel(alignPanel, this);
3612   }
3613
3614   /**
3615    * DOCUMENT ME!
3616    * 
3617    * @param e
3618    *          DOCUMENT ME!
3619    */
3620   @Override
3621   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3622   {
3623     if ((viewport.getSelectionGroup() == null)
3624             || (viewport.getSelectionGroup().getSize() < 2))
3625     {
3626       JvOptionPane.showInternalMessageDialog(this,
3627               MessageManager.getString(
3628                       "label.you_must_select_least_two_sequences"),
3629               MessageManager.getString("label.invalid_selection"),
3630               JvOptionPane.WARNING_MESSAGE);
3631     }
3632     else
3633     {
3634       JInternalFrame frame = new JInternalFrame();
3635       frame.setContentPane(new PairwiseAlignPanel(viewport));
3636       Desktop.addInternalFrame(frame,
3637               MessageManager.getString("action.pairwise_alignment"), 600,
3638               500);
3639     }
3640   }
3641
3642   @Override
3643   public void autoCalculate_actionPerformed(ActionEvent e)
3644   {
3645     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3646     if (viewport.autoCalculateConsensus)
3647     {
3648       viewport.firePropertyChange("alignment", null,
3649               viewport.getAlignment().getSequences());
3650     }
3651   }
3652
3653   @Override
3654   public void sortByTreeOption_actionPerformed(ActionEvent e)
3655   {
3656     viewport.sortByTree = sortByTree.isSelected();
3657   }
3658
3659   @Override
3660   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3661   {
3662     viewport.followSelection = listenToViewSelections.isSelected();
3663   }
3664
3665   /**
3666    * Constructs a tree panel and adds it to the desktop
3667    * 
3668    * @param type
3669    *          tree type (NJ or AV)
3670    * @param modelName
3671    *          name of score model used to compute the tree
3672    * @param options
3673    *          parameters for the distance or similarity calculation
3674    */
3675   void newTreePanel(String type, String modelName,
3676           SimilarityParamsI options)
3677   {
3678     String frameTitle = "";
3679     TreePanel tp;
3680
3681     boolean onSelection = false;
3682     if (viewport.getSelectionGroup() != null
3683             && viewport.getSelectionGroup().getSize() > 0)
3684     {
3685       SequenceGroup sg = viewport.getSelectionGroup();
3686
3687       /* Decide if the selection is a column region */
3688       for (SequenceI _s : sg.getSequences())
3689       {
3690         if (_s.getLength() < sg.getEndRes())
3691         {
3692           JvOptionPane.showMessageDialog(Desktop.desktop,
3693                   MessageManager.getString(
3694                           "label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
3695                   MessageManager.getString(
3696                           "label.sequences_selection_not_aligned"),
3697                   JvOptionPane.WARNING_MESSAGE);
3698
3699           return;
3700         }
3701       }
3702       onSelection = true;
3703     }
3704     else
3705     {
3706       if (viewport.getAlignment().getHeight() < 2)
3707       {
3708         return;
3709       }
3710     }
3711
3712     tp = new TreePanel(alignPanel, type, modelName, options);
3713     frameTitle = tp.getPanelTitle() + (onSelection ? " on region" : "");
3714
3715     frameTitle += " from ";
3716
3717     if (viewport.getViewName() != null)
3718     {
3719       frameTitle += viewport.getViewName() + " of ";
3720     }
3721
3722     frameTitle += this.title;
3723
3724     Desktop.addInternalFrame(tp, frameTitle, 600, 500);
3725   }
3726
3727   /**
3728    * DOCUMENT ME!
3729    * 
3730    * @param title
3731    *          DOCUMENT ME!
3732    * @param order
3733    *          DOCUMENT ME!
3734    */
3735   public void addSortByOrderMenuItem(String title,
3736           final AlignmentOrder order)
3737   {
3738     final JMenuItem item = new JMenuItem(MessageManager
3739             .formatMessage("action.by_title_param", new Object[]
3740             { title }));
3741     sort.add(item);
3742     item.addActionListener(new java.awt.event.ActionListener()
3743     {
3744       @Override
3745       public void actionPerformed(ActionEvent e)
3746       {
3747         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3748
3749         // TODO: JBPNote - have to map order entries to curent SequenceI
3750         // pointers
3751         AlignmentSorter.sortBy(viewport.getAlignment(), order);
3752
3753         addHistoryItem(new OrderCommand(order.getName(), oldOrder,
3754                 viewport.getAlignment()));
3755
3756         alignPanel.paintAlignment(true, false);
3757       }
3758     });
3759   }
3760
3761   /**
3762    * Add a new sort by annotation score menu item
3763    * 
3764    * @param sort
3765    *          the menu to add the option to
3766    * @param scoreLabel
3767    *          the label used to retrieve scores for each sequence on the
3768    *          alignment
3769    */
3770   public void addSortByAnnotScoreMenuItem(JMenu sort,
3771           final String scoreLabel)
3772   {
3773     final JMenuItem item = new JMenuItem(scoreLabel);
3774     sort.add(item);
3775     item.addActionListener(new java.awt.event.ActionListener()
3776     {
3777       @Override
3778       public void actionPerformed(ActionEvent e)
3779       {
3780         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3781         AlignmentSorter.sortByAnnotationScore(scoreLabel,
3782                 viewport.getAlignment());// ,viewport.getSelectionGroup());
3783         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
3784                 viewport.getAlignment()));
3785         alignPanel.paintAlignment(true, false);
3786       }
3787     });
3788   }
3789
3790   /**
3791    * last hash for alignment's annotation array - used to minimise cost of
3792    * rebuild.
3793    */
3794   protected int _annotationScoreVectorHash;
3795
3796   /**
3797    * search the alignment and rebuild the sort by annotation score submenu the
3798    * last alignment annotation vector hash is stored to minimize cost of
3799    * rebuilding in subsequence calls.
3800    * 
3801    */
3802   @Override
3803   public void buildSortByAnnotationScoresMenu()
3804   {
3805     if (viewport.getAlignment().getAlignmentAnnotation() == null)
3806     {
3807       return;
3808     }
3809
3810     if (viewport.getAlignment().getAlignmentAnnotation()
3811             .hashCode() != _annotationScoreVectorHash)
3812     {
3813       sortByAnnotScore.removeAll();
3814       // almost certainly a quicker way to do this - but we keep it simple
3815       Hashtable scoreSorts = new Hashtable();
3816       AlignmentAnnotation aann[];
3817       for (SequenceI sqa : viewport.getAlignment().getSequences())
3818       {
3819         aann = sqa.getAnnotation();
3820         for (int i = 0; aann != null && i < aann.length; i++)
3821         {
3822           if (aann[i].hasScore() && aann[i].sequenceRef != null)
3823           {
3824             scoreSorts.put(aann[i].label, aann[i].label);
3825           }
3826         }
3827       }
3828       Enumeration labels = scoreSorts.keys();
3829       while (labels.hasMoreElements())
3830       {
3831         addSortByAnnotScoreMenuItem(sortByAnnotScore,
3832                 (String) labels.nextElement());
3833       }
3834       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
3835       scoreSorts.clear();
3836
3837       _annotationScoreVectorHash = viewport.getAlignment()
3838               .getAlignmentAnnotation().hashCode();
3839     }
3840   }
3841
3842   /**
3843    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
3844    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
3845    * call. Listeners are added to remove the menu item when the treePanel is
3846    * closed, and adjust the tree leaf to sequence mapping when the alignment is
3847    * modified.
3848    */
3849   @Override
3850   public void buildTreeSortMenu()
3851   {
3852     sortByTreeMenu.removeAll();
3853
3854     List<Component> comps = PaintRefresher.components
3855             .get(viewport.getSequenceSetId());
3856     List<TreePanel> treePanels = new ArrayList<>();
3857     for (Component comp : comps)
3858     {
3859       if (comp instanceof TreePanel)
3860       {
3861         treePanels.add((TreePanel) comp);
3862       }
3863     }
3864
3865     if (treePanels.size() < 1)
3866     {
3867       sortByTreeMenu.setVisible(false);
3868       return;
3869     }
3870
3871     sortByTreeMenu.setVisible(true);
3872
3873     for (final TreePanel tp : treePanels)
3874     {
3875       final JMenuItem item = new JMenuItem(tp.getTitle());
3876       item.addActionListener(new java.awt.event.ActionListener()
3877       {
3878         @Override
3879         public void actionPerformed(ActionEvent e)
3880         {
3881           tp.sortByTree_actionPerformed();
3882           addHistoryItem(tp.sortAlignmentIn(alignPanel));
3883
3884         }
3885       });
3886
3887       sortByTreeMenu.add(item);
3888     }
3889   }
3890
3891   public boolean sortBy(AlignmentOrder alorder, String undoname)
3892   {
3893     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3894     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
3895     if (undoname != null)
3896     {
3897       addHistoryItem(new OrderCommand(undoname, oldOrder,
3898               viewport.getAlignment()));
3899     }
3900     alignPanel.paintAlignment(true, false);
3901     return true;
3902   }
3903
3904   /**
3905    * Work out whether the whole set of sequences or just the selected set will
3906    * be submitted for multiple alignment.
3907    * 
3908    */
3909   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
3910   {
3911     // Now, check we have enough sequences
3912     AlignmentView msa = null;
3913
3914     if ((viewport.getSelectionGroup() != null)
3915             && (viewport.getSelectionGroup().getSize() > 1))
3916     {
3917       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
3918       // some common interface!
3919       /*
3920        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
3921        * SequenceI[sz = seqs.getSize(false)];
3922        * 
3923        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
3924        * seqs.getSequenceAt(i); }
3925        */
3926       msa = viewport.getAlignmentView(true);
3927     }
3928     else if (viewport.getSelectionGroup() != null
3929             && viewport.getSelectionGroup().getSize() == 1)
3930     {
3931       int option = JvOptionPane.showConfirmDialog(this,
3932               MessageManager.getString("warn.oneseq_msainput_selection"),
3933               MessageManager.getString("label.invalid_selection"),
3934               JvOptionPane.OK_CANCEL_OPTION);
3935       if (option == JvOptionPane.OK_OPTION)
3936       {
3937         msa = viewport.getAlignmentView(false);
3938       }
3939     }
3940     else
3941     {
3942       msa = viewport.getAlignmentView(false);
3943     }
3944     return msa;
3945   }
3946
3947   /**
3948    * Decides what is submitted to a secondary structure prediction service: the
3949    * first sequence in the alignment, or in the current selection, or, if the
3950    * alignment is 'aligned' (ie padded with gaps), then the currently selected
3951    * region or the whole alignment. (where the first sequence in the set is the
3952    * one that the prediction will be for).
3953    */
3954   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
3955   {
3956     AlignmentView seqs = null;
3957
3958     if ((viewport.getSelectionGroup() != null)
3959             && (viewport.getSelectionGroup().getSize() > 0))
3960     {
3961       seqs = viewport.getAlignmentView(true);
3962     }
3963     else
3964     {
3965       seqs = viewport.getAlignmentView(false);
3966     }
3967     // limit sequences - JBPNote in future - could spawn multiple prediction
3968     // jobs
3969     // TODO: viewport.getAlignment().isAligned is a global state - the local
3970     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
3971     if (!viewport.getAlignment().isAligned(false))
3972     {
3973       seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] });
3974       // TODO: if seqs.getSequences().length>1 then should really have warned
3975       // user!
3976
3977     }
3978     return seqs;
3979   }
3980
3981   /**
3982    * DOCUMENT ME!
3983    * 
3984    * @param e
3985    *          DOCUMENT ME!
3986    */
3987   @Override
3988   protected void loadTreeMenuItem_actionPerformed(ActionEvent e)
3989   {
3990     // Pick the tree file
3991     JalviewFileChooser chooser = new JalviewFileChooser(
3992             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
3993     chooser.setFileView(new JalviewFileView());
3994     chooser.setDialogTitle(
3995             MessageManager.getString("label.select_newick_like_tree_file"));
3996     chooser.setToolTipText(
3997             MessageManager.getString("label.load_tree_file"));
3998
3999     chooser.setResponseHandler(0,new Runnable()
4000     {
4001       @Override
4002       public void run()
4003       {
4004         String filePath = chooser.getSelectedFile().getPath();
4005         Cache.setProperty("LAST_DIRECTORY", filePath);
4006         NewickFile fin = null;
4007         try
4008         {
4009           fin = new NewickFile(new FileParse(chooser.getSelectedFile(),
4010                   DataSourceType.FILE));
4011           viewport.setCurrentTree(showNewickTree(fin, filePath).getTree());
4012         } catch (Exception ex)
4013         {
4014           JvOptionPane.showMessageDialog(Desktop.desktop, ex.getMessage(),
4015                   MessageManager
4016                           .getString("label.problem_reading_tree_file"),
4017                   JvOptionPane.WARNING_MESSAGE);
4018           ex.printStackTrace();
4019         }
4020         if (fin != null && fin.hasWarningMessage())
4021         {
4022           JvOptionPane.showMessageDialog(Desktop.desktop,
4023                   fin.getWarningMessage(),
4024                   MessageManager.getString(
4025                           "label.possible_problem_with_tree_file"),
4026                   JvOptionPane.WARNING_MESSAGE);
4027         }
4028       }
4029     });
4030     chooser.showOpenDialog(this);
4031   }
4032
4033   public TreePanel showNewickTree(NewickFile nf, String treeTitle)
4034   {
4035     return showNewickTree(nf, treeTitle, 600, 500, 4, 5);
4036   }
4037
4038   public TreePanel showNewickTree(NewickFile nf, String treeTitle, int w,
4039           int h, int x, int y)
4040   {
4041     return showNewickTree(nf, treeTitle, null, w, h, x, y);
4042   }
4043
4044   /**
4045    * Add a treeviewer for the tree extracted from a Newick file object to the
4046    * current alignment view
4047    * 
4048    * @param nf
4049    *          the tree
4050    * @param title
4051    *          tree viewer title
4052    * @param input
4053    *          Associated alignment input data (or null)
4054    * @param w
4055    *          width
4056    * @param h
4057    *          height
4058    * @param x
4059    *          position
4060    * @param y
4061    *          position
4062    * @return TreePanel handle
4063    */
4064   public TreePanel showNewickTree(NewickFile nf, String treeTitle,
4065           AlignmentView input, int w, int h, int x, int y)
4066   {
4067     TreePanel tp = null;
4068
4069     try
4070     {
4071       nf.parse();
4072
4073       if (nf.getTree() != null)
4074       {
4075         tp = new TreePanel(alignPanel, nf, treeTitle, input);
4076
4077         tp.setSize(w, h);
4078
4079         if (x > 0 && y > 0)
4080         {
4081           tp.setLocation(x, y);
4082         }
4083
4084         Desktop.addInternalFrame(tp, treeTitle, w, h);
4085       }
4086     } catch (Exception ex)
4087     {
4088       ex.printStackTrace();
4089     }
4090
4091     return tp;
4092   }
4093
4094   private boolean buildingMenu = false;
4095
4096   /**
4097    * Generates menu items and listener event actions for web service clients
4098    * 
4099    */
4100   public void BuildWebServiceMenu()
4101   {
4102     while (buildingMenu)
4103     {
4104       try
4105       {
4106         System.err.println("Waiting for building menu to finish.");
4107         Thread.sleep(10);
4108       } catch (Exception e)
4109       {
4110       }
4111     }
4112     final AlignFrame me = this;
4113     buildingMenu = true;
4114     new Thread(new Runnable()
4115     {
4116       @Override
4117       public void run()
4118       {
4119         final List<JMenuItem> legacyItems = new ArrayList<>();
4120         try
4121         {
4122           // System.err.println("Building ws menu again "
4123           // + Thread.currentThread());
4124           // TODO: add support for context dependent disabling of services based
4125           // on
4126           // alignment and current selection
4127           // TODO: add additional serviceHandle parameter to specify abstract
4128           // handler
4129           // class independently of AbstractName
4130           // TODO: add in rediscovery GUI function to restart discoverer
4131           // TODO: group services by location as well as function and/or
4132           // introduce
4133           // object broker mechanism.
4134           final Vector<JMenu> wsmenu = new Vector<>();
4135           final IProgressIndicator af = me;
4136
4137           /*
4138            * do not i18n these strings - they are hard-coded in class
4139            * compbio.data.msa.Category, Jws2Discoverer.isRecalculable() and
4140            * SequenceAnnotationWSClient.initSequenceAnnotationWSClient()
4141            */
4142           final JMenu msawsmenu = new JMenu("Alignment");
4143           final JMenu secstrmenu = new JMenu(
4144                   "Secondary Structure Prediction");
4145           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4146           final JMenu analymenu = new JMenu("Analysis");
4147           final JMenu dismenu = new JMenu("Protein Disorder");
4148           // JAL-940 - only show secondary structure prediction services from
4149           // the legacy server
4150           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4151               // &&
4152           Discoverer.services != null && (Discoverer.services.size() > 0))
4153           {
4154             // TODO: refactor to allow list of AbstractName/Handler bindings to
4155             // be
4156             // stored or retrieved from elsewhere
4157             // No MSAWS used any more:
4158             // Vector msaws = null; // (Vector)
4159             // Discoverer.services.get("MsaWS");
4160             Vector secstrpr = (Vector) Discoverer.services
4161                     .get("SecStrPred");
4162             if (secstrpr != null)
4163             {
4164               // Add any secondary structure prediction services
4165               for (int i = 0, j = secstrpr.size(); i < j; i++)
4166               {
4167                 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4168                         .get(i);
4169                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4170                         .getServiceClient(sh);
4171                 int p = secstrmenu.getItemCount();
4172                 impl.attachWSMenuEntry(secstrmenu, me);
4173                 int q = secstrmenu.getItemCount();
4174                 for (int litm = p; litm < q; litm++)
4175                 {
4176                   legacyItems.add(secstrmenu.getItem(litm));
4177                 }
4178               }
4179             }
4180           }
4181
4182           // Add all submenus in the order they should appear on the web
4183           // services menu
4184           wsmenu.add(msawsmenu);
4185           wsmenu.add(secstrmenu);
4186           wsmenu.add(dismenu);
4187           wsmenu.add(analymenu);
4188           // No search services yet
4189           // wsmenu.add(seqsrchmenu);
4190
4191           javax.swing.SwingUtilities.invokeLater(new Runnable()
4192           {
4193             @Override
4194             public void run()
4195             {
4196               try
4197               {
4198                 webService.removeAll();
4199                 // first, add discovered services onto the webservices menu
4200                 if (wsmenu.size() > 0)
4201                 {
4202                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4203                   {
4204                     webService.add(wsmenu.get(i));
4205                   }
4206                 }
4207                 else
4208                 {
4209                   webService.add(me.webServiceNoServices);
4210                 }
4211                 // TODO: move into separate menu builder class.
4212                 boolean new_sspred = false;
4213                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4214                 {
4215                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4216                   if (jws2servs != null)
4217                   {
4218                     if (jws2servs.hasServices())
4219                     {
4220                       jws2servs.attachWSMenuEntry(webService, me);
4221                       for (Jws2Instance sv : jws2servs.getServices())
4222                       {
4223                         if (sv.description.toLowerCase().contains("jpred"))
4224                         {
4225                           for (JMenuItem jmi : legacyItems)
4226                           {
4227                             jmi.setVisible(false);
4228                           }
4229                         }
4230                       }
4231
4232                     }
4233                     if (jws2servs.isRunning())
4234                     {
4235                       JMenuItem tm = new JMenuItem(
4236                               "Still discovering JABA Services");
4237                       tm.setEnabled(false);
4238                       webService.add(tm);
4239                     }
4240                   }
4241                 }
4242                 build_urlServiceMenu(me.webService);
4243                 build_fetchdbmenu(webService);
4244                 for (JMenu item : wsmenu)
4245                 {
4246                   if (item.getItemCount() == 0)
4247                   {
4248                     item.setEnabled(false);
4249                   }
4250                   else
4251                   {
4252                     item.setEnabled(true);
4253                   }
4254                 }
4255               } catch (Exception e)
4256               {
4257                 Cache.log.debug(
4258                         "Exception during web service menu building process.",
4259                         e);
4260               }
4261             }
4262           });
4263         } catch (Exception e)
4264         {
4265         }
4266         buildingMenu = false;
4267       }
4268     }).start();
4269
4270   }
4271
4272   /**
4273    * construct any groupURL type service menu entries.
4274    * 
4275    * @param webService
4276    */
4277   private void build_urlServiceMenu(JMenu webService)
4278   {
4279     // TODO: remove this code when 2.7 is released
4280     // DEBUG - alignmentView
4281     /*
4282      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4283      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4284      * 
4285      * @Override public void actionPerformed(ActionEvent e) {
4286      * jalview.datamodel.AlignmentView
4287      * .testSelectionViews(af.viewport.getAlignment(),
4288      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4289      * 
4290      * }); webService.add(testAlView);
4291      */
4292     // TODO: refactor to RestClient discoverer and merge menu entries for
4293     // rest-style services with other types of analysis/calculation service
4294     // SHmmr test client - still being implemented.
4295     // DEBUG - alignmentView
4296
4297     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4298             .getRestClients())
4299     {
4300       client.attachWSMenuEntry(
4301               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4302               this);
4303     }
4304   }
4305
4306   /**
4307    * Searches the alignment sequences for xRefs and builds the Show
4308    * Cross-References menu (formerly called Show Products), with database
4309    * sources for which cross-references are found (protein sources for a
4310    * nucleotide alignment and vice versa)
4311    * 
4312    * @return true if Show Cross-references menu should be enabled
4313    */
4314   public boolean canShowProducts()
4315   {
4316     SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
4317     AlignmentI dataset = viewport.getAlignment().getDataset();
4318
4319     showProducts.removeAll();
4320     final boolean dna = viewport.getAlignment().isNucleotide();
4321
4322     if (seqs == null || seqs.length == 0)
4323     {
4324       // nothing to see here.
4325       return false;
4326     }
4327
4328     boolean showp = false;
4329     try
4330     {
4331       List<String> ptypes = new CrossRef(seqs, dataset)
4332               .findXrefSourcesForSequences(dna);
4333
4334       for (final String source : ptypes)
4335       {
4336         showp = true;
4337         final AlignFrame af = this;
4338         JMenuItem xtype = new JMenuItem(source);
4339         xtype.addActionListener(new ActionListener()
4340         {
4341           @Override
4342           public void actionPerformed(ActionEvent e)
4343           {
4344             showProductsFor(af.viewport.getSequenceSelection(), dna,
4345                     source);
4346           }
4347         });
4348         showProducts.add(xtype);
4349       }
4350       showProducts.setVisible(showp);
4351       showProducts.setEnabled(showp);
4352     } catch (Exception e)
4353     {
4354       Cache.log.warn(
4355               "canShowProducts threw an exception - please report to help@jalview.org",
4356               e);
4357       return false;
4358     }
4359     return showp;
4360   }
4361
4362   /**
4363    * Finds and displays cross-references for the selected sequences (protein
4364    * products for nucleotide sequences, dna coding sequences for peptides).
4365    * 
4366    * @param sel
4367    *          the sequences to show cross-references for
4368    * @param dna
4369    *          true if from a nucleotide alignment (so showing proteins)
4370    * @param source
4371    *          the database to show cross-references for
4372    */
4373   protected void showProductsFor(final SequenceI[] sel, final boolean _odna,
4374           final String source)
4375   {
4376     new Thread(CrossRefAction.getHandlerFor(sel, _odna, source, this))
4377             .start();
4378   }
4379
4380   /**
4381    * Construct and display a new frame containing the translation of this
4382    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
4383    */
4384   @Override
4385   public void showTranslation_actionPerformed(GeneticCodeI codeTable)
4386   {
4387     AlignmentI al = null;
4388     try
4389     {
4390       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4391
4392       al = dna.translateCdna(codeTable);
4393     } catch (Exception ex)
4394     {
4395       jalview.bin.Cache.log.error(
4396               "Exception during translation. Please report this !", ex);
4397       final String msg = MessageManager.getString(
4398               "label.error_when_translating_sequences_submit_bug_report");
4399       final String errorTitle = MessageManager
4400               .getString("label.implementation_error")
4401               + MessageManager.getString("label.translation_failed");
4402       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4403               JvOptionPane.ERROR_MESSAGE);
4404       return;
4405     }
4406     if (al == null || al.getHeight() == 0)
4407     {
4408       final String msg = MessageManager.getString(
4409               "label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4410       final String errorTitle = MessageManager
4411               .getString("label.translation_failed");
4412       JvOptionPane.showMessageDialog(Desktop.desktop, msg, errorTitle,
4413               JvOptionPane.WARNING_MESSAGE);
4414     }
4415     else
4416     {
4417       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4418       af.setFileFormat(this.currentFileFormat);
4419       final String newTitle = MessageManager
4420               .formatMessage("label.translation_of_params", new Object[]
4421               { this.getTitle(), codeTable.getId() });
4422       af.setTitle(newTitle);
4423       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
4424       {
4425         final SequenceI[] seqs = viewport.getSelectionAsNewSequence();
4426         viewport.openSplitFrame(af, new Alignment(seqs));
4427       }
4428       else
4429       {
4430         Desktop.addInternalFrame(af, newTitle, DEFAULT_WIDTH,
4431                 DEFAULT_HEIGHT);
4432       }
4433     }
4434   }
4435
4436   /**
4437    * Set the file format
4438    * 
4439    * @param format
4440    */
4441   public void setFileFormat(FileFormatI format)
4442   {
4443     this.currentFileFormat = format;
4444   }
4445
4446   /**
4447    * Try to load a features file onto the alignment.
4448    * 
4449    * @param file
4450    *          contents or path to retrieve file or a File object
4451    * @param sourceType
4452    *          access mode of file (see jalview.io.AlignFile)
4453    * @return true if features file was parsed correctly.
4454    */
4455   public boolean parseFeaturesFile(Object file, DataSourceType sourceType)
4456   {
4457     // BH 2018
4458     return avc.parseFeaturesFile(file, sourceType,
4459             Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4460
4461   }
4462
4463   @Override
4464   public void refreshFeatureUI(boolean enableIfNecessary)
4465   {
4466     // note - currently this is only still here rather than in the controller
4467     // because of the featureSettings hard reference that is yet to be
4468     // abstracted
4469     if (enableIfNecessary)
4470     {
4471       viewport.setShowSequenceFeatures(true);
4472       showSeqFeatures.setSelected(true);
4473     }
4474
4475   }
4476
4477   @Override
4478   public void dragEnter(DropTargetDragEvent evt)
4479   {
4480   }
4481
4482   @Override
4483   public void dragExit(DropTargetEvent evt)
4484   {
4485   }
4486
4487   @Override
4488   public void dragOver(DropTargetDragEvent evt)
4489   {
4490   }
4491
4492   @Override
4493   public void dropActionChanged(DropTargetDragEvent evt)
4494   {
4495   }
4496
4497   @Override
4498   public void drop(DropTargetDropEvent evt)
4499   {
4500     // JAL-1552 - acceptDrop required before getTransferable call for
4501     // Java's Transferable for native dnd
4502     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4503     Transferable t = evt.getTransferable();
4504
4505     final AlignFrame thisaf = this;
4506     final List<Object> files = new ArrayList<>();
4507     List<DataSourceType> protocols = new ArrayList<>();
4508
4509     try
4510     {
4511       Desktop.transferFromDropTarget(files, protocols, evt, t);
4512     } catch (Exception e)
4513     {
4514       e.printStackTrace();
4515     }
4516     if (files != null)
4517     {
4518       new Thread(new Runnable()
4519       {
4520         @Override
4521         public void run()
4522         {
4523           try
4524           {
4525             // check to see if any of these files have names matching sequences
4526             // in
4527             // the alignment
4528             SequenceIdMatcher idm = new SequenceIdMatcher(
4529                     viewport.getAlignment().getSequencesArray());
4530             /**
4531              * Object[] { String,SequenceI}
4532              */
4533             ArrayList<Object[]> filesmatched = new ArrayList<>();
4534             ArrayList<Object> filesnotmatched = new ArrayList<>();
4535             for (int i = 0; i < files.size(); i++)
4536             {
4537               // BH 2018
4538               Object file = files.get(i);
4539               String fileName = file.toString();
4540               String pdbfn = "";
4541               DataSourceType protocol = (file instanceof File
4542                       ? DataSourceType.FILE
4543                       : FormatAdapter.checkProtocol(fileName));
4544               if (protocol == DataSourceType.FILE)
4545               {
4546                 File fl = (file instanceof File ? (File) file
4547                         : new File(fileName));
4548                 pdbfn = fl.getName();
4549               }
4550               else if (protocol == DataSourceType.URL)
4551               {
4552                 URL url = new URL(fileName);
4553                 pdbfn = url.getFile();
4554               }
4555               if (pdbfn.length() > 0)
4556               {
4557                 // attempt to find a match in the alignment
4558                 SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
4559                 int l = 0, c = pdbfn.indexOf(".");
4560                 while (mtch == null && c != -1)
4561                 {
4562                   do
4563                   {
4564                     l = c;
4565                   } while ((c = pdbfn.indexOf(".", l)) > l);
4566                   if (l > -1)
4567                   {
4568                     pdbfn = pdbfn.substring(0, l);
4569                   }
4570                   mtch = idm.findAllIdMatches(pdbfn);
4571                 }
4572                 if (mtch != null)
4573                 {
4574                   FileFormatI type;
4575                   try
4576                   {
4577                     type = new IdentifyFile().identify(file, protocol);
4578                   } catch (Exception ex)
4579                   {
4580                     type = null;
4581                   }
4582                   if (type != null && type.isStructureFile())
4583                   {
4584                     filesmatched.add(new Object[] { file, protocol, mtch });
4585                     continue;
4586                   }
4587                 }
4588                 // File wasn't named like one of the sequences or wasn't a PDB
4589                 // file.
4590                 filesnotmatched.add(file);
4591               }
4592             }
4593             int assocfiles = 0;
4594             if (filesmatched.size() > 0)
4595             {
4596               boolean autoAssociate = Cache
4597                       .getDefault("AUTOASSOCIATE_PDBANDSEQS", false);
4598               if (!autoAssociate)
4599               {
4600                 String msg = MessageManager.formatMessage(
4601                         "label.automatically_associate_structure_files_with_sequences_same_name",
4602                         new Object[]
4603                         { Integer.valueOf(filesmatched.size())
4604                                 .toString() });
4605                 String ttl = MessageManager.getString(
4606                         "label.automatically_associate_structure_files_by_name");
4607                 int choice = JvOptionPane.showConfirmDialog(thisaf, msg,
4608                         ttl, JvOptionPane.YES_NO_OPTION);
4609                 autoAssociate = choice == JvOptionPane.YES_OPTION;
4610               }
4611               if (autoAssociate)
4612               {
4613                 for (Object[] fm : filesmatched)
4614                 {
4615                   // try and associate
4616                   // TODO: may want to set a standard ID naming formalism for
4617                   // associating PDB files which have no IDs.
4618                   for (SequenceI toassoc : (SequenceI[]) fm[2])
4619                   {
4620                     PDBEntry pe = new AssociatePdbFileWithSeq()
4621                             .associatePdbWithSeq(fm[0].toString(),
4622                                     (DataSourceType) fm[1], toassoc, false,
4623                                     Desktop.instance);
4624                     if (pe != null)
4625                     {
4626                       System.err.println("Associated file : "
4627                               + (fm[0].toString()) + " with "
4628                               + toassoc.getDisplayId(true));
4629                       assocfiles++;
4630                     }
4631                   }
4632                   // TODO: do we need to update overview ? only if features are
4633                   // shown I guess
4634                   alignPanel.paintAlignment(true, false);
4635                 }
4636               }
4637               else
4638               {
4639                 /*
4640                  * add declined structures as sequences
4641                  */
4642                 for (Object[] o : filesmatched)
4643                 {
4644                   filesnotmatched.add(o[0]);
4645                 }
4646               }
4647             }
4648             if (filesnotmatched.size() > 0)
4649             {
4650               if (assocfiles > 0 && (Cache.getDefault(
4651                       "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false)
4652                       || JvOptionPane.showConfirmDialog(thisaf,
4653                               "<html>" + MessageManager.formatMessage(
4654                                       "label.ignore_unmatched_dropped_files_info",
4655                                       new Object[]
4656                                       { Integer.valueOf(
4657                                               filesnotmatched.size())
4658                                               .toString() })
4659                                       + "</html>",
4660                               MessageManager.getString(
4661                                       "label.ignore_unmatched_dropped_files"),
4662                               JvOptionPane.YES_NO_OPTION) == JvOptionPane.YES_OPTION))
4663               {
4664                 return;
4665               }
4666               for (Object fn : filesnotmatched)
4667               {
4668                 loadJalviewDataFile(fn, null, null, null);
4669               }
4670
4671             }
4672           } catch (Exception ex)
4673           {
4674             ex.printStackTrace();
4675           }
4676         }
4677       }).start();
4678     }
4679   }
4680
4681   /**
4682    * Attempt to load a "dropped" file or URL string, by testing in turn for
4683    * <ul>
4684    * <li>an Annotation file</li>
4685    * <li>a JNet file</li>
4686    * <li>a features file</li>
4687    * <li>else try to interpret as an alignment file</li>
4688    * </ul>
4689    * 
4690    * @param file
4691    *          either a filename or a URL string.
4692    */
4693   public void loadJalviewDataFile(Object file, DataSourceType sourceType,
4694           FileFormatI format, SequenceI assocSeq)
4695   {
4696     // BH 2018 was String file
4697     try
4698     {
4699       if (sourceType == null)
4700       {
4701         sourceType = FormatAdapter.checkProtocol(file);
4702       }
4703       // if the file isn't identified, or not positively identified as some
4704       // other filetype (PFAM is default unidentified alignment file type) then
4705       // try to parse as annotation.
4706       boolean isAnnotation = (format == null
4707               || FileFormat.Pfam.equals(format))
4708                       ? new AnnotationFile().annotateAlignmentView(viewport,
4709                               file, sourceType)
4710                       : false;
4711
4712       if (!isAnnotation)
4713       {
4714         // first see if its a T-COFFEE score file
4715         TCoffeeScoreFile tcf = null;
4716         try
4717         {
4718           tcf = new TCoffeeScoreFile(file, sourceType);
4719           if (tcf.isValid())
4720           {
4721             if (tcf.annotateAlignment(viewport.getAlignment(), true))
4722             {
4723               buildColourMenu();
4724               changeColour(
4725                       new TCoffeeColourScheme(viewport.getAlignment()));
4726               isAnnotation = true;
4727               setStatus(MessageManager.getString(
4728                       "label.successfully_pasted_tcoffee_scores_to_alignment"));
4729             }
4730             else
4731             {
4732               // some problem - if no warning its probable that the ID matching
4733               // process didn't work
4734               JvOptionPane.showMessageDialog(Desktop.desktop,
4735                       tcf.getWarningMessage() == null
4736                               ? MessageManager.getString(
4737                                       "label.check_file_matches_sequence_ids_alignment")
4738                               : tcf.getWarningMessage(),
4739                       MessageManager.getString(
4740                               "label.problem_reading_tcoffee_score_file"),
4741                       JvOptionPane.WARNING_MESSAGE);
4742             }
4743           }
4744           else
4745           {
4746             tcf = null;
4747           }
4748         } catch (Exception x)
4749         {
4750           Cache.log.debug(
4751                   "Exception when processing data source as T-COFFEE score file",
4752                   x);
4753           tcf = null;
4754         }
4755         if (tcf == null)
4756         {
4757           // try to see if its a JNet 'concise' style annotation file *before*
4758           // we
4759           // try to parse it as a features file
4760           if (format == null)
4761           {
4762             format = new IdentifyFile().identify(file, sourceType);
4763           }
4764           if (FileFormat.ScoreMatrix == format)
4765           {
4766             ScoreMatrixFile sm = new ScoreMatrixFile(
4767                     new FileParse(file, sourceType));
4768             sm.parse();
4769             // todo: i18n this message
4770             setStatus(MessageManager.formatMessage(
4771                     "label.successfully_loaded_matrix",
4772                     sm.getMatrixName()));
4773           }
4774           else if (FileFormat.Jnet.equals(format))
4775           {
4776             JPredFile predictions = new JPredFile(file, sourceType);
4777             new JnetAnnotationMaker();
4778             JnetAnnotationMaker.add_annotation(predictions,
4779                     viewport.getAlignment(), 0, false);
4780             viewport.getAlignment().setupJPredAlignment();
4781             isAnnotation = true;
4782           }
4783           // else if (IdentifyFile.FeaturesFile.equals(format))
4784           else if (FileFormat.Features.equals(format))
4785           {
4786             if (parseFeaturesFile(file, sourceType))
4787             {
4788               alignPanel.paintAlignment(true, true);
4789             }
4790           }
4791           else
4792           {
4793             new FileLoader().LoadFile(viewport, file, sourceType, format);
4794           }
4795         }
4796       }
4797       if (isAnnotation)
4798       {
4799
4800         alignPanel.adjustAnnotationHeight();
4801         viewport.updateSequenceIdColours();
4802         buildSortByAnnotationScoresMenu();
4803         alignPanel.paintAlignment(true, true);
4804       }
4805     } catch (Exception ex)
4806     {
4807       ex.printStackTrace();
4808     } catch (OutOfMemoryError oom)
4809     {
4810       try
4811       {
4812         System.gc();
4813       } catch (Exception x)
4814       {
4815       }
4816       new OOMWarning(
4817               "loading data "
4818                       + (sourceType != null
4819                               ? (sourceType == DataSourceType.PASTE
4820                                       ? "from clipboard."
4821                                       : "using " + sourceType + " from "
4822                                               + file)
4823                               : ".")
4824                       + (format != null
4825                               ? "(parsing as '" + format + "' file)"
4826                               : ""),
4827               oom, Desktop.desktop);
4828     }
4829   }
4830
4831   /**
4832    * Method invoked by the ChangeListener on the tabbed pane, in other words
4833    * when a different tabbed pane is selected by the user or programmatically.
4834    */
4835   @Override
4836   public void tabSelectionChanged(int index)
4837   {
4838     if (index > -1)
4839     {
4840       alignPanel = alignPanels.get(index);
4841       viewport = alignPanel.av;
4842       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
4843       setMenusFromViewport(viewport);
4844     }
4845
4846     /*
4847      * 'focus' any colour slider that is open to the selected viewport
4848      */
4849     if (viewport.getConservationSelected())
4850     {
4851       SliderPanel.setConservationSlider(alignPanel,
4852               viewport.getResidueShading(), alignPanel.getViewName());
4853     }
4854     else
4855     {
4856       SliderPanel.hideConservationSlider();
4857     }
4858     if (viewport.getAbovePIDThreshold())
4859     {
4860       SliderPanel.setPIDSliderSource(alignPanel,
4861               viewport.getResidueShading(), alignPanel.getViewName());
4862     }
4863     else
4864     {
4865       SliderPanel.hidePIDSlider();
4866     }
4867
4868     /*
4869      * If there is a frame linked to this one in a SplitPane, switch it to the
4870      * same view tab index. No infinite recursion of calls should happen, since
4871      * tabSelectionChanged() should not get invoked on setting the selected
4872      * index to an unchanged value. Guard against setting an invalid index
4873      * before the new view peer tab has been created.
4874      */
4875     final AlignViewportI peer = viewport.getCodingComplement();
4876     if (peer != null)
4877     {
4878       AlignFrame linkedAlignFrame = ((AlignViewport) peer)
4879               .getAlignPanel().alignFrame;
4880       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
4881       {
4882         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
4883       }
4884     }
4885   }
4886
4887   /**
4888    * On right mouse click on view tab, prompt for and set new view name.
4889    */
4890   @Override
4891   public void tabbedPane_mousePressed(MouseEvent e)
4892   {
4893     if (e.isPopupTrigger())
4894     {
4895       String msg = MessageManager.getString("label.enter_view_name");
4896       String ttl = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
4897       String reply = JvOptionPane.showInputDialog(msg, ttl);
4898
4899       if (reply != null)
4900       {
4901         viewport.setViewName(reply);
4902         // TODO warn if reply is in getExistingViewNames()?
4903         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
4904       }
4905     }
4906   }
4907
4908   public AlignViewport getCurrentView()
4909   {
4910     return viewport;
4911   }
4912
4913   /**
4914    * Open the dialog for regex description parsing.
4915    */
4916   @Override
4917   protected void extractScores_actionPerformed(ActionEvent e)
4918   {
4919     ParseProperties pp = new jalview.analysis.ParseProperties(
4920             viewport.getAlignment());
4921     // TODO: verify regex and introduce GUI dialog for version 2.5
4922     // if (pp.getScoresFromDescription("col", "score column ",
4923     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
4924     // true)>0)
4925     if (pp.getScoresFromDescription("description column",
4926             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
4927     {
4928       buildSortByAnnotationScoresMenu();
4929     }
4930   }
4931
4932   /*
4933    * (non-Javadoc)
4934    * 
4935    * @see
4936    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
4937    * )
4938    */
4939   @Override
4940   protected void showDbRefs_actionPerformed(ActionEvent e)
4941   {
4942     viewport.setShowDBRefs(showDbRefsMenuitem.isSelected());
4943   }
4944
4945   /*
4946    * (non-Javadoc)
4947    * 
4948    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
4949    * ActionEvent)
4950    */
4951   @Override
4952   protected void showNpFeats_actionPerformed(ActionEvent e)
4953   {
4954     viewport.setShowNPFeats(showNpFeatsMenuitem.isSelected());
4955   }
4956
4957   /**
4958    * find the viewport amongst the tabs in this alignment frame and close that
4959    * tab
4960    * 
4961    * @param av
4962    */
4963   public boolean closeView(AlignViewportI av)
4964   {
4965     if (viewport == av)
4966     {
4967       this.closeMenuItem_actionPerformed(false);
4968       return true;
4969     }
4970     Component[] comp = tabbedPane.getComponents();
4971     for (int i = 0; comp != null && i < comp.length; i++)
4972     {
4973       if (comp[i] instanceof AlignmentPanel)
4974       {
4975         if (((AlignmentPanel) comp[i]).av == av)
4976         {
4977           // close the view.
4978           closeView((AlignmentPanel) comp[i]);
4979           return true;
4980         }
4981       }
4982     }
4983     return false;
4984   }
4985
4986   protected void build_fetchdbmenu(JMenu webService)
4987   {
4988     // Temporary hack - DBRef Fetcher always top level ws entry.
4989     // TODO We probably want to store a sequence database checklist in
4990     // preferences and have checkboxes.. rather than individual sources selected
4991     // here
4992     final JMenu rfetch = new JMenu(
4993             MessageManager.getString("action.fetch_db_references"));
4994     rfetch.setToolTipText(MessageManager.getString(
4995             "label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
4996     webService.add(rfetch);
4997
4998     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
4999             MessageManager.getString("option.trim_retrieved_seqs"));
5000     trimrs.setToolTipText(
5001             MessageManager.getString("label.trim_retrieved_sequences"));
5002     trimrs.setSelected(
5003             Cache.getDefault(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES, true));
5004     trimrs.addActionListener(new ActionListener()
5005     {
5006       @Override
5007       public void actionPerformed(ActionEvent e)
5008       {
5009         trimrs.setSelected(trimrs.isSelected());
5010         Cache.setProperty(DBRefFetcher.TRIM_RETRIEVED_SEQUENCES,
5011                 Boolean.valueOf(trimrs.isSelected()).toString());
5012       };
5013     });
5014     rfetch.add(trimrs);
5015     JMenuItem fetchr = new JMenuItem(
5016             MessageManager.getString("label.standard_databases"));
5017     fetchr.setToolTipText(
5018             MessageManager.getString("label.fetch_embl_uniprot"));
5019     fetchr.addActionListener(new ActionListener()
5020     {
5021
5022       @Override
5023       public void actionPerformed(ActionEvent e)
5024       {
5025         new Thread(new Runnable()
5026         {
5027           @Override
5028           public void run()
5029           {
5030             boolean isNucleotide = alignPanel.alignFrame.getViewport()
5031                     .getAlignment().isNucleotide();
5032             DBRefFetcher dbRefFetcher = new DBRefFetcher(
5033                     alignPanel.av.getSequenceSelection(),
5034                     alignPanel.alignFrame, null,
5035                     alignPanel.alignFrame.featureSettings, isNucleotide);
5036             dbRefFetcher.addListener(new FetchFinishedListenerI()
5037             {
5038               @Override
5039               public void finished()
5040               {
5041                 AlignFrame.this.setMenusForViewport();
5042               }
5043             });
5044             dbRefFetcher.fetchDBRefs(false);
5045           }
5046         }).start();
5047
5048       }
5049
5050     });
5051     rfetch.add(fetchr);
5052     new Thread(new Runnable()
5053     {
5054       @Override
5055       public void run()
5056       {
5057         final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
5058                 .getSequenceFetcherSingleton();
5059         javax.swing.SwingUtilities.invokeLater(new Runnable()
5060         {
5061           @Override
5062           public void run()
5063           {
5064             String[] dbclasses = sf.getNonAlignmentSources();
5065             List<DbSourceProxy> otherdb;
5066             JMenu dfetch = new JMenu();
5067             JMenu ifetch = new JMenu();
5068             JMenuItem fetchr = null;
5069             int comp = 0, icomp = 0, mcomp = 15;
5070             String mname = null;
5071             int dbi = 0;
5072             for (String dbclass : dbclasses)
5073             {
5074               otherdb = sf.getSourceProxy(dbclass);
5075               // add a single entry for this class, or submenu allowing 'fetch
5076               // all' or pick one
5077               if (otherdb == null || otherdb.size() < 1)
5078               {
5079                 continue;
5080               }
5081               if (mname == null)
5082               {
5083                 mname = "From " + dbclass;
5084               }
5085               if (otherdb.size() == 1)
5086               {
5087                 final DbSourceProxy[] dassource = otherdb
5088                         .toArray(new DbSourceProxy[0]);
5089                 DbSourceProxy src = otherdb.get(0);
5090                 fetchr = new JMenuItem(src.getDbSource());
5091                 fetchr.addActionListener(new ActionListener()
5092                 {
5093
5094                   @Override
5095                   public void actionPerformed(ActionEvent e)
5096                   {
5097                     new Thread(new Runnable()
5098                     {
5099
5100                       @Override
5101                       public void run()
5102                       {
5103                         boolean isNucleotide = alignPanel.alignFrame
5104                                 .getViewport().getAlignment()
5105                                 .isNucleotide();
5106                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5107                                 alignPanel.av.getSequenceSelection(),
5108                                 alignPanel.alignFrame, dassource,
5109                                 alignPanel.alignFrame.featureSettings,
5110                                 isNucleotide);
5111                         dbRefFetcher
5112                                 .addListener(new FetchFinishedListenerI()
5113                                 {
5114                                   @Override
5115                                   public void finished()
5116                                   {
5117                                     AlignFrame.this.setMenusForViewport();
5118                                   }
5119                                 });
5120                         dbRefFetcher.fetchDBRefs(false);
5121                       }
5122                     }).start();
5123                   }
5124
5125                 });
5126                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5127                         MessageManager.formatMessage(
5128                                 "label.fetch_retrieve_from", new Object[]
5129                                 { src.getDbName() })));
5130                 dfetch.add(fetchr);
5131                 comp++;
5132               }
5133               else
5134               {
5135                 final DbSourceProxy[] dassource = otherdb
5136                         .toArray(new DbSourceProxy[0]);
5137                 // fetch all entry
5138                 DbSourceProxy src = otherdb.get(0);
5139                 fetchr = new JMenuItem(MessageManager
5140                         .formatMessage("label.fetch_all_param", new Object[]
5141                         { src.getDbSource() }));
5142                 fetchr.addActionListener(new ActionListener()
5143                 {
5144                   @Override
5145                   public void actionPerformed(ActionEvent e)
5146                   {
5147                     new Thread(new Runnable()
5148                     {
5149
5150                       @Override
5151                       public void run()
5152                       {
5153                         boolean isNucleotide = alignPanel.alignFrame
5154                                 .getViewport().getAlignment()
5155                                 .isNucleotide();
5156                         DBRefFetcher dbRefFetcher = new DBRefFetcher(
5157                                 alignPanel.av.getSequenceSelection(),
5158                                 alignPanel.alignFrame, dassource,
5159                                 alignPanel.alignFrame.featureSettings,
5160                                 isNucleotide);
5161                         dbRefFetcher
5162                                 .addListener(new FetchFinishedListenerI()
5163                                 {
5164                                   @Override
5165                                   public void finished()
5166                                   {
5167                                     AlignFrame.this.setMenusForViewport();
5168                                   }
5169                                 });
5170                         dbRefFetcher.fetchDBRefs(false);
5171                       }
5172                     }).start();
5173                   }
5174                 });
5175
5176                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true,
5177                         MessageManager.formatMessage(
5178                                 "label.fetch_retrieve_from_all_sources",
5179                                 new Object[]
5180                                 { Integer.valueOf(otherdb.size())
5181                                         .toString(),
5182                                     src.getDbSource(), src.getDbName() })));
5183                 dfetch.add(fetchr);
5184                 comp++;
5185                 // and then build the rest of the individual menus
5186                 ifetch = new JMenu(MessageManager.formatMessage(
5187                         "label.source_from_db_source", new Object[]
5188                         { src.getDbSource() }));
5189                 icomp = 0;
5190                 String imname = null;
5191                 int i = 0;
5192                 for (DbSourceProxy sproxy : otherdb)
5193                 {
5194                   String dbname = sproxy.getDbName();
5195                   String sname = dbname.length() > 5
5196                           ? dbname.substring(0, 5) + "..."
5197                           : dbname;
5198                   String msname = dbname.length() > 10
5199                           ? dbname.substring(0, 10) + "..."
5200                           : dbname;
5201                   if (imname == null)
5202                   {
5203                     imname = MessageManager
5204                             .formatMessage("label.from_msname", new Object[]
5205                             { sname });
5206                   }
5207                   fetchr = new JMenuItem(msname);
5208                   final DbSourceProxy[] dassrc = { sproxy };
5209                   fetchr.addActionListener(new ActionListener()
5210                   {
5211
5212                     @Override
5213                     public void actionPerformed(ActionEvent e)
5214                     {
5215                       new Thread(new Runnable()
5216                       {
5217
5218                         @Override
5219                         public void run()
5220                         {
5221                           boolean isNucleotide = alignPanel.alignFrame
5222                                   .getViewport().getAlignment()
5223                                   .isNucleotide();
5224                           DBRefFetcher dbRefFetcher = new DBRefFetcher(
5225                                   alignPanel.av.getSequenceSelection(),
5226                                   alignPanel.alignFrame, dassrc,
5227                                   alignPanel.alignFrame.featureSettings,
5228                                   isNucleotide);
5229                           dbRefFetcher
5230                                   .addListener(new FetchFinishedListenerI()
5231                                   {
5232                                     @Override
5233                                     public void finished()
5234                                     {
5235                                       AlignFrame.this.setMenusForViewport();
5236                                     }
5237                                   });
5238                           dbRefFetcher.fetchDBRefs(false);
5239                         }
5240                       }).start();
5241                     }
5242
5243                   });
5244                   fetchr.setToolTipText(
5245                           "<html>" + MessageManager.formatMessage(
5246                                   "label.fetch_retrieve_from", new Object[]
5247                                   { dbname }));
5248                   ifetch.add(fetchr);
5249                   ++i;
5250                   if (++icomp >= mcomp || i == (otherdb.size()))
5251                   {
5252                     ifetch.setText(MessageManager.formatMessage(
5253                             "label.source_to_target", imname, sname));
5254                     dfetch.add(ifetch);
5255                     ifetch = new JMenu();
5256                     imname = null;
5257                     icomp = 0;
5258                     comp++;
5259                   }
5260                 }
5261               }
5262               ++dbi;
5263               if (comp >= mcomp || dbi >= (dbclasses.length))
5264               {
5265                 dfetch.setText(MessageManager.formatMessage(
5266                         "label.source_to_target", mname, dbclass));
5267                 rfetch.add(dfetch);
5268                 dfetch = new JMenu();
5269                 mname = null;
5270                 comp = 0;
5271               }
5272             }
5273           }
5274         });
5275       }
5276     }).start();
5277
5278   }
5279
5280   /**
5281    * Left justify the whole alignment.
5282    */
5283   @Override
5284   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5285   {
5286     AlignmentI al = viewport.getAlignment();
5287     al.justify(false);
5288     viewport.firePropertyChange("alignment", null, al);
5289   }
5290
5291   /**
5292    * Right justify the whole alignment.
5293    */
5294   @Override
5295   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5296   {
5297     AlignmentI al = viewport.getAlignment();
5298     al.justify(true);
5299     viewport.firePropertyChange("alignment", null, al);
5300   }
5301
5302   @Override
5303   public void setShowSeqFeatures(boolean b)
5304   {
5305     showSeqFeatures.setSelected(b);
5306     viewport.setShowSequenceFeatures(b);
5307   }
5308
5309   /*
5310    * (non-Javadoc)
5311    * 
5312    * @see
5313    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5314    * awt.event.ActionEvent)
5315    */
5316   @Override
5317   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5318   {
5319     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5320     alignPanel.paintAlignment(false, false);
5321   }
5322
5323   /*
5324    * (non-Javadoc)
5325    * 
5326    * @see
5327    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5328    * .ActionEvent)
5329    */
5330   @Override
5331   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5332   {
5333     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5334     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5335
5336   }
5337
5338   /*
5339    * (non-Javadoc)
5340    * 
5341    * @see
5342    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5343    * .event.ActionEvent)
5344    */
5345   @Override
5346   protected void showGroupConservation_actionPerformed(ActionEvent e)
5347   {
5348     viewport.setShowGroupConservation(showGroupConservation.getState());
5349     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5350   }
5351
5352   /*
5353    * (non-Javadoc)
5354    * 
5355    * @see
5356    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5357    * .event.ActionEvent)
5358    */
5359   @Override
5360   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5361   {
5362     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5363     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5364   }
5365
5366   /*
5367    * (non-Javadoc)
5368    * 
5369    * @see
5370    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5371    * .event.ActionEvent)
5372    */
5373   @Override
5374   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5375   {
5376     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5377     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5378   }
5379
5380   @Override
5381   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5382   {
5383     showSequenceLogo.setState(true);
5384     viewport.setShowSequenceLogo(true);
5385     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5386     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5387   }
5388
5389   @Override
5390   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5391   {
5392     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5393   }
5394
5395   /*
5396    * (non-Javadoc)
5397    * 
5398    * @see
5399    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5400    * .event.ActionEvent)
5401    */
5402   @Override
5403   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5404   {
5405     if (avc.makeGroupsFromSelection())
5406     {
5407       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5408       alignPanel.updateAnnotation();
5409       alignPanel.paintAlignment(true,
5410               viewport.needToUpdateStructureViews());
5411     }
5412   }
5413
5414   public void clearAlignmentSeqRep()
5415   {
5416     // TODO refactor alignmentseqrep to controller
5417     if (viewport.getAlignment().hasSeqrep())
5418     {
5419       viewport.getAlignment().setSeqrep(null);
5420       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5421       alignPanel.updateAnnotation();
5422       alignPanel.paintAlignment(true, true);
5423     }
5424   }
5425
5426   @Override
5427   protected void createGroup_actionPerformed(ActionEvent e)
5428   {
5429     if (avc.createGroup())
5430     {
5431       if (applyAutoAnnotationSettings.isSelected())
5432       {
5433         alignPanel.updateAnnotation(true, false);
5434       }
5435       alignPanel.alignmentChanged();
5436     }
5437   }
5438
5439   @Override
5440   protected void unGroup_actionPerformed(ActionEvent e)
5441   {
5442     if (avc.unGroup())
5443     {
5444       alignPanel.alignmentChanged();
5445     }
5446   }
5447
5448   /**
5449    * make the given alignmentPanel the currently selected tab
5450    * 
5451    * @param alignmentPanel
5452    */
5453   public void setDisplayedView(AlignmentPanel alignmentPanel)
5454   {
5455     if (!viewport.getSequenceSetId()
5456             .equals(alignmentPanel.av.getSequenceSetId()))
5457     {
5458       throw new Error(MessageManager.getString(
5459               "error.implementation_error_cannot_show_view_alignment_frame"));
5460     }
5461     if (tabbedPane != null && tabbedPane.getTabCount() > 0 && alignPanels
5462             .indexOf(alignmentPanel) != tabbedPane.getSelectedIndex())
5463     {
5464       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5465     }
5466   }
5467
5468   /**
5469    * Action on selection of menu options to Show or Hide annotations.
5470    * 
5471    * @param visible
5472    * @param forSequences
5473    *          update sequence-related annotations
5474    * @param forAlignment
5475    *          update non-sequence-related annotations
5476    */
5477   @Override
5478   protected void setAnnotationsVisibility(boolean visible,
5479           boolean forSequences, boolean forAlignment)
5480   {
5481     AlignmentAnnotation[] anns = alignPanel.getAlignment()
5482             .getAlignmentAnnotation();
5483     if (anns == null)
5484     {
5485       return;
5486     }
5487     for (AlignmentAnnotation aa : anns)
5488     {
5489       /*
5490        * don't display non-positional annotations on an alignment
5491        */
5492       if (aa.annotations == null)
5493       {
5494         continue;
5495       }
5496       boolean apply = (aa.sequenceRef == null && forAlignment)
5497               || (aa.sequenceRef != null && forSequences);
5498       if (apply)
5499       {
5500         aa.visible = visible;
5501       }
5502     }
5503     alignPanel.validateAnnotationDimensions(true);
5504     alignPanel.alignmentChanged();
5505   }
5506
5507   /**
5508    * Store selected annotation sort order for the view and repaint.
5509    */
5510   @Override
5511   protected void sortAnnotations_actionPerformed()
5512   {
5513     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5514     this.alignPanel.av
5515             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5516     alignPanel.paintAlignment(false, false);
5517   }
5518
5519   /**
5520    * 
5521    * @return alignment panels in this alignment frame
5522    */
5523   public List<? extends AlignmentViewPanel> getAlignPanels()
5524   {
5525     // alignPanels is never null
5526     // return alignPanels == null ? Arrays.asList(alignPanel) : alignPanels;
5527     return alignPanels;
5528   }
5529
5530   /**
5531    * Open a new alignment window, with the cDNA associated with this (protein)
5532    * alignment, aligned as is the protein.
5533    */
5534   protected void viewAsCdna_actionPerformed()
5535   {
5536     // TODO no longer a menu action - refactor as required
5537     final AlignmentI alignment = getViewport().getAlignment();
5538     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5539     if (mappings == null)
5540     {
5541       return;
5542     }
5543     List<SequenceI> cdnaSeqs = new ArrayList<>();
5544     for (SequenceI aaSeq : alignment.getSequences())
5545     {
5546       for (AlignedCodonFrame acf : mappings)
5547       {
5548         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5549         if (dnaSeq != null)
5550         {
5551           /*
5552            * There is a cDNA mapping for this protein sequence - add to new
5553            * alignment. It will share the same dataset sequence as other mapped
5554            * cDNA (no new mappings need to be created).
5555            */
5556           final Sequence newSeq = new Sequence(dnaSeq);
5557           newSeq.setDatasetSequence(dnaSeq);
5558           cdnaSeqs.add(newSeq);
5559         }
5560       }
5561     }
5562     if (cdnaSeqs.size() == 0)
5563     {
5564       // show a warning dialog no mapped cDNA
5565       return;
5566     }
5567     AlignmentI cdna = new Alignment(
5568             cdnaSeqs.toArray(new SequenceI[cdnaSeqs.size()]));
5569     GAlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5570             AlignFrame.DEFAULT_HEIGHT);
5571     cdna.alignAs(alignment);
5572     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5573             + this.title;
5574     Desktop.addInternalFrame(alignFrame, newtitle, AlignFrame.DEFAULT_WIDTH,
5575             AlignFrame.DEFAULT_HEIGHT);
5576   }
5577
5578   /**
5579    * Set visibility of dna/protein complement view (available when shown in a
5580    * split frame).
5581    * 
5582    * @param show
5583    */
5584   @Override
5585   protected void showComplement_actionPerformed(boolean show)
5586   {
5587     SplitContainerI sf = getSplitViewContainer();
5588     if (sf != null)
5589     {
5590       sf.setComplementVisible(this, show);
5591     }
5592   }
5593
5594   /**
5595    * Generate the reverse (optionally complemented) of the selected sequences,
5596    * and add them to the alignment
5597    */
5598   @Override
5599   protected void showReverse_actionPerformed(boolean complement)
5600   {
5601     AlignmentI al = null;
5602     try
5603     {
5604       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
5605       al = dna.reverseCdna(complement);
5606       viewport.addAlignment(al, "");
5607       addHistoryItem(new EditCommand(
5608               MessageManager.getString("label.add_sequences"), Action.PASTE,
5609               al.getSequencesArray(), 0, al.getWidth(),
5610               viewport.getAlignment()));
5611     } catch (Exception ex)
5612     {
5613       System.err.println(ex.getMessage());
5614       return;
5615     }
5616   }
5617
5618   /**
5619    * Try to run a script in the Groovy console, having first ensured that this
5620    * AlignFrame is set as currentAlignFrame in Desktop, to allow the script to
5621    * be targeted at this alignment.
5622    */
5623   @Override
5624   protected void runGroovy_actionPerformed()
5625   {
5626     Jalview.setCurrentAlignFrame(this);
5627     groovy.ui.Console console = Desktop.getGroovyConsole();
5628     if (console != null)
5629     {
5630       try
5631       {
5632         console.runScript();
5633       } catch (Exception ex)
5634       {
5635         System.err.println((ex.toString()));
5636         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
5637                 MessageManager.getString("label.couldnt_run_groovy_script"),
5638                 MessageManager.getString("label.groovy_support_failed"),
5639                 JvOptionPane.ERROR_MESSAGE);
5640       }
5641     }
5642     else
5643     {
5644       System.err.println("Can't run Groovy script as console not found");
5645     }
5646   }
5647
5648   /**
5649    * Hides columns containing (or not containing) a specified feature, provided
5650    * that would not leave all columns hidden
5651    * 
5652    * @param featureType
5653    * @param columnsContaining
5654    * @return
5655    */
5656   public boolean hideFeatureColumns(String featureType,
5657           boolean columnsContaining)
5658   {
5659     boolean notForHiding = avc.markColumnsContainingFeatures(
5660             columnsContaining, false, false, featureType);
5661     if (notForHiding)
5662     {
5663       if (avc.markColumnsContainingFeatures(!columnsContaining, false,
5664               false, featureType))
5665       {
5666         getViewport().hideSelectedColumns();
5667         return true;
5668       }
5669     }
5670     return false;
5671   }
5672
5673   @Override
5674   protected void selectHighlightedColumns_actionPerformed(
5675           ActionEvent actionEvent)
5676   {
5677     // include key modifier check in case user selects from menu
5678     avc.markHighlightedColumns(
5679             (actionEvent.getModifiers() & ActionEvent.ALT_MASK) != 0, true,
5680             (actionEvent.getModifiers() & (ActionEvent.META_MASK
5681                     | ActionEvent.CTRL_MASK)) != 0);
5682   }
5683
5684   /**
5685    * Rebuilds the Colour menu, including any user-defined colours which have
5686    * been loaded either on startup or during the session
5687    */
5688   public void buildColourMenu()
5689   {
5690     colourMenu.removeAll();
5691
5692     colourMenu.add(applyToAllGroups);
5693     colourMenu.add(textColour);
5694     colourMenu.addSeparator();
5695
5696     ButtonGroup bg = ColourMenuHelper.addMenuItems(colourMenu, this,
5697             viewport.getAlignment(), false);
5698
5699     colourMenu.add(annotationColour);
5700     bg.add(annotationColour);
5701     colourMenu.addSeparator();
5702     colourMenu.add(conservationMenuItem);
5703     colourMenu.add(modifyConservation);
5704     colourMenu.add(abovePIDThreshold);
5705     colourMenu.add(modifyPID);
5706
5707     ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
5708     ColourMenuHelper.setColourSelected(colourMenu, colourScheme);
5709   }
5710
5711   /**
5712    * Open a dialog (if not already open) that allows the user to select and
5713    * calculate PCA or Tree analysis
5714    */
5715   protected void openTreePcaDialog()
5716   {
5717     if (alignPanel.getCalculationDialog() == null)
5718     {
5719       new CalculationChooser(AlignFrame.this);
5720     }
5721   }
5722
5723   @Override
5724   protected void loadVcf_actionPerformed()
5725   {
5726     JalviewFileChooser chooser = new JalviewFileChooser(
5727             Cache.getProperty("LAST_DIRECTORY"));
5728     chooser.setFileView(new JalviewFileView());
5729     chooser.setDialogTitle(MessageManager.getString("label.load_vcf_file"));
5730     chooser.setToolTipText(MessageManager.getString("label.load_vcf_file"));
5731     final AlignFrame us = this;
5732     chooser.setResponseHandler(0, new Runnable()
5733     {
5734       @Override
5735       public void run()
5736       {
5737         String choice = chooser.getSelectedFile().getPath();
5738         Cache.setProperty("LAST_DIRECTORY", choice);
5739         SequenceI[] seqs = viewport.getAlignment().getSequencesArray();
5740         new VCFLoader(choice).loadVCF(seqs, us);
5741       };
5742     });
5743     chooser.showOpenDialog(null);
5744
5745   }
5746
5747 }
5748
5749 class PrintThread extends Thread
5750 {
5751   AlignmentPanel ap;
5752
5753   public PrintThread(AlignmentPanel ap)
5754   {
5755     this.ap = ap;
5756   }
5757
5758   static PageFormat pf;
5759
5760   @Override
5761   public void run()
5762   {
5763     PrinterJob printJob = PrinterJob.getPrinterJob();
5764
5765     if (pf != null)
5766     {
5767       printJob.setPrintable(ap, pf);
5768     }
5769     else
5770     {
5771       printJob.setPrintable(ap);
5772     }
5773
5774     if (printJob.printDialog())
5775     {
5776       try
5777       {
5778         printJob.print();
5779       } catch (Exception PrintException)
5780       {
5781         PrintException.printStackTrace();
5782       }
5783     }
5784   }
5785 }