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