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