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