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