JAL-3829 tests need to wait for dialog to be closed and background processes to finis...
[jalview.git] / src / jalview / gui / StructureChooser.java
index 55d0ba1..82ad03b 100644 (file)
 
 package jalview.gui;
 
+import java.awt.event.ItemEvent;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.concurrent.Executors;
+
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JTable;
+import javax.swing.SwingUtilities;
+import javax.swing.table.AbstractTableModel;
+
 import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
 import jalview.bin.Jalview;
-import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.DBRefSource;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.fts.api.FTSData;
@@ -37,6 +50,7 @@ import jalview.fts.core.FTSRestResponse;
 import jalview.fts.service.pdb.PDBFTSRestClient;
 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
 import jalview.gui.structurechooser.StructureChooserQuerySource;
+import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
 import jalview.io.DataSourceType;
 import jalview.jbgui.FilterOption;
 import jalview.jbgui.GStructureChooser;
@@ -44,25 +58,9 @@ import jalview.structure.StructureMapping;
 import jalview.structure.StructureSelectionManager;
 import jalview.util.MessageManager;
 import jalview.ws.DBRefFetcher;
+import jalview.ws.seqfetcher.DbSourceProxy;
 import jalview.ws.sifts.SiftsSettings;
 
-import java.awt.event.ItemEvent;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import java.util.Vector;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JLabel;
-import javax.swing.JTable;
-import javax.swing.SwingUtilities;
-import javax.swing.table.AbstractTableModel;
-
 /**
  * Provides the behaviors for the Structure chooser Panel
  * 
@@ -97,6 +95,8 @@ public class StructureChooser extends GStructureChooser
 
   private boolean cachedPDBExists;
 
+  private Collection<FTSData> lastDiscoveredStructuresSet;
+
   private static StructureViewer lastTargetedView = null;
 
   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
@@ -127,21 +127,26 @@ public class StructureChooser extends GStructureChooser
 
     chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
 
-    // ensure a filter option is in force for search
-    populateFilterComboBox(true, cachedPDBExists);
-    Thread discoverPDBStructuresThread = new Thread(new Runnable()
+    final Runnable discoverPDBStructures = new Runnable()
     {
       @Override
       public void run()
       {
-        // looks for any existing structures already loaded 
-        // for the sequences (the cached ones) 
-        // then queries the StructureChooserQuerySource to 
+        // check which FTS engine to use
+        data = StructureChooserQuerySource
+                .getQuerySourceFor(selectedSequences);
+
+        // ensure a filter option is in force for search
+        populateFilterComboBox(true, cachedPDBExists);
+
+        // looks for any existing structures already loaded
+        // for the sequences (the cached ones)
+        // then queries the StructureChooserQuerySource to
         // discover more structures.
-        // 
+        //
         // Possible optimisation is to only begin querying
         // the structure chooser if there are no cached structures.
-        
+
         long startTime = System.currentTimeMillis();
         updateProgressIndicator(MessageManager
                 .getString("status.loading_cached_pdb_entries"), startTime);
@@ -157,8 +162,80 @@ public class StructureChooser extends GStructureChooser
         mainFrame.setVisible(true);
         updateCurrentView();
       }
-    });
-    discoverPDBStructuresThread.start();
+    };
+    final List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
+
+    final Runnable discoverCanonicalDBrefs = new Runnable()
+    {
+      @Override
+      public void run()
+      {
+        long progressId = System.currentTimeMillis();
+
+        int y = seqsWithoutSourceDBRef.size();
+        
+        setProgressBar(MessageManager.formatMessage(
+                "status.fetching_dbrefs_for_sequences_without_valid_refs",
+                y), progressId);
+        SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
+                .toArray(new SequenceI[y]);
+        
+        DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
+                progressBar, new DbSourceProxy[]
+                { new jalview.ws.dbsources.Uniprot() },
+                null, false);
+        
+        dbRefFetcher.fetchDBRefs(true);
+
+        setProgressBar("Fetch complete.", progressId); // todo i18n
+
+        Executors.defaultThreadFactory().newThread(discoverPDBStructures).start();
+      }
+    };
+
+    Executors.defaultThreadFactory().newThread(new Runnable()
+    {
+      public void run()
+      {
+
+        for (SequenceI seq : selectedSequences)
+        {
+          if (seq.isProtein())
+          {
+            int dbRef = ThreeDBStructureChooserQuerySource
+                    .checkUniprotRefs(seq.getDBRefs());
+            if (dbRef < 0)
+            {
+              if (seq.getAllPDBEntries()==null && seq.getAllPDBEntries().size()==0)
+              {
+                seqsWithoutSourceDBRef.add(seq);
+              }
+            }
+          }
+        }
+        // retrieve database refs for protein sequences
+        if (!seqsWithoutSourceDBRef.isEmpty())
+        {
+          // need cancel and no to result in the discoverPDB action - mocked is 'cancel'
+          JvOptionPane.newOptionDialog(Desktop.getDesktop())
+                  .setResponseHandler(JvOptionPane.OK_OPTION, discoverCanonicalDBrefs)
+                  .setResponseHandler(JvOptionPane.CANCEL_OPTION, discoverPDBStructures)
+                  .setResponseHandler(JvOptionPane.NO_OPTION, discoverPDBStructures)
+                  .showDialog(MessageManager.formatMessage("label.fetch_references_for",
+                          seqsWithoutSourceDBRef.size()), MessageManager.getString(
+                          "label.fetch_uniprot_references"),
+                          JvOptionPane.YES_NO_OPTION,
+                          JvOptionPane.PLAIN_MESSAGE, null, new Object[]
+                          { MessageManager.getString("action.ok"),
+                              MessageManager.getString("action.cancel") },
+                          MessageManager.getString("action.ok"));
+        } else {
+          // get structures directly
+          Executors.defaultThreadFactory().newThread(discoverPDBStructures).start();
+        }
+      };
+    }).start();;
+
   }
 
   /**
@@ -280,7 +357,9 @@ public class StructureChooser extends GStructureChooser
     {
       getResultTable()
               .setModel(data.getTableModel(discoveredStructuresSet));
+      
       noOfStructuresFound = discoveredStructuresSet.size();
+      lastDiscoveredStructuresSet=discoveredStructuresSet;
       mainFrame.setTitle(MessageManager.formatMessage(
               "label.structure_chooser_no_of_structures",
               noOfStructuresFound, totalTime));
@@ -336,6 +415,7 @@ public class StructureChooser extends GStructureChooser
   {
     Thread filterThread = new Thread(new Runnable()
     {
+
       @Override
       public void run()
       {
@@ -378,7 +458,7 @@ public class StructureChooser extends GStructureChooser
           reorderedStructuresSet.addAll(discoveredStructuresSet);
           getResultTable()
                   .setModel(data.getTableModel(reorderedStructuresSet));
-
+          
           FTSRestResponse.configureTableColumn(getResultTable(),
                   wantedFields, tempUserPrefs);
           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
@@ -450,36 +530,57 @@ public class StructureChooser extends GStructureChooser
   protected void populateFilterComboBox(boolean haveData,
           boolean cachedPDBExist)
   {
+    populateFilterComboBox(haveData, cachedPDBExist, null);
+  }
+  /**
+   * Populates the filter combo-box options dynamically depending on discovered
+   * structures
+   */
+  protected void populateFilterComboBox(boolean haveData,
+          boolean cachedPDBExist, FilterOption lastSel)
+  {
+    
     /*
      * temporarily suspend the change listener behaviour
      */
     cmb_filterOption.removeItemListener(this);
-
+    int selSet=-1;
     cmb_filterOption.removeAllItems();
     if (haveData)
     {
       List<FilterOption> filters = data.getAvailableFilterOptions(VIEWS_FILTER);
+      data.updateAvailableFilterOptions(VIEWS_FILTER, filters, lastDiscoveredStructuresSet);
+      int p=0;
       for (FilterOption filter:filters)
       {
+        if (lastSel!=null && filter.equals(lastSel)) {
+          selSet=p;
+        }
+        p++;
         cmb_filterOption.addItem(filter);
       }
     }
     cmb_filterOption.addItem(
             new FilterOption(MessageManager.getString("label.enter_pdb_id"),
-                    "-", VIEWS_ENTER_ID, false));
+                    "-", VIEWS_ENTER_ID, false,null));
     cmb_filterOption.addItem(
             new FilterOption(MessageManager.getString("label.from_file"),
-                    "-", VIEWS_FROM_FILE, false));
+                    "-", VIEWS_FROM_FILE, false,null));
 
     if (cachedPDBExist)
     {
       FilterOption cachedOption = new FilterOption(
               MessageManager.getString("label.cached_structures"), "-",
-              VIEWS_LOCAL_PDB, false);
+              VIEWS_LOCAL_PDB, false,null);
       cmb_filterOption.addItem(cachedOption);
-      cmb_filterOption.setSelectedItem(cachedOption);
+      if (selSet==-1) {
+        cmb_filterOption.setSelectedItem(cachedOption);
+      }
+    }
+    if (selSet>-1)
+    {
+      cmb_filterOption.setSelectedIndex(selSet);
     }
-
     cmb_filterOption.addItemListener(this);
   }
 
@@ -498,8 +599,18 @@ public class StructureChooser extends GStructureChooser
     if (selectedFilterOpt.getView() == VIEWS_FILTER)
     {
       mainFrame.setTitle(filterTitle);
-      chk_invertFilter.setVisible(true);
-      filterResultSet(selectedFilterOpt.getValue());
+      // TDB Query has no invert as yet
+      chk_invertFilter.setVisible(selectedFilterOpt.getQuerySource() instanceof PDBStructureChooserQuerySource);
+      
+      if (data!=selectedFilterOpt.getQuerySource() || data.needsRefetch(selectedFilterOpt)) 
+      {
+        data = selectedFilterOpt.getQuerySource();
+        // rebuild the views completely, since prefs will also change
+        tabRefresh();
+        return;
+      } else {
+        filterResultSet(selectedFilterOpt.getValue());
+      }
     }
     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
@@ -763,8 +874,8 @@ public class StructureChooser extends GStructureChooser
           List<SequenceI> selectedSeqsToView = new ArrayList<>();
           for (int row : selectedRows)
           {
-            PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
-                    pdbIdColIndex);
+            PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb.getModel()).getPDBEntryAt(row).getPdbEntry();
+            
             pdbEntriesToView[count++] = pdbEntry;
             SequenceI selectedSeq = (SequenceI) tbl_local_pdb
                     .getValueAt(row, refSeqColIndex);
@@ -1065,6 +1176,8 @@ public class StructureChooser extends GStructureChooser
         public void run()
         {
           fetchStructuresMetaData();
+          //populateFilterComboBox(true, cachedPDBExists);
+
           filterResultSet(
                   ((FilterOption) cmb_filterOption.getSelectedItem())
                           .getValue());
@@ -1121,7 +1234,7 @@ public class StructureChooser extends GStructureChooser
         value = entry.getSequence();
         break;
       case 1:
-        value = entry.getPdbEntry();
+        value = entry.getQualifiedId();
         break;
       case 2:
         value = entry.getPdbEntry().getChainCode() == null ? "_"
@@ -1162,6 +1275,15 @@ public class StructureChooser extends GStructureChooser
       this.pdbEntry = pdbEntry;
     }
 
+    public String getQualifiedId()
+    {
+      if (pdbEntry.hasProvider())
+      {
+        return pdbEntry.getProvider()+":"+pdbEntry.getId();
+      } 
+      return pdbEntry.toString();
+    }
+
     public SequenceI getSequence()
     {
       return sequence;
@@ -1205,4 +1327,15 @@ public class StructureChooser extends GStructureChooser
     data.setDocFieldPrefs(newPrefs);
     
   }
+
+  /**
+   * 
+   * @return true when all initialisation threads have finished and dialog is visible
+   */
+  public boolean isDialogVisible()
+  {
+    return mainFrame != null && data != null && cmb_filterOption != null
+            && mainFrame.isVisible()
+            && cmb_filterOption.getSelectedItem() != null;
+  }
 }