49511ad41f0f7104ccd1063888cec9c27add88d0
[jalview.git] / src / jalview / gui / SequenceFetcher.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 java.util.*;
21
22 import java.awt.*;
23 import java.awt.event.*;
24
25 import javax.swing.*;
26 import javax.swing.tree.DefaultMutableTreeNode;
27 import javax.swing.tree.MutableTreeNode;
28 import javax.swing.tree.TreeModel;
29
30 import jalview.datamodel.*;
31 import jalview.io.*;
32 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
33 import jalview.ws.seqfetcher.DbSourceProxy;
34
35 import java.awt.BorderLayout;
36
37 public class SequenceFetcher extends JPanel implements Runnable
38 {
39   // ASequenceFetcher sfetch;
40   JInternalFrame frame;
41
42   IProgressIndicator guiWindow;
43
44   AlignFrame alignFrame;
45
46   StringBuffer result;
47
48   final String noDbSelected = "-- Select Database --";
49
50   private static jalview.ws.SequenceFetcher sfetch = null;
51
52   private static long lastDasSourceRegistry = -3;
53
54   private static DasSourceRegistryI dasRegistry = null;
55
56   private static boolean _initingFetcher = false;
57
58   private static Thread initingThread = null;
59
60   /**
61    * Blocking method that initialises and returns the shared instance of the
62    * SequenceFetcher client
63    * 
64    * @param guiWindow
65    *          - where the initialisation delay message should be shown
66    * @return the singleton instance of the sequence fetcher client
67    */
68   public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
69           final IProgressIndicator guiWindow)
70   {
71     if (_initingFetcher && initingThread != null && initingThread.isAlive())
72     {
73       if (guiWindow != null)
74       {
75         guiWindow.setProgressBar(
76                 "Waiting for Sequence Database Fetchers to initialise",
77                 Thread.currentThread().hashCode());
78       }
79       // initting happening on another thread - so wait around to see if it
80       // finishes.
81       while (_initingFetcher && initingThread != null
82               && initingThread.isAlive())
83       {
84         try
85         {
86           Thread.sleep(10);
87         } catch (Exception e)
88         {
89         }
90         ;
91       }
92       if (guiWindow != null)
93       {
94         guiWindow.setProgressBar(
95                 "Waiting for Sequence Database Fetchers to initialise",
96                 Thread.currentThread().hashCode());
97       }
98     }
99     if (sfetch == null
100             || dasRegistry != jalview.bin.Cache.getDasSourceRegistry()
101             || lastDasSourceRegistry != (jalview.bin.Cache
102                     .getDasSourceRegistry().getDasRegistryURL() + jalview.bin.Cache
103                     .getDasSourceRegistry().getLocalSourceString())
104                     .hashCode())
105     {
106       _initingFetcher = true;
107       initingThread = Thread.currentThread();
108       /**
109        * give a visual indication that sequence fetcher construction is occuring
110        */
111       if (guiWindow != null)
112       {
113         guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
114                 Thread.currentThread().hashCode());
115       }
116       dasRegistry = jalview.bin.Cache.getDasSourceRegistry();
117       dasRegistry.refreshSources();
118
119       jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
120       if (guiWindow != null)
121       {
122         guiWindow.setProgressBar("Initialising Sequence Database Fetchers",
123                 Thread.currentThread().hashCode());
124       }
125       lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
126               .getLocalSourceString()).hashCode();
127       sfetch = sf;
128       _initingFetcher = false;
129       initingThread = null;
130     }
131     return sfetch;
132   }
133
134   public SequenceFetcher(IProgressIndicator guiIndic)
135   {
136     final IProgressIndicator guiWindow = guiIndic;
137     final SequenceFetcher us = this;
138     // launch initialiser thread
139     Thread sf = new Thread(new Runnable()
140     {
141
142       public void run()
143       {
144         if (getSequenceFetcherSingleton(guiWindow) != null)
145         {
146           us.initGui(guiWindow);
147         }
148         else
149         {
150           javax.swing.SwingUtilities.invokeLater(new Runnable()
151           {
152             public void run()
153             {
154               JOptionPane
155                       .showInternalMessageDialog(
156                               Desktop.desktop,
157                               "Could not create the sequence fetcher client. Check error logs for details.",
158                               "Couldn't create SequenceFetcher",
159                               JOptionPane.ERROR_MESSAGE);
160             }
161           });
162
163           // raise warning dialog
164         }
165       }
166     });
167     sf.start();
168   }
169
170   private class DatabaseAuthority extends DefaultMutableTreeNode
171   {
172
173   };
174
175   private class DatabaseSource extends DefaultMutableTreeNode
176   {
177
178   };
179
180   /**
181    * called by thread spawned by constructor
182    * 
183    * @param guiWindow
184    */
185   private void initGui(IProgressIndicator guiWindow)
186   {
187     this.guiWindow = guiWindow;
188     if (guiWindow instanceof AlignFrame)
189     {
190       alignFrame = (AlignFrame) guiWindow;
191     }
192     database = new JDatabaseTree(sfetch);
193     try
194     {
195       jbInit();
196     } catch (Exception ex)
197     {
198       ex.printStackTrace();
199     }
200
201     frame = new JInternalFrame();
202     frame.setContentPane(this);
203     if (new jalview.util.Platform().isAMac())
204     {
205       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
206     }
207     else
208     {
209       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
210     }
211   }
212
213   private String getFrameTitle()
214   {
215     return ((alignFrame == null) ? "New " : "Additional ")
216             + "Sequence Fetcher";
217   }
218
219   private void jbInit() throws Exception
220   {
221     this.setLayout(borderLayout2);
222
223     database.setFont(JvSwingUtils.getLabelFont());
224     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
225     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
226     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
227     jLabel1.setText("Separate multiple accession ids with semi colon \";\"");
228
229     replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
230     replacePunctuation
231             .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
232     replacePunctuation.setText("Replace commas with semi-colons");
233     ok.setText("OK");
234     ok.addActionListener(new ActionListener()
235     {
236       public void actionPerformed(ActionEvent e)
237       {
238         ok_actionPerformed();
239       }
240     });
241     clear.setText("Clear");
242     clear.addActionListener(new ActionListener()
243     {
244       public void actionPerformed(ActionEvent e)
245       {
246         clear_actionPerformed();
247       }
248     });
249
250     example.setText("Example");
251     example.addActionListener(new ActionListener()
252     {
253       public void actionPerformed(ActionEvent e)
254       {
255         example_actionPerformed();
256       }
257     });
258     close.setText("Close");
259     close.addActionListener(new ActionListener()
260     {
261       public void actionPerformed(ActionEvent e)
262       {
263         close_actionPerformed(e);
264       }
265     });
266     textArea.setFont(JvSwingUtils.getLabelFont());
267     textArea.setLineWrap(true);
268     textArea.addKeyListener(new KeyAdapter()
269     {
270       public void keyPressed(KeyEvent e)
271       {
272         if (e.getKeyCode() == KeyEvent.VK_ENTER)
273           ok_actionPerformed();
274       }
275     });
276     jPanel3.setLayout(borderLayout1);
277     borderLayout1.setVgap(5);
278     jPanel1.add(ok);
279     jPanel1.add(example);
280     jPanel1.add(clear);
281     jPanel1.add(close);
282     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
283     jPanel2.setLayout(borderLayout3);
284     databaseButt = database.getDatabaseSelectorButton();
285     databaseButt.setFont(JvSwingUtils.getLabelFont());
286     database.addActionListener(new ActionListener()
287     {
288
289       public void actionPerformed(ActionEvent e)
290       {
291         DbSourceProxy db = null;
292         try
293         {
294           databaseButt.setText(database.getSelectedItem()
295                   + (database.getSelectedSources().size() > 1 ? " (and "
296                           + database.getSelectedSources().size()
297                           + " others)" : ""));
298           String eq = database.getExampleQueries();
299           dbeg.setText("Example query: " + eq);
300           replacePunctuation.setEnabled(!(eq != null && eq.indexOf(",") > -1));
301         } catch (Exception ex)
302         {
303           dbeg.setText("");
304           replacePunctuation.setEnabled(true);
305         }
306         jPanel2.repaint();
307       }
308     });
309     dbeg.setText("");
310     jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
311     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
312     JPanel jPanel2a = new JPanel(new BorderLayout());
313     jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
314     jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
315     jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
316     // jPanel2.setPreferredSize(new Dimension())
317     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
318     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
319     this.add(jPanel3, java.awt.BorderLayout.CENTER);
320     this.add(jPanel2, java.awt.BorderLayout.NORTH);
321     jScrollPane1.getViewport().add(textArea);
322
323   }
324
325   protected void example_actionPerformed()
326   {
327     DbSourceProxy db = null;
328     try
329     {
330       textArea.setText(database.getExampleQueries());
331     } catch (Exception ex)
332     {
333     }
334     jPanel3.repaint();
335   }
336
337   protected void clear_actionPerformed()
338   {
339     textArea.setText("");
340     jPanel3.repaint();
341   }
342
343   JLabel dbeg = new JLabel();
344
345   JDatabaseTree database;
346
347   JButton databaseButt;
348
349   JLabel jLabel1 = new JLabel();
350
351   JCheckBox replacePunctuation = new JCheckBox();
352
353   JButton ok = new JButton();
354
355   JButton clear = new JButton();
356
357   JButton example = new JButton();
358
359   JButton close = new JButton();
360
361   JPanel jPanel1 = new JPanel();
362
363   JTextArea textArea = new JTextArea();
364
365   JScrollPane jScrollPane1 = new JScrollPane();
366
367   JPanel jPanel2 = new JPanel();
368
369   JPanel jPanel3 = new JPanel();
370
371   JPanel jPanel4 = new JPanel();
372
373   BorderLayout borderLayout1 = new BorderLayout();
374
375   BorderLayout borderLayout2 = new BorderLayout();
376
377   BorderLayout borderLayout3 = new BorderLayout();
378
379   public void close_actionPerformed(ActionEvent e)
380   {
381     try
382     {
383       frame.setClosed(true);
384     } catch (Exception ex)
385     {
386     }
387   }
388
389   public void ok_actionPerformed()
390   {
391     database.setEnabled(false);
392     textArea.setEnabled(false);
393     ok.setEnabled(false);
394     close.setEnabled(false);
395
396     Thread worker = new Thread(this);
397     worker.start();
398   }
399
400   private void resetDialog()
401   {
402     database.setEnabled(true);
403     textArea.setEnabled(true);
404     ok.setEnabled(true);
405     close.setEnabled(true);
406   }
407
408   public void run()
409   {
410     String error = "";
411     if (!database.hasSelection())
412     {
413       error += "Please select the source database\n";
414     }
415     // TODO: make this transformation more configurable
416     com.stevesoft.pat.Regex empty;
417     if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
418     {
419       empty = new com.stevesoft.pat.Regex(
420       // replace commas and spaces with a semicolon
421               "(\\s|[,; ])+", ";");
422     }
423     else
424     {
425       // just turn spaces and semicolons into single semicolons
426       empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
427     }
428     textArea.setText(empty.replaceAll(textArea.getText()));
429     // see if there's anthing to search with
430     if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
431             .getText()))
432     {
433       error += "Please enter a (semi-colon separated list of) database id(s)";
434     }
435     if (error.length() > 0)
436     {
437       showErrorMessage(error);
438       resetDialog();
439       return;
440     }
441     ArrayList<String> aresultq = new ArrayList<String>();
442     ArrayList<AlignmentI> aresult = new ArrayList<AlignmentI>();
443     DbSourceProxy proxy = database.getSelectedSources().get(0);
444     Enumeration en = new StringTokenizer(textArea.getText(), ";");
445     boolean isAliSource = false;
446     try
447     {
448       guiWindow.setProgressBar(
449               "Fetching Sequences from " + proxy.getDbName(), Thread
450                       .currentThread().hashCode());
451       isAliSource = proxy.isA(DBRefSource.ALIGNMENTDB);
452       if (proxy.getAccessionSeparator() == null)
453       {
454         while (en.hasMoreElements())
455         {
456           String item = (String) en.nextElement();
457           try
458           {
459             if (aresult != null)
460             {
461               try
462               {
463                 // give the server a chance to breathe
464                 Thread.sleep(5);
465               } catch (Exception e)
466               {
467                 //
468               }
469
470             }
471
472             AlignmentI indres = null;
473             try
474             {
475               indres = proxy.getSequenceRecords(item);
476             } catch (OutOfMemoryError oome)
477             {
478               new OOMWarning("fetching " + item + " from "
479                       + proxy.getDbName(), oome, this);
480             }
481             if (indres != null)
482             {
483               aresultq.add(item);
484               aresult.add(indres);
485             }
486           } catch (Exception e)
487           {
488             jalview.bin.Cache.log.info("Error retrieving " + item
489                     + " from " + proxy.getDbName(), e);
490           }
491         }
492       }
493       else
494       {
495         StringBuffer multiacc = new StringBuffer();
496         while (en.hasMoreElements())
497         {
498           multiacc.append(en.nextElement());
499           if (en.hasMoreElements())
500           {
501             multiacc.append(proxy.getAccessionSeparator());
502           }
503         }
504         try
505         {
506           aresultq.add(multiacc.toString());
507           aresult.add(proxy.getSequenceRecords(multiacc.toString()));
508         } catch (OutOfMemoryError oome)
509         {
510           new OOMWarning("fetching " + multiacc + " from "
511                   + database.getSelectedItem(), oome, this);
512         }
513
514       }
515
516     } catch (Exception e)
517     {
518       showErrorMessage("Error retrieving " + textArea.getText() + " from "
519               + database.getSelectedItem());
520       // error +="Couldn't retrieve sequences from "+database.getSelectedItem();
521       System.err.println("Retrieval failed for source ='"
522               + database.getSelectedItem() + "' and query\n'"
523               + textArea.getText() + "'\n");
524       e.printStackTrace();
525     } catch (OutOfMemoryError e)
526     {
527       // resets dialog box - so we don't use OOMwarning here.
528       showErrorMessage("Out of Memory when retrieving "
529               + textArea.getText()
530               + " from "
531               + database.getSelectedItem()
532               + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
533       e.printStackTrace();
534     } catch (Error e)
535     {
536       showErrorMessage("Serious Error retrieving " + textArea.getText()
537               + " from " + database.getSelectedItem());
538       e.printStackTrace();
539     }
540     if (aresult != null && aresult.size() > 0)
541     {
542       AlignmentI ar = null;
543       if (isAliSource)
544       {
545         // new window for each result
546         while (aresult.size() > 0)
547         {
548           parseResult(aresult.remove(0), aresultq.remove(0) + " "
549                   + getDefaultRetrievalTitle(), null);
550         }
551       }
552       else
553       {
554         // concatenate all results in one window
555         while (aresult.size() > 0)
556         {
557           if (ar == null)
558           {
559             ar = aresult.remove(0);
560           }
561           else
562           {
563             ar.append(aresult.remove(0));
564           }
565           ;
566         }
567         parseResult(ar, null, null);
568       }
569     }
570     // only remove visual delay after we finished parsing.
571     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
572     resetDialog();
573   }
574
575   AlignmentI parseResult(String result, String title)
576   {
577     String format = new IdentifyFile().Identify(result, "Paste");
578     Alignment sequences = null;
579     if (FormatAdapter.isValidFormat(format))
580     {
581       sequences = null;
582       try
583       {
584         sequences = new FormatAdapter().readFile(result.toString(),
585                 "Paste", format);
586       } catch (Exception ex)
587       {
588       }
589
590       if (sequences != null)
591       {
592         return parseResult(sequences, title, format);
593       }
594     }
595     else
596     {
597       showErrorMessage("Error retrieving " + textArea.getText() + " from "
598               + database.getSelectedItem());
599     }
600
601     return null;
602   }
603
604   /**
605    * 
606    * @return a standard title for any results retrieved using the currently
607    *         selected source and settings
608    */
609   public String getDefaultRetrievalTitle()
610   {
611     return "Retrieved from " + database.getSelectedItem();
612   }
613
614   AlignmentI parseResult(AlignmentI al, String title,
615           String currentFileFormat)
616   {
617
618     if (al != null && al.getHeight() > 0)
619     {
620       if (alignFrame == null)
621       {
622         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
623                 AlignFrame.DEFAULT_HEIGHT);
624         if (currentFileFormat != null)
625         {
626           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
627           // FORMAT FOR
628           // NON-FormatAdapter Sourced
629           // Alignments?
630         }
631
632         if (title == null)
633         {
634           title = getDefaultRetrievalTitle();
635         }
636         SequenceFeature[] sfs = null;
637         for (Enumeration sq = al.getSequences().elements(); sq
638                 .hasMoreElements();)
639         {
640           if ((sfs = ((SequenceI) sq.nextElement()).getDatasetSequence()
641                   .getSequenceFeatures()) != null)
642           {
643             if (sfs.length > 0)
644             {
645               af.setShowSeqFeatures(true);
646               break;
647             }
648           }
649
650         }
651         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
652                 AlignFrame.DEFAULT_HEIGHT);
653
654         af.statusBar.setText("Successfully pasted alignment file");
655
656         try
657         {
658           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
659                   false));
660         } catch (Exception ex)
661         {
662         }
663       }
664       else
665       {
666         for (int i = 0; i < al.getHeight(); i++)
667         {
668           alignFrame.viewport.getAlignment().addSequence(
669                   al.getSequenceAt(i)); // this
670           // also
671           // creates
672           // dataset
673           // sequence
674           // entries
675         }
676         alignFrame.viewport.setEndSeq(alignFrame.viewport.getAlignment()
677                 .getHeight());
678         alignFrame.viewport.getAlignment().getWidth();
679         alignFrame.viewport.firePropertyChange("alignment", null,
680                 alignFrame.viewport.getAlignment().getSequences());
681       }
682     }
683     return al;
684   }
685
686   void showErrorMessage(final String error)
687   {
688     resetDialog();
689     javax.swing.SwingUtilities.invokeLater(new Runnable()
690     {
691       public void run()
692       {
693         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
694                 "Error Retrieving Data", JOptionPane.WARNING_MESSAGE);
695       }
696     });
697   }
698 }