JAL-969 - refactor colourscheme machinery from GUI code to core alignment view model
[jalview.git] / src / jalview / gui / AlignFrame.java
index e1775d7..3a0e3f5 100755 (executable)
@@ -55,6 +55,7 @@ import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.io.JnetAnnotationMaker;
 import jalview.io.NewickFile;
+import jalview.io.TCoffeeScoreFile;
 import jalview.jbgui.GAlignFrame;
 import jalview.schemes.Blosum62ColourScheme;
 import jalview.schemes.BuriedColourScheme;
@@ -69,13 +70,14 @@ import jalview.schemes.PurinePyrimidineColourScheme;
 import jalview.schemes.RNAHelicesColourChooser;
 import jalview.schemes.ResidueProperties;
 import jalview.schemes.StrandColourScheme;
+import jalview.schemes.TCoffeeColourScheme;
 import jalview.schemes.TaylorColourScheme;
 import jalview.schemes.TurnColourScheme;
 import jalview.schemes.UserColourScheme;
 import jalview.schemes.ZappoColourScheme;
-import jalview.ws.WSMenuEntryProviderI;
 import jalview.ws.jws1.Discoverer;
 import jalview.ws.jws2.Jws2Discoverer;
+import jalview.ws.seqfetcher.DbSourceProxy;
 
 import java.awt.BorderLayout;
 import java.awt.Color;
@@ -106,6 +108,7 @@ import java.net.URL;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.Hashtable;
+import java.util.List;
 import java.util.Vector;
 
 import javax.swing.JButton;
@@ -143,7 +146,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   AlignViewport viewport;
 
   Vector alignPanels = new Vector();
-
+  
   /**
    * Last format used to load or save alignments in this window
    */
@@ -715,7 +718,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
     showSeqFeatures.setSelected(av.showSequenceFeatures);
     hiddenMarkers.setState(av.showHiddenMarkers);
-    applyToAllGroups.setState(av.colourAppliesToAllGroups);
+    applyToAllGroups.setState(av.getColourAppliesToAllGroups());
     showNpFeatsMenuitem.setSelected(av.isShowNpFeats());
     showDbRefsMenuitem.setSelected(av.isShowDbRefs());
     autoCalculate.setSelected(av.autoCalculateConsensus);
@@ -853,6 +856,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   {
     if (fileName != null)
     {
+      // TODO: JAL-1108 - ensure all associated frames are closed regardless of
+      // originating file's format
       // TODO: work out how to recover feature settings for correct view(s) when
       // file is reloaded.
       if (currentFileFormat.equals("Jalview"))
@@ -1554,10 +1559,10 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
   synchronized void slideSequences(boolean right, int size)
   {
-    Vector sg = new Vector();
+    List<SequenceI> sg = new Vector();
     if (viewport.cursorMode)
     {
-      sg.addElement(viewport.getAlignment().getSequenceAt(
+      sg.add(viewport.getAlignment().getSequenceAt(
               alignPanel.seqPanel.seqCanvas.cursorY));
     }
     else if (viewport.getSelectionGroup() != null
@@ -1581,10 +1586,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         invertGroup.add(viewport.getAlignment().getSequenceAt(i));
     }
 
-    SequenceI[] seqs1 = new SequenceI[sg.size()];
-    for (int i = 0; i < sg.size(); i++)
-      seqs1[i] = (SequenceI) sg.elementAt(i);
-
+    SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
+            
     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
     for (int i = 0; i < invertGroup.size(); i++)
       seqs2[i] = (SequenceI) invertGroup.elementAt(i);
@@ -2232,12 +2235,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
       addHistoryItem(trimRegion);
 
-      Vector groups = viewport.getAlignment().getGroups();
-
-      for (int i = 0; i < groups.size(); i++)
+      for (SequenceGroup sg :viewport.getAlignment().getGroups())
       {
-        SequenceGroup sg = (SequenceGroup) groups.get(i);
-
         if ((trimLeft && !sg.adjustForRemoveLeft(column))
                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
         {
@@ -2920,8 +2919,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    */
   public void clustalColour_actionPerformed(ActionEvent e)
   {
-    changeColour(new ClustalxColourScheme(viewport.getAlignment()
-            .getSequences(), viewport.getAlignment().getWidth()));
+    changeColour(new ClustalxColourScheme(viewport.getAlignment(), viewport.getHiddenRepSequences()));
   }
 
   /**
@@ -3052,6 +3050,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    */
   public void changeColour(ColourSchemeI cs)
   {
+    // TODO: compare with applet and pull up to model method
     int threshold = 0;
 
     if (cs != null)
@@ -3098,12 +3097,10 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
     if (viewport.getColourAppliesToAllGroups())
     {
-      Vector groups = viewport.getAlignment().getGroups();
 
-      for (int i = 0; i < groups.size(); i++)
-      {
-        SequenceGroup sg = (SequenceGroup) groups.elementAt(i);
 
+      for (SequenceGroup sg:viewport.getAlignment().getGroups())
+      {
         if (cs == null)
         {
           sg.cs = null;
@@ -3112,8 +3109,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
         if (cs instanceof ClustalxColourScheme)
         {
-          sg.cs = new ClustalxColourScheme(sg.getSequences(viewport
-                  .getHiddenRepSequences()), sg.getWidth());
+          sg.cs = new ClustalxColourScheme(sg, viewport
+                  .getHiddenRepSequences());
         }
         else if (cs instanceof UserColourScheme)
         {
@@ -3123,7 +3120,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         {
           try
           {
-            sg.cs = (ColourSchemeI) cs.getClass().newInstance();
+            sg.cs = cs.getClass().newInstance();
           } catch (Exception ex)
           {
           }
@@ -3565,13 +3562,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         return;
       }
 
-      int s = 0;
       SequenceGroup sg = viewport.getSelectionGroup();
 
       /* Decide if the selection is a column region */
-      while (s < sg.getSize())
+      for (SequenceI _s:sg.getSequences())
       {
-        if (((SequenceI) sg.getSequences(null).elementAt(s++)).getLength() < sg
+        if (_s.getLength() < sg
                 .getEndRes())
         {
           JOptionPane
@@ -3922,6 +3918,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
   }
 
+  @Override
+  protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
+  {
+    changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
+  }
+
   public TreePanel ShowNewickTree(NewickFile nf, String title)
   {
     return ShowNewickTree(nf, title, 600, 500, 4, 5);
@@ -4099,12 +4101,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           wsmenu.add(secstrmenu);
           wsmenu.add(dismenu);
           wsmenu.add(analymenu);
-//          final ArrayList<JMenu> submens=new ArrayList<JMenu>();
-//          submens.add(msawsmenu);
- //         submens.add(secstrmenu);
- //         submens.add(dismenu);
-  //        submens.add(analymenu);
-          
+          // final ArrayList<JMenu> submens=new ArrayList<JMenu>();
+          // submens.add(msawsmenu);
+          // submens.add(secstrmenu);
+          // submens.add(dismenu);
+          // submens.add(analymenu);
+
           // No search services yet
           // wsmenu.add(seqsrchmenu);
 
@@ -4738,54 +4740,92 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
       if (!isAnnotation)
       {
-        // try to see if its a JNet 'concise' style annotation file *before* we
-        // try to parse it as a features file
-        if (format == null)
+        // first see if its a T-COFFEE score file
+        TCoffeeScoreFile tcf = null;
+        try
         {
-          format = new IdentifyFile().Identify(file, protocol);
-        }
-        if (format.equalsIgnoreCase("JnetFile"))
+          tcf = new TCoffeeScoreFile(file, protocol);
+          if (tcf.isValid())
+          {
+            if (tcf.annotateAlignment(viewport.getAlignment(), true))
+            {
+              tcoffeeColour.setEnabled(true);
+              tcoffeeColour.setSelected(true);
+              changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
+              isAnnotation = true;
+              statusBar
+                      .setText("Successfully pasted T-Coffee scores to alignment.");
+            }
+            else
+            {
+              // some problem - if no warning its probable that the ID matching process didn't work
+              JOptionPane.showMessageDialog(Desktop.desktop,
+                      tcf.getWarningMessage()==null ? "Check that the file matches sequence IDs in the alignment." : tcf.getWarningMessage(),
+                      "Problem reading T-COFFEE score file",
+                      JOptionPane.WARNING_MESSAGE);
+            }
+          }
+          else
+          {
+            tcf = null;
+          }
+        } catch (Exception x)
         {
-          jalview.io.JPredFile predictions = new jalview.io.JPredFile(file,
-                  protocol);
-          new JnetAnnotationMaker().add_annotation(predictions,
-                  viewport.getAlignment(), 0, false);
-          isAnnotation = true;
+          Cache.log.debug("Exception when processing data source as T-COFFEE score file",x);
+          tcf = null;
         }
-        else
+        if (tcf == null)
         {
-          /*
-           * if (format.equalsIgnoreCase("PDB")) {
-           * 
-           * String pdbfn = ""; // try to match up filename with sequence id try
-           * { if (protocol == jalview.io.FormatAdapter.FILE) { File fl = new
-           * File(file); pdbfn = fl.getName(); } else if (protocol ==
-           * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
-           * url.getFile(); } } catch (Exception e) { } ; if (assocSeq == null)
-           * { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
-           * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) { //
-           * attempt to find a match in the alignment SequenceI mtch =
-           * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
-           * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) > l)
-           * { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch =
-           * idm.findIdMatch(pdbfn); } if (mtch != null) { // try and associate
-           * // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
-           * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null) {
-           * System.err.println("Associated file : " + file + " with " +
-           * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
-           * TODO: maybe need to load as normal otherwise return; } }
-           */
+          // try to see if its a JNet 'concise' style annotation file *before*
+          // we
           // try to parse it as a features file
-          boolean isGroupsFile = parseFeaturesFile(file, protocol);
-          // if it wasn't a features file then we just treat it as a general
-          // alignment file to load into the current view.
-          if (!isGroupsFile)
+          if (format == null)
           {
-            new FileLoader().LoadFile(viewport, file, protocol, format);
+            format = new IdentifyFile().Identify(file, protocol);
+          }
+          if (format.equalsIgnoreCase("JnetFile"))
+          {
+            jalview.io.JPredFile predictions = new jalview.io.JPredFile(
+                    file, protocol);
+            new JnetAnnotationMaker().add_annotation(predictions,
+                    viewport.getAlignment(), 0, false);
+            isAnnotation = true;
           }
           else
           {
-            alignPanel.paintAlignment(true);
+            /*
+             * if (format.equalsIgnoreCase("PDB")) {
+             * 
+             * String pdbfn = ""; // try to match up filename with sequence id
+             * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
+             * new File(file); pdbfn = fl.getName(); } else if (protocol ==
+             * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
+             * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
+             * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
+             * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
+             * // attempt to find a match in the alignment SequenceI mtch =
+             * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
+             * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
+             * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
+             * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
+             * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
+             * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
+             * { System.err.println("Associated file : " + file + " with " +
+             * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
+             * TODO: maybe need to load as normal otherwise return; } }
+             */
+            // try to parse it as a features file
+            boolean isGroupsFile = parseFeaturesFile(file, protocol);
+            // if it wasn't a features file then we just treat it as a general
+            // alignment file to load into the current view.
+            if (!isGroupsFile)
+            {
+              new FileLoader().LoadFile(viewport, file, protocol, format);
+            }
+            else
+            {
+              alignPanel.paintAlignment(true);
+            }
           }
         }
       }
@@ -4943,31 +4983,45 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       {
         final jalview.ws.SequenceFetcher sf = SequenceFetcher
                 .getSequenceFetcherSingleton(me);
-        final String[] otherdb = sf.getOrderedSupportedSources();
-        // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
-        // jalview.util.QuickSort.sort(otherdb, otherdb);
         javax.swing.SwingUtilities.invokeLater(new Runnable()
         {
           public void run()
           {
-
+            String[] dbclasses = sf.getOrderedSupportedSources();
+            // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
+            // jalview.util.QuickSort.sort(otherdb, otherdb);
+            List<DbSourceProxy> otherdb;
             JMenu dfetch = new JMenu();
-            JMenuItem fetchr;
-            rfetch.add(dfetch);
-            int comp = 0, mcomp = 15;
+            JMenu ifetch = new JMenu();
+            JMenuItem fetchr = null;
+            int comp = 0, icomp = 0, mcomp = 15;
             String mname = null;
-            if (otherdb != null && otherdb.length > 0)
+            int dbi = 0;
+            for (String dbclass : dbclasses)
             {
-              for (int i = 0; i < otherdb.length; i++)
+              otherdb = sf.getSourceProxy(dbclass);
+              // add a single entry for this class, or submenu allowing 'fetch
+              // all' or pick one
+              if (otherdb == null || otherdb.size() < 1)
               {
-                String dbname = sf.getSourceProxy(otherdb[i]).getDbName();
-                if (mname == null)
-                {
-                  mname = "from '" + dbname + "'";
-                }
-                fetchr = new JMenuItem(otherdb[i]);
-                final String[] dassource = new String[]
-                { otherdb[i] };
+                continue;
+              }
+              // List<DbSourceProxy> dbs=otherdb;
+              // otherdb=new ArrayList<DbSourceProxy>();
+              // for (DbSourceProxy db:dbs)
+              // {
+              // if (!db.isA(DBRefSource.ALIGNMENTDB)
+              // }
+              if (mname == null)
+              {
+                mname = "From " + dbclass;
+              }
+              if (otherdb.size() == 1)
+              {
+                final DbSourceProxy[] dassource = otherdb
+                        .toArray(new DbSourceProxy[0]);
+                DbSourceProxy src = otherdb.get(0);
+                fetchr = new JMenuItem(src.getDbSource());
                 fetchr.addActionListener(new ActionListener()
                 {
 
@@ -4987,17 +5041,108 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
                   }
 
                 });
-                fetchr.setToolTipText("Retrieve from " + dbname);
+                fetchr.setToolTipText("<html>"
+                        + JvSwingUtils.wrapTooltip("Retrieve from "
+                                + src.getDbName()) + "<html>");
                 dfetch.add(fetchr);
-                if (comp++ == mcomp || i == (otherdb.length - 1))
+                comp++;
+              }
+              else
+              {
+                final DbSourceProxy[] dassource = otherdb
+                        .toArray(new DbSourceProxy[0]);
+                // fetch all entry
+                DbSourceProxy src = otherdb.get(0);
+                fetchr = new JMenuItem("Fetch All '" + src.getDbSource()
+                        + "'");
+                fetchr.addActionListener(new ActionListener()
                 {
-                  dfetch.setText(mname + " to '" + dbname + "'");
-                  rfetch.add(dfetch);
-                  dfetch = new JMenu();
-                  mname = null;
-                  comp = 0;
+                  public void actionPerformed(ActionEvent e)
+                  {
+                    new Thread(new Runnable()
+                    {
+
+                      public void run()
+                      {
+                        new jalview.ws.DBRefFetcher(alignPanel.av
+                                .getSequenceSelection(),
+                                alignPanel.alignFrame, dassource)
+                                .fetchDBRefs(false);
+                      }
+                    }).start();
+                  }
+                });
+
+                fetchr.setToolTipText("<html>"
+                        + JvSwingUtils.wrapTooltip("Retrieve from all "
+                                + otherdb.size() + " sources in "
+                                + src.getDbSource() + "<br>First is :"
+                                + src.getDbName()) + "<html>");
+                dfetch.add(fetchr);
+                comp++;
+                // and then build the rest of the individual menus
+                ifetch = new JMenu("Sources from " + src.getDbSource());
+                icomp = 0;
+                String imname = null;
+                int i = 0;
+                for (DbSourceProxy sproxy : otherdb)
+                {
+                  String dbname = sproxy.getDbName();
+                  String sname = dbname.length() > 5 ? dbname.substring(0,
+                          5) + "..." : dbname;
+                  String msname = dbname.length() > 10 ? dbname.substring(
+                          0, 10) + "..." : dbname;
+                  if (imname == null)
+                  {
+                    imname = "from '" + sname + "'";
+                  }
+                  fetchr = new JMenuItem(msname);
+                  final DbSourceProxy[] dassrc =
+                  { sproxy };
+                  fetchr.addActionListener(new ActionListener()
+                  {
+
+                    public void actionPerformed(ActionEvent e)
+                    {
+                      new Thread(new Runnable()
+                      {
+
+                        public void run()
+                        {
+                          new jalview.ws.DBRefFetcher(alignPanel.av
+                                  .getSequenceSelection(),
+                                  alignPanel.alignFrame, dassrc)
+                                  .fetchDBRefs(false);
+                        }
+                      }).start();
+                    }
+
+                  });
+                  fetchr.setToolTipText("<html>"
+                          + JvSwingUtils.wrapTooltip("Retrieve from "
+                                  + dbname) + "</html>");
+                  ifetch.add(fetchr);
+                  ++i;
+                  if (++icomp >= mcomp || i == (otherdb.size()))
+                  {
+                    ifetch.setText(imname + " to '" + sname + "'");
+                    dfetch.add(ifetch);
+                    ifetch = new JMenu();
+                    imname = null;
+                    icomp = 0;
+                    comp++;
+                  }
                 }
               }
+              ++dbi;
+              if (comp >= mcomp || dbi >= (dbclasses.length))
+              {
+                dfetch.setText(mname + " to '" + dbclass + "'");
+                rfetch.add(dfetch);
+                dfetch = new JMenu();
+                mname = null;
+                comp = 0;
+              }
             }
           }
         });
@@ -5137,9 +5282,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
         Color col = new Color((int) (Math.random() * 255),
                 (int) (Math.random() * 255), (int) (Math.random() * 255));
         col = col.brighter();
-        for (Enumeration sq = gps[g].getSequences(null).elements(); sq
-                .hasMoreElements(); viewport.setSequenceColour(
-                (SequenceI) sq.nextElement(), col))
+        for (SequenceI s:gps[g].getSequences())
+          viewport.setSequenceColour(
+                s, col)
           ;
       }
       PaintRefresher.Refresh(this, viewport.getSequenceSetId());