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