JAL-2054 Renamed getStartEnd in AlignFrame to getVisibleStartAndEndIndex, and refacto...
[jalview.git] / src / jalview / gui / AlignFrame.java
index c93b84b..cb769bb 100644 (file)
@@ -32,6 +32,7 @@ import jalview.api.AlignViewControllerI;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureSettingsControllerI;
+import jalview.api.FeatureSettingsModelI;
 import jalview.api.SplitContainerI;
 import jalview.api.ViewStyleI;
 import jalview.api.analysis.ScoreModelI;
@@ -53,6 +54,7 @@ import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentOrder;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.ColumnSelection;
+import jalview.datamodel.DBRefSource;
 import jalview.datamodel.HiddenSequences;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SeqCigar;
@@ -94,6 +96,9 @@ import jalview.schemes.ZappoColourScheme;
 import jalview.structure.StructureSelectionManager;
 import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
+import jalview.ws.DBRefFetcher;
+import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
+import jalview.ws.SequenceFetcher;
 import jalview.ws.jws1.Discoverer;
 import jalview.ws.jws2.Jws2Discoverer;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
@@ -962,7 +967,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   @Override
   public void fetchSequence_actionPerformed(ActionEvent e)
   {
-    new SequenceFetcher(this);
+    new jalview.gui.SequenceFetcher(this);
   }
 
   @Override
@@ -1271,13 +1276,11 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     AlignmentI alignmentToExport = null;
     AlignExportSettingI settings = exportSettings;
     String[] omitHidden = null;
-    int[] alignmentStartEnd = new int[2];
 
     HiddenSequences hiddenSeqs = viewport.getAlignment()
             .getHiddenSequences();
 
     alignmentToExport = viewport.getAlignment();
-    alignmentStartEnd = new int[] { 0, alignmentToExport.getWidth() - 1 };
 
     boolean hasHiddenSeqs = hiddenSeqs.getSize() > 0;
     if (settings == null)
@@ -1292,6 +1295,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       omitHidden = viewport.getViewAsString(false);
     }
 
+    int[] alignmentStartEnd = new int[2];
     if (hasHiddenSeqs && settings.isExportHiddenSequences())
     {
       alignmentToExport = hiddenSeqs.getFullAlignment();
@@ -1299,7 +1303,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     else
     {
       alignmentToExport = viewport.getAlignment();
-      alignmentStartEnd = getStartEnd(alignmentStartEnd, viewport
+      alignmentStartEnd = viewport.getAlignment()
+              .getVisibleStartAndEndIndex(
+                      viewport
               .getColumnSelection().getHiddenColumns());
     }
     AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
@@ -1307,55 +1313,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     return ed;
   }
 
-  public static int[] getStartEnd(int[] aligmentStartEnd,
-          List<int[]> hiddenCols)
-  {
-    int startPos = aligmentStartEnd[0];
-    int endPos = aligmentStartEnd[1];
-
-    int[] lowestRange = new int[] { -1, -1 };
-    int[] higestRange = new int[] { -1, -1 };
-
-    for (int[] hiddenCol : hiddenCols)
-    {
-      lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
-      higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
-    }
-
-    if (lowestRange[0] == -1 && lowestRange[1] == -1)
-    {
-      startPos = aligmentStartEnd[0];
-    }
-    else
-    {
-      startPos = lowestRange[1] + 1;
-    }
-
-    if (higestRange[0] == -1 && higestRange[1] == -1)
-    {
-      endPos = aligmentStartEnd[1];
-    }
-    else
-    {
-      endPos = higestRange[0] - 1;
-    }
-
-    // System.out.println("Export range : " + startPos + " - " + endPos);
-    return new int[] { startPos, endPos };
-  }
-
-  public static void main(String[] args)
-  {
-    ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
-    hiddenCols.add(new int[] { 0, 0 });
-    hiddenCols.add(new int[] { 6, 9 });
-    hiddenCols.add(new int[] { 11, 12 });
-    hiddenCols.add(new int[] { 33, 33 });
-    hiddenCols.add(new int[] { 50, 50 });
-
-    int[] x = getStartEnd(new int[] { 0, 50 }, hiddenCols);
-    // System.out.println("Export range : " + x[0] + " - " + x[1]);
-  }
 
   /**
    * DOCUMENT ME!
@@ -4717,30 +4674,21 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                 new Object[] { source }), sttime);
         try
         {
-          /*
-           * 'peer' sequences are any to add to this alignment, for example
-           * alternative protein products for my protein's gene
-           */
-          List<SequenceI> addedPeers = new ArrayList<SequenceI>();
-          AlignmentI alignment = AlignFrame.this.getViewport().getAlignment();
-          Alignment xrefs = CrossRef.findXrefSequences(sel, dna, source,
-                  alignment, addedPeers);
+          AlignmentI alignment = AlignFrame.this.getViewport()
+                  .getAlignment();
+          AlignmentI xrefs = CrossRef.findXrefSequences(sel, dna, source,
+                  alignment);
           if (xrefs != null)
           {
-            Alignment al = makeCrossReferencesAlignment(
-                    alignment.getDataset(), xrefs);
-
             /*
-             * Copy dna-to-protein mappings to new alignment
+             * get display scheme (if any) to apply to features
              */
-            // TODO 1: no mappings are set up for EMBL product
-            // TODO 2: if they were, should add them to protein alignment, not
-            // dna
-            // List<AlignedCodonFrame> cf = xrefs.getCodonFrames();
-            // for (AlignedCodonFrame acf : cf)
-            // {
-            // al.addCodonFrame(acf);
-            // }
+            FeatureSettingsModelI featureColourScheme = new SequenceFetcher()
+                    .getFeatureColourScheme(source);
+
+            AlignmentI al = makeCrossReferencesAlignment(
+                    alignment.getDataset(), xrefs);
+
             AlignFrame newFrame = new AlignFrame(al, DEFAULT_WIDTH,
                     DEFAULT_HEIGHT);
             String newtitle = String.format("%s %s %s",
@@ -4749,136 +4697,184 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                             .getString("label.for"), getTitle());
             newFrame.setTitle(newtitle);
 
-            boolean asSplitFrame = Cache.getDefault(
-                    Preferences.ENABLE_SPLIT_FRAME, true);
-            if (asSplitFrame)
+            if (!Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
             {
               /*
-               * Make a copy of this alignment (sharing the same dataset
-               * sequences). If we are DNA, drop introns and update mappings
+               * split frame display is turned off in preferences file
                */
-              AlignmentI copyAlignment = null;
-              final SequenceI[] sequenceSelection = AlignFrame.this.viewport
-                      .getSequenceSelection();
-              List<AlignedCodonFrame> cf = xrefs.getCodonFrames();
-              if (dna)
-              {
-                copyAlignment = AlignmentUtils.makeCdsAlignment(
-                        sequenceSelection, cf);
-                al.getCodonFrames().clear();
-                al.getCodonFrames().addAll(cf);
-              }
-              else
+              Desktop.addInternalFrame(newFrame, newtitle, DEFAULT_WIDTH,
+                      DEFAULT_HEIGHT);
+              return; // via finally clause
+            }
+
+            /*
+             * Make a copy of this alignment (sharing the same dataset
+             * sequences). If we are DNA, drop introns and update mappings
+             */
+            AlignmentI copyAlignment = null;
+            final SequenceI[] sequenceSelection = AlignFrame.this.viewport
+                    .getSequenceSelection();
+            List<AlignedCodonFrame> cf = xrefs.getCodonFrames();
+            boolean copyAlignmentIsAligned = false;
+            if (dna)
+            {
+              copyAlignment = AlignmentUtils.makeCdsAlignment(
+                      sequenceSelection, cf, alignment);
+              if (copyAlignment.getHeight() == 0)
               {
-                copyAlignment = new Alignment(new Alignment(
-                        sequenceSelection));
-                copyAlignment.getCodonFrames().addAll(cf);
+                System.err.println("Failed to make CDS alignment");
               }
-              StructureSelectionManager ssm = StructureSelectionManager
-                      .getStructureSelectionManager(Desktop.instance);
-              ssm.registerMappings(cf);
+              al.getCodonFrames().clear();
+              al.getCodonFrames().addAll(copyAlignment.getCodonFrames());
 
               /*
-               * add in any extra 'peer' sequences discovered
-               * (e.g. alternative protein products)
+               * pending getting Embl transcripts to 'align', 
+               * we are only doing this for Ensembl
                */
-              for (SequenceI peer : addedPeers)
+              // TODO proper criteria for 'can align as cdna'
+              if (DBRefSource.ENSEMBL.equalsIgnoreCase(source)
+                      || AlignmentUtils.looksLikeEnsembl(alignment))
               {
-                copyAlignment.addSequence(peer);
+                copyAlignment.alignAs(alignment);
+                copyAlignmentIsAligned = true;
               }
+            }
+            else
+            {
+              copyAlignment = AlignmentUtils.makeCopyAlignment(
+                      sequenceSelection, xrefs.getSequencesArray());
+              copyAlignment.getCodonFrames().addAll(cf);
+            }
+            copyAlignment.setGapCharacter(AlignFrame.this.viewport
+                    .getGapCharacter());
 
-              /*
-               * align protein to dna
-               */
-              // TODO needs debugging
-              // if (dna)
-              // {
-              // al.alignAs(copyAlignment);
-              // }
-              // else
-              // {
-              // copyAlignment.alignAs(al);
-              // }
-
-              AlignFrame copyThis = new AlignFrame(copyAlignment,
-                      AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
-              copyThis.setTitle(AlignFrame.this.getTitle());
+            StructureSelectionManager ssm = StructureSelectionManager
+                    .getStructureSelectionManager(Desktop.instance);
+            ssm.registerMappings(cf);
 
-              boolean showSequenceFeatures = viewport
-                      .isShowSequenceFeatures();
-              newFrame.setShowSeqFeatures(showSequenceFeatures);
-              copyThis.setShowSeqFeatures(showSequenceFeatures);
-              FeatureRenderer myFeatureStyling = alignPanel.getSeqPanel().seqCanvas
-                      .getFeatureRenderer();
-              /*
-               * copy feature rendering settings to split frame
-               */
-              newFrame.alignPanel.getSeqPanel().seqCanvas
-                      .getFeatureRenderer().transferSettings(
-                              myFeatureStyling);
-              copyThis.alignPanel.getSeqPanel().seqCanvas
-                      .getFeatureRenderer().transferSettings(
-                              myFeatureStyling);
-              SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
-                      dna ? newFrame : copyThis);
-              newFrame.setVisible(true);
-              copyThis.setVisible(true);
-              String linkedTitle = MessageManager
-                      .getString("label.linked_view_title");
-              Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
-              sf.adjustDivider();
+            if (copyAlignment.getHeight() <= 0)
+            {
+              System.err.println("No Sequences generated for xRef type "
+                      + source);
+              return;
+            }
+            /*
+             * align protein to dna
+             */
+            if (dna && copyAlignmentIsAligned)
+            {
+              al.alignAs(copyAlignment);
             }
             else
             {
-              Desktop.addInternalFrame(newFrame, newtitle, DEFAULT_WIDTH,
-                      DEFAULT_HEIGHT);
+              /*
+               * align cdna to protein - currently only if 
+               * fetching and aligning Ensembl transcripts!
+               */
+              if (DBRefSource.ENSEMBL.equalsIgnoreCase(source))
+              {
+                copyAlignment.alignAs(al);
+              }
             }
-          }
-          else
-          {
-            System.err.println("No Sequences generated for xRef type "
-                    + source);
+
+            AlignFrame copyThis = new AlignFrame(copyAlignment,
+                    AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
+            copyThis.setTitle(AlignFrame.this.getTitle());
+
+            boolean showSequenceFeatures = viewport
+                    .isShowSequenceFeatures();
+            newFrame.setShowSeqFeatures(showSequenceFeatures);
+            copyThis.setShowSeqFeatures(showSequenceFeatures);
+            FeatureRenderer myFeatureStyling = alignPanel.getSeqPanel().seqCanvas
+                    .getFeatureRenderer();
+
+            /*
+             * copy feature rendering settings to split frame
+             */
+            newFrame.alignPanel.getSeqPanel().seqCanvas
+                    .getFeatureRenderer()
+                    .transferSettings(myFeatureStyling);
+            copyThis.alignPanel.getSeqPanel().seqCanvas
+                    .getFeatureRenderer()
+                    .transferSettings(myFeatureStyling);
+
+            /*
+             * apply 'database source' feature configuration
+             * if any was found
+             */
+            // TODO is this the feature colouring for the original
+            // alignment or the fetched xrefs? either could be Ensembl
+            newFrame.getViewport().applyFeaturesStyle(featureColourScheme);
+            copyThis.getViewport().applyFeaturesStyle(featureColourScheme);
+
+            SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
+                    dna ? newFrame : copyThis);
+            newFrame.setVisible(true);
+            copyThis.setVisible(true);
+            String linkedTitle = MessageManager
+                    .getString("label.linked_view_title");
+            Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
+            sf.adjustDivider();
           }
         } catch (Exception e)
         {
-          jalview.bin.Cache.log.error(
+          Cache.log.error(
                   "Exception when finding crossreferences", e);
         } catch (OutOfMemoryError e)
         {
           new OOMWarning("whilst fetching crossreferences", e);
-        } catch (Error e)
+        } catch (Throwable e)
         {
-          jalview.bin.Cache.log.error("Error when finding crossreferences",
+          Cache.log.error("Error when finding crossreferences",
                   e);
+        } finally
+        {
+          AlignFrame.this.setProgressBar(MessageManager.formatMessage(
+                  "status.finished_searching_for_sequences_from",
+                  new Object[] { source }), sttime);
         }
-        AlignFrame.this.setProgressBar(MessageManager.formatMessage(
-                "status.finished_searching_for_sequences_from",
-                new Object[] { source }), sttime);
       }
 
       /**
-       * @param alignment
-       * @param prods
+       * Makes an alignment containing the given sequences. If this is of the
+       * same type as the given dataset (nucleotide/protein), then the new
+       * alignment shares the same dataset, and its dataset sequences are added
+       * to it. Otherwise a new dataset sequence is created for the
+       * cross-references.
+       * 
+       * @param dataset
+       * @param seqs
        * @return
        */
-      protected Alignment makeCrossReferencesAlignment(
-Alignment dataset,
-              Alignment prods)
+      protected AlignmentI makeCrossReferencesAlignment(AlignmentI dataset,
+              AlignmentI seqs)
       {
-        SequenceI[] sprods = new SequenceI[prods.getHeight()];
+        boolean sameType = dataset.isNucleotide() == seqs.isNucleotide();
+
+        SequenceI[] sprods = new SequenceI[seqs.getHeight()];
         for (int s = 0; s < sprods.length; s++)
         {
-          sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
-          if (dataset.getSequences() == null
-                  || !dataset.getSequences().contains(
-                          sprods[s].getDatasetSequence()))
+          sprods[s] = (seqs.getSequenceAt(s)).deriveSequence();
+          if (sameType)
           {
-            dataset.addSequence(sprods[s].getDatasetSequence());
+            if (dataset.getSequences() == null
+                    || !dataset.getSequences().contains(
+                            sprods[s].getDatasetSequence()))
+            {
+              dataset.addSequence(sprods[s].getDatasetSequence());
+            }
           }
           sprods[s].updatePDBIds();
         }
         Alignment al = new Alignment(sprods);
-        al.setDataset(dataset);
+        if (sameType)
+        {
+          al.setDataset((Alignment) dataset);
+        }
+        else
+        {
+          al.createDatasetAlignment();
+        }
         return al;
       }
 
@@ -4887,23 +4883,6 @@ Alignment dataset,
     frunner.start();
   }
 
-  public boolean canShowTranslationProducts(SequenceI[] selection,
-          AlignmentI alignment)
-  {
-    // old way
-    try
-    {
-      return (jalview.analysis.Dna.canTranslate(selection,
-              viewport.getViewAsVisibleContigs(true)));
-    } catch (Exception e)
-    {
-      jalview.bin.Cache.log
-              .warn("canTranslate threw an exception - please report to help@jalview.org",
-                      e);
-      return false;
-    }
-  }
-
   /**
    * Construct and display a new frame containing the translation of this
    * frame's DNA sequences to their aligned protein (amino acid) equivalents.
@@ -5318,10 +5297,10 @@ Alignment dataset,
               alignPanel.paintAlignment(true);
             }
           }
-            else
-            {
-              new FileLoader().LoadFile(viewport, file, protocol, format);
-            }
+          else
+          {
+            new FileLoader().LoadFile(viewport, file, protocol, format);
+          }
         }
       }
       if (isAnnotation)
@@ -5525,18 +5504,23 @@ Alignment dataset,
       {
         new Thread(new Runnable()
         {
-
           @Override
           public void run()
           {
-            boolean isNuclueotide = alignPanel.alignFrame
-                    .getViewport().getAlignment()
-                    .isNucleotide();
-            new jalview.ws.DBRefFetcher(alignPanel.av
-                    .getSequenceSelection(),
-                    alignPanel.alignFrame, null,
-                    alignPanel.alignFrame.featureSettings,
-                    isNuclueotide)
+            boolean isNucleotide = alignPanel.alignFrame.getViewport()
+                    .getAlignment().isNucleotide();
+            DBRefFetcher dbRefFetcher = new DBRefFetcher(alignPanel.av
+                    .getSequenceSelection(), alignPanel.alignFrame, null,
+                    alignPanel.alignFrame.featureSettings, isNucleotide);
+            dbRefFetcher.addListener(new FetchFinishedListenerI()
+            {
+              @Override
+              public void finished()
+              {
+                AlignFrame.this.setMenusForViewport();
+              }
+            });
+            dbRefFetcher
                     .fetchDBRefs(false);
           }
         }).start();
@@ -5551,7 +5535,7 @@ Alignment dataset,
       @Override
       public void run()
       {
-        final jalview.ws.SequenceFetcher sf = SequenceFetcher
+        final jalview.ws.SequenceFetcher sf = jalview.gui.SequenceFetcher
                 .getSequenceFetcherSingleton(me);
         javax.swing.SwingUtilities.invokeLater(new Runnable()
         {
@@ -5605,15 +5589,24 @@ Alignment dataset,
                       @Override
                       public void run()
                       {
-                        boolean isNuclueotide = alignPanel.alignFrame
+                        boolean isNucleotide = alignPanel.alignFrame
                                 .getViewport().getAlignment()
                                 .isNucleotide();
-                        new jalview.ws.DBRefFetcher(alignPanel.av
-                                .getSequenceSelection(),
+                        DBRefFetcher dbRefFetcher = new DBRefFetcher(
+                                alignPanel.av.getSequenceSelection(),
                                 alignPanel.alignFrame, dassource,
                                 alignPanel.alignFrame.featureSettings,
-                                isNuclueotide)
-                                .fetchDBRefs(false);
+                                isNucleotide);
+                        dbRefFetcher
+                                .addListener(new FetchFinishedListenerI()
+                                {
+                                  @Override
+                                  public void finished()
+                                  {
+                                    AlignFrame.this.setMenusForViewport();
+                                  }
+                                });
+                        dbRefFetcher.fetchDBRefs(false);
                       }
                     }).start();
                   }
@@ -5646,15 +5639,24 @@ Alignment dataset,
                       @Override
                       public void run()
                       {
-                        boolean isNuclueotide = alignPanel.alignFrame
+                        boolean isNucleotide = alignPanel.alignFrame
                                 .getViewport().getAlignment()
                                 .isNucleotide();
-                        new jalview.ws.DBRefFetcher(alignPanel.av
-                                .getSequenceSelection(),
+                        DBRefFetcher dbRefFetcher = new DBRefFetcher(
+                                alignPanel.av.getSequenceSelection(),
                                 alignPanel.alignFrame, dassource,
                                 alignPanel.alignFrame.featureSettings,
-                                isNuclueotide)
-                                .fetchDBRefs(false);
+                                isNucleotide);
+                        dbRefFetcher
+                                .addListener(new FetchFinishedListenerI()
+                                {
+                                  @Override
+                                  public void finished()
+                                  {
+                                    AlignFrame.this.setMenusForViewport();
+                                  }
+                                });
+                        dbRefFetcher.fetchDBRefs(false);
                       }
                     }).start();
                   }
@@ -5702,15 +5704,24 @@ Alignment dataset,
                         @Override
                         public void run()
                         {
-                          boolean isNuclueotide = alignPanel.alignFrame
+                          boolean isNucleotide = alignPanel.alignFrame
                                   .getViewport().getAlignment()
                                   .isNucleotide();
-                          new jalview.ws.DBRefFetcher(alignPanel.av
-                                  .getSequenceSelection(),
+                          DBRefFetcher dbRefFetcher = new DBRefFetcher(
+                                  alignPanel.av.getSequenceSelection(),
                                   alignPanel.alignFrame, dassrc,
                                   alignPanel.alignFrame.featureSettings,
-                                  isNuclueotide)
-                                  .fetchDBRefs(false);
+                                  isNucleotide);
+                          dbRefFetcher
+                                  .addListener(new FetchFinishedListenerI()
+                                  {
+                                    @Override
+                                    public void finished()
+                                    {
+                                      AlignFrame.this.setMenusForViewport();
+                                    }
+                                  });
+                          dbRefFetcher.fetchDBRefs(false);
                         }
                       }).start();
                     }