ab78ad322ec0a6d866b8110648f1fa70fedbcfe5
[jalview.git] / src / jalview / gui / SequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.FeatureSettingsModelI;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.service.pdb.PDBFTSPanel;
30 import jalview.fts.service.uniprot.UniprotFTSPanel;
31 import jalview.io.gff.SequenceOntologyI;
32 import jalview.util.DBRefUtils;
33 import jalview.util.MessageManager;
34 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
35 import jalview.ws.seqfetcher.DbSourceProxy;
36
37 import java.awt.BorderLayout;
38 import java.awt.Font;
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.KeyAdapter;
42 import java.awt.event.KeyEvent;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Iterator;
46 import java.util.List;
47
48 import javax.swing.JButton;
49 import javax.swing.JCheckBox;
50 import javax.swing.JInternalFrame;
51 import javax.swing.JLabel;
52 import javax.swing.JOptionPane;
53 import javax.swing.JPanel;
54 import javax.swing.JScrollPane;
55 import javax.swing.JTextArea;
56 import javax.swing.SwingConstants;
57 import javax.swing.tree.DefaultMutableTreeNode;
58
59 public class SequenceFetcher extends JPanel implements Runnable
60 {
61   JLabel dbeg = new JLabel();
62
63   JDatabaseTree database;
64
65   JButton databaseButt;
66
67   JLabel jLabel1 = new JLabel();
68
69   JCheckBox replacePunctuation = new JCheckBox();
70
71   JButton ok = new JButton();
72
73   JButton clear = new JButton();
74
75   JButton example = new JButton();
76
77   JButton close = new JButton();
78
79   JPanel jPanel1 = new JPanel();
80
81   JTextArea textArea = new JTextArea();
82
83   JScrollPane jScrollPane1 = new JScrollPane();
84
85   JPanel jPanel2 = new JPanel();
86
87   JPanel jPanel3 = new JPanel();
88
89   JPanel jPanel4 = new JPanel();
90
91   BorderLayout borderLayout1 = new BorderLayout();
92
93   BorderLayout borderLayout2 = new BorderLayout();
94
95   BorderLayout borderLayout3 = new BorderLayout();
96
97   JInternalFrame frame;
98
99   IProgressIndicator guiWindow;
100
101   AlignFrame alignFrame;
102
103   StringBuffer result;
104
105   final String noDbSelected = "-- Select Database --";
106
107   private static jalview.ws.SequenceFetcher sfetch = null;
108
109   private static long lastDasSourceRegistry = -3;
110
111   private static DasSourceRegistryI dasRegistry = null;
112
113   private static boolean _initingFetcher = false;
114
115   private static Thread initingThread = null;
116
117   int debounceTrap = 0;
118
119   public JTextArea getTextArea()
120   {
121     return textArea;
122   }
123
124   /**
125    * Blocking method that initialises and returns the shared instance of the
126    * SequenceFetcher client
127    * 
128    * @param guiWindow
129    *          - where the initialisation delay message should be shown
130    * @return the singleton instance of the sequence fetcher client
131    */
132   public static jalview.ws.SequenceFetcher getSequenceFetcherSingleton(
133           final IProgressIndicator guiWindow)
134   {
135     if (_initingFetcher && initingThread != null && initingThread.isAlive())
136     {
137       if (guiWindow != null)
138       {
139         guiWindow
140                 .setProgressBar(
141                         MessageManager
142                                 .getString("status.waiting_sequence_database_fetchers_init"),
143                         Thread.currentThread().hashCode());
144       }
145       // initting happening on another thread - so wait around to see if it
146       // finishes.
147       while (_initingFetcher && initingThread != null
148               && initingThread.isAlive())
149       {
150         try
151         {
152           Thread.sleep(10);
153         } catch (Exception e)
154         {
155         }
156         ;
157       }
158       if (guiWindow != null)
159       {
160         guiWindow
161                 .setProgressBar(
162                         MessageManager
163                                 .getString("status.waiting_sequence_database_fetchers_init"),
164                         Thread.currentThread().hashCode());
165       }
166     }
167     if (sfetch == null
168             || dasRegistry != Cache.getDasSourceRegistry()
169             || lastDasSourceRegistry != (Cache.getDasSourceRegistry()
170                     .getDasRegistryURL() + Cache
171                     .getDasSourceRegistry().getLocalSourceString())
172                     .hashCode())
173     {
174       _initingFetcher = true;
175       initingThread = Thread.currentThread();
176       /**
177        * give a visual indication that sequence fetcher construction is occuring
178        */
179       if (guiWindow != null)
180       {
181         guiWindow.setProgressBar(MessageManager
182                 .getString("status.init_sequence_database_fetchers"),
183                 Thread.currentThread().hashCode());
184       }
185       dasRegistry = Cache.getDasSourceRegistry();
186       dasRegistry.refreshSources();
187
188       jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
189       if (guiWindow != null)
190       {
191         guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
192       }
193       lastDasSourceRegistry = (dasRegistry.getDasRegistryURL() + dasRegistry
194               .getLocalSourceString()).hashCode();
195       sfetch = sf;
196       _initingFetcher = false;
197       initingThread = null;
198     }
199     return sfetch;
200   }
201
202   private IProgressIndicator progressIndicator;
203
204   public SequenceFetcher(IProgressIndicator guiIndic)
205   {
206     this.progressIndicator = guiIndic;
207     final SequenceFetcher us = this;
208     // launch initialiser thread
209     Thread sf = new Thread(new Runnable()
210     {
211
212       @Override
213       public void run()
214       {
215         if (getSequenceFetcherSingleton(progressIndicator) != null)
216         {
217           us.initGui(progressIndicator);
218         }
219         else
220         {
221           javax.swing.SwingUtilities.invokeLater(new Runnable()
222           {
223             @Override
224             public void run()
225             {
226               JOptionPane
227                       .showInternalMessageDialog(
228                               Desktop.desktop,
229                               MessageManager
230                                       .getString("warn.couldnt_create_sequence_fetcher_client"),
231                               MessageManager
232                                       .getString("label.couldnt_create_sequence_fetcher"),
233                               JOptionPane.ERROR_MESSAGE);
234             }
235           });
236
237           // raise warning dialog
238         }
239       }
240     });
241     sf.start();
242   }
243
244   private class DatabaseAuthority extends DefaultMutableTreeNode
245   {
246
247   };
248
249   private class DatabaseSource extends DefaultMutableTreeNode
250   {
251
252   };
253
254   /**
255    * called by thread spawned by constructor
256    * 
257    * @param guiWindow
258    */
259   private void initGui(IProgressIndicator guiWindow)
260   {
261     this.guiWindow = guiWindow;
262     if (guiWindow instanceof AlignFrame)
263     {
264       alignFrame = (AlignFrame) guiWindow;
265     }
266     database = new JDatabaseTree(sfetch);
267     try
268     {
269       jbInit();
270     } catch (Exception ex)
271     {
272       ex.printStackTrace();
273     }
274
275     frame = new JInternalFrame();
276     frame.setContentPane(this);
277     if (new jalview.util.Platform().isAMac())
278     {
279       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 240);
280     }
281     else
282     {
283       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 180);
284     }
285   }
286
287   private String getFrameTitle()
288   {
289     return ((alignFrame == null) ? MessageManager
290             .getString("label.new_sequence_fetcher") : MessageManager
291             .getString("label.additional_sequence_fetcher"));
292   }
293
294   private void jbInit() throws Exception
295   {
296     this.setLayout(borderLayout2);
297
298     database.setFont(JvSwingUtils.getLabelFont());
299     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
300     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
301     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
302     jLabel1.setText(MessageManager
303             .getString("label.separate_multiple_accession_ids"));
304
305     replacePunctuation.setHorizontalAlignment(SwingConstants.CENTER);
306     replacePunctuation
307             .setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
308     replacePunctuation.setText(MessageManager
309             .getString("label.replace_commas_semicolons"));
310     ok.setText(MessageManager.getString("action.ok"));
311     ok.addActionListener(new ActionListener()
312     {
313       @Override
314       public void actionPerformed(ActionEvent e)
315       {
316         ok_actionPerformed();
317       }
318     });
319     clear.setText(MessageManager.getString("action.clear"));
320     clear.addActionListener(new ActionListener()
321     {
322       @Override
323       public void actionPerformed(ActionEvent e)
324       {
325         clear_actionPerformed();
326       }
327     });
328
329     example.setText(MessageManager.getString("label.example"));
330     example.addActionListener(new ActionListener()
331     {
332       @Override
333       public void actionPerformed(ActionEvent e)
334       {
335         example_actionPerformed();
336       }
337     });
338     close.setText(MessageManager.getString("action.close"));
339     close.addActionListener(new ActionListener()
340     {
341       @Override
342       public void actionPerformed(ActionEvent e)
343       {
344         close_actionPerformed(e);
345       }
346     });
347     textArea.setFont(JvSwingUtils.getLabelFont());
348     textArea.setLineWrap(true);
349     textArea.addKeyListener(new KeyAdapter()
350     {
351       @Override
352       public void keyPressed(KeyEvent e)
353       {
354         if (e.getKeyCode() == KeyEvent.VK_ENTER)
355         {
356           ok_actionPerformed();
357         }
358       }
359     });
360     jPanel3.setLayout(borderLayout1);
361     borderLayout1.setVgap(5);
362     jPanel1.add(ok);
363     jPanel1.add(example);
364     jPanel1.add(clear);
365     jPanel1.add(close);
366     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
367     jPanel2.setLayout(borderLayout3);
368     databaseButt = database.getDatabaseSelectorButton();
369     databaseButt.setFont(JvSwingUtils.getLabelFont());
370     database.addActionListener(new ActionListener()
371     {
372       @Override
373       public void actionPerformed(ActionEvent e)
374       {
375         debounceTrap++;
376         String currentSelection = database.getSelectedItem();
377
378         if (currentSelection.equalsIgnoreCase("pdb")
379                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
380         {
381           pdbSourceAction();
382         }
383         else if (currentSelection.equalsIgnoreCase("uniprot")
384                 && (database.action == KeyEvent.VK_ENTER || ((debounceTrap % 2) == 0)))
385         {
386           uniprotSourceAction();
387         }
388         else
389         {
390           otherSourceAction();
391         }
392         database.action = -1;
393       }
394     });
395
396     dbeg.setText("");
397     jPanel2.add(databaseButt, java.awt.BorderLayout.NORTH);
398     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
399     JPanel jPanel2a = new JPanel(new BorderLayout());
400     jPanel2a.add(jLabel1, java.awt.BorderLayout.NORTH);
401     jPanel2a.add(replacePunctuation, java.awt.BorderLayout.SOUTH);
402     jPanel2.add(jPanel2a, java.awt.BorderLayout.SOUTH);
403     // jPanel2.setPreferredSize(new Dimension())
404     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
405     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
406     this.add(jPanel3, java.awt.BorderLayout.CENTER);
407     this.add(jPanel2, java.awt.BorderLayout.NORTH);
408     jScrollPane1.getViewport().add(textArea);
409
410   }
411
412   private void pdbSourceAction()
413   {
414     databaseButt.setText(database.getSelectedItem());
415     new PDBFTSPanel(this);
416     frame.dispose();
417   }
418
419   private void uniprotSourceAction()
420   {
421     databaseButt.setText(database.getSelectedItem());
422     new UniprotFTSPanel(this);
423     frame.dispose();
424   }
425   private void otherSourceAction()
426   {
427     try
428     {
429       databaseButt.setText(database.getSelectedItem()
430               + (database.getSelectedSources().size() > 1 ? " (and "
431                       + database.getSelectedSources().size() + " others)"
432                       : ""));
433       String eq = database.getExampleQueries();
434       dbeg.setText(MessageManager.formatMessage(
435               "label.example_query_param", new String[] { eq }));
436       boolean enablePunct = !(eq != null && eq.indexOf(",") > -1);
437       for (DbSourceProxy dbs : database.getSelectedSources())
438       {
439         if (dbs instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
440         {
441           enablePunct = false;
442           break;
443         }
444       }
445       replacePunctuation.setEnabled(enablePunct);
446
447     } catch (Exception ex)
448     {
449       dbeg.setText("");
450       replacePunctuation.setEnabled(true);
451     }
452     jPanel2.repaint();
453   }
454
455   protected void example_actionPerformed()
456   {
457     DbSourceProxy db = null;
458     try
459     {
460       textArea.setText(database.getExampleQueries());
461     } catch (Exception ex)
462     {
463     }
464     jPanel3.repaint();
465   }
466
467   protected void clear_actionPerformed()
468   {
469     textArea.setText("");
470     jPanel3.repaint();
471   }
472
473   public void close_actionPerformed(ActionEvent e)
474   {
475     try
476     {
477       frame.setClosed(true);
478     } catch (Exception ex)
479     {
480     }
481   }
482
483   public void ok_actionPerformed()
484   {
485     databaseButt.setEnabled(false);
486     example.setEnabled(false);
487     textArea.setEnabled(false);
488     ok.setEnabled(false);
489     close.setEnabled(false);
490
491     Thread worker = new Thread(this);
492     worker.start();
493   }
494
495   private void resetDialog()
496   {
497     databaseButt.setEnabled(true);
498     example.setEnabled(true);
499     textArea.setEnabled(true);
500     ok.setEnabled(true);
501     close.setEnabled(true);
502   }
503
504   @Override
505   public void run()
506   {
507     String error = "";
508     if (!database.hasSelection())
509     {
510       error += "Please select the source database\n";
511     }
512     // TODO: make this transformation more configurable
513     com.stevesoft.pat.Regex empty;
514     if (replacePunctuation.isEnabled() && replacePunctuation.isSelected())
515     {
516       empty = new com.stevesoft.pat.Regex(
517       // replace commas and spaces with a semicolon
518               "(\\s|[,; ])+", ";");
519     }
520     else
521     {
522       // just turn spaces and semicolons into single semicolons
523       empty = new com.stevesoft.pat.Regex("(\\s|[; ])+", ";");
524     }
525     textArea.setText(empty.replaceAll(textArea.getText()));
526     // see if there's anthing to search with
527     if (!new com.stevesoft.pat.Regex("[A-Za-z0-9_.]").search(textArea
528             .getText()))
529     {
530       error += "Please enter a (semi-colon separated list of) database id(s)";
531     }
532     if (error.length() > 0)
533     {
534       showErrorMessage(error);
535       resetDialog();
536       return;
537     }
538     // TODO: Refactor to GUI independent code and write tests.
539     // indicate if successive sources should be merged into one alignment.
540     boolean addToLast = false;
541     ArrayList<String> aresultq = new ArrayList<String>(), presultTitle = new ArrayList<String>();
542     ArrayList<AlignmentI> presult = new ArrayList<AlignmentI>(), aresult = new ArrayList<AlignmentI>();
543     Iterator<DbSourceProxy> proxies = database.getSelectedSources()
544             .iterator();
545     String[] qries;
546     List<String> nextfetch = Arrays.asList(qries = textArea.getText()
547             .split(";"));
548     Iterator<String> en = Arrays.asList(new String[0]).iterator();
549     int nqueries = qries.length;
550
551     FeatureSettingsModelI preferredFeatureColours = null;
552     while (proxies.hasNext() && (en.hasNext() || nextfetch.size() > 0))
553     {
554       if (!en.hasNext() && nextfetch.size() > 0)
555       {
556         en = nextfetch.iterator();
557         nqueries = nextfetch.size();
558         // save the remaining queries in the original array
559         qries = nextfetch.toArray(new String[nqueries]);
560         nextfetch = new ArrayList<String>();
561       }
562
563       DbSourceProxy proxy = proxies.next();
564       boolean isAliSource = false;
565       try
566       {
567         // update status
568         guiWindow
569                 .setProgressBar(MessageManager.formatMessage(
570                         "status.fetching_sequence_queries_from",
571                         new String[] {
572                             Integer.valueOf(nqueries).toString(),
573                             proxy.getDbName() }), Thread.currentThread()
574                         .hashCode());
575         isAliSource = proxy.isAlignmentSource();
576         if (proxy.getMaximumQueryCount() == 1)
577         {
578           while (en.hasNext())
579           {
580             String item = en.next();
581             try
582             {
583               if (aresult != null)
584               {
585                 try
586                 {
587                   // give the server a chance to breathe
588                   Thread.sleep(5);
589                 } catch (Exception e)
590                 {
591                   //
592                 }
593
594               }
595
596               AlignmentI indres = null;
597               try
598               {
599                 indres = proxy.getSequenceRecords(item);
600               } catch (OutOfMemoryError oome)
601               {
602                 new OOMWarning("fetching " + item + " from "
603                         + proxy.getDbName(), oome, this);
604               }
605               if (indres != null)
606               {
607                 aresultq.add(item);
608                 aresult.add(indres);
609               }
610               else
611               {
612                 nextfetch.add(item);
613               }
614             } catch (Exception e)
615             {
616               Cache.log.info(
617                       "Error retrieving " + item
618                       + " from " + proxy.getDbName(), e);
619               nextfetch.add(item);
620             }
621           }
622         }
623         else
624         {
625           StringBuffer multiacc = new StringBuffer();
626           ArrayList<String> tosend = new ArrayList<String>();
627           while (en.hasNext())
628           {
629             String nel = en.next();
630             tosend.add(nel);
631             multiacc.append(nel);
632             if (en.hasNext())
633             {
634               multiacc.append(proxy.getAccessionSeparator());
635             }
636           }
637           try
638           {
639             AlignmentI rslt;
640             SequenceI[] rs;
641             List<String> nores = new ArrayList<String>();
642             rslt = proxy.getSequenceRecords(multiacc.toString());
643             if (rslt == null || rslt.getHeight() == 0)
644             {
645               // no results - pass on all queries to next source
646               nextfetch.addAll(tosend);
647             }
648             else
649             {
650               aresultq.add(multiacc.toString());
651               aresult.add(rslt);
652
653               rs = rslt.getSequencesArray();
654               // search for each query in the dbrefs associated with each
655               // sequence
656               // returned.
657               // ones we do not find will be used to query next source (if any)
658               for (String q : tosend)
659               {
660                 DBRefEntry dbr = new DBRefEntry(), found[] = null;
661                 dbr.setSource(proxy.getDbSource());
662                 dbr.setVersion(null);
663                 String accId = proxy.getAccessionIdFromQuery(q);
664                 dbr.setAccessionId(accId);
665                 boolean rfound = false;
666                 for (int r = 0; r < rs.length; r++)
667                 {
668                   if (rs[r] != null)
669                   {
670                     found = DBRefUtils.searchRefs(rs[r].getDBRefs(), accId);
671                     if (found != null && found.length > 0)
672                     {
673                       rfound = true;
674                       rs[r] = null;
675                     }
676                   }
677                 }
678                 if (!rfound)
679                 {
680                   nextfetch.add(q);
681                 }
682               }
683             }
684           } catch (OutOfMemoryError oome)
685           {
686             new OOMWarning("fetching " + multiacc + " from "
687                     + database.getSelectedItem(), oome, this);
688           }
689         }
690
691       } catch (Exception e)
692       {
693         showErrorMessage("Error retrieving " + textArea.getText()
694                 + " from " + database.getSelectedItem());
695         // error
696         // +="Couldn't retrieve sequences from "+database.getSelectedItem();
697         System.err.println("Retrieval failed for source ='"
698                 + database.getSelectedItem() + "' and query\n'"
699                 + textArea.getText() + "'\n");
700         e.printStackTrace();
701       } catch (OutOfMemoryError e)
702       {
703         // resets dialog box - so we don't use OOMwarning here.
704         showErrorMessage("Out of Memory when retrieving "
705                 + textArea.getText()
706                 + " from "
707                 + database.getSelectedItem()
708                 + "\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
709         e.printStackTrace();
710       } catch (Error e)
711       {
712         showErrorMessage("Serious Error retrieving " + textArea.getText()
713                 + " from " + database.getSelectedItem());
714         e.printStackTrace();
715       }
716       // Stack results ready for opening in alignment windows
717       if (aresult != null && aresult.size() > 0)
718       {
719         FeatureSettingsModelI proxyColourScheme = proxy
720                 .getFeatureColourScheme();
721         if (proxyColourScheme != null)
722         {
723           preferredFeatureColours = proxyColourScheme;
724         }
725
726         AlignmentI ar = null;
727         if (isAliSource)
728         {
729           addToLast = false;
730           // new window for each result
731           while (aresult.size() > 0)
732           {
733             presult.add(aresult.remove(0));
734             presultTitle.add(aresultq.remove(0) + " "
735                     + getDefaultRetrievalTitle());
736           }
737         }
738         else
739         {
740           String titl = null;
741           if (addToLast && presult.size() > 0)
742           {
743             ar = presult.remove(presult.size() - 1);
744             titl = presultTitle.remove(presultTitle.size() - 1);
745           }
746           // concatenate all results in one window
747           while (aresult.size() > 0)
748           {
749             if (ar == null)
750             {
751               ar = aresult.remove(0);
752             }
753             else
754             {
755               ar.append(aresult.remove(0));
756             }
757             ;
758           }
759           addToLast = true;
760           presult.add(ar);
761           presultTitle.add(titl);
762         }
763       }
764       guiWindow.setProgressBar(MessageManager
765               .getString("status.finshed_querying"), Thread.currentThread()
766               .hashCode());
767     }
768     guiWindow.setProgressBar(
769             (presult.size() > 0) ? MessageManager
770                     .getString("status.parsing_results") : MessageManager
771                     .getString("status.processing"), Thread.currentThread()
772                     .hashCode());
773     // process results
774     while (presult.size() > 0)
775     {
776       parseResult(presult.remove(0), presultTitle.remove(0), null,
777               preferredFeatureColours);
778     }
779     // only remove visual delay after we finished parsing.
780     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
781     if (nextfetch.size() > 0)
782     {
783       StringBuffer sb = new StringBuffer();
784       sb.append("Didn't retrieve the following "
785               + (nextfetch.size() == 1 ? "query" : nextfetch.size()
786                       + " queries") + ": \n");
787       int l = sb.length(), lr = 0;
788       for (String s : nextfetch)
789       {
790         if (l != sb.length())
791         {
792           sb.append("; ");
793         }
794         if (lr - sb.length() > 40)
795         {
796           sb.append("\n");
797         }
798         sb.append(s);
799       }
800       showErrorMessage(sb.toString());
801     }
802     resetDialog();
803   }
804
805   /**
806    * 
807    * @return a standard title for any results retrieved using the currently
808    *         selected source and settings
809    */
810   public String getDefaultRetrievalTitle()
811   {
812     return "Retrieved from " + database.getSelectedItem();
813   }
814
815   AlignmentI parseResult(AlignmentI al, String title,
816           String currentFileFormat,
817           FeatureSettingsModelI preferredFeatureColours)
818   {
819
820     if (al != null && al.getHeight() > 0)
821     {
822       if (title == null)
823       {
824         title = getDefaultRetrievalTitle();
825       }
826       if (alignFrame == null)
827       {
828         AlignFrame af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
829                 AlignFrame.DEFAULT_HEIGHT);
830         if (currentFileFormat != null)
831         {
832           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT
833           // FORMAT FOR
834           // NON-FormatAdapter Sourced
835           // Alignments?
836         }
837
838         SequenceFeature[] sfs = null;
839         List<SequenceI> alsqs;
840         synchronized (alsqs = al.getSequences())
841         {
842           for (SequenceI sq : alsqs)
843           {
844             if ((sfs = sq.getSequenceFeatures()) != null)
845             {
846               if (sfs.length > 0)
847               {
848                 af.setShowSeqFeatures(true);
849                 break;
850               }
851             }
852
853           }
854         }
855
856         if (preferredFeatureColours != null)
857         {
858           af.getViewport().applyFeaturesStyle(preferredFeatureColours);
859         }
860         if (Cache.getDefault("HIDE_INTRONS", true))
861         {
862           hideIntronsIfPresent(af);
863         }
864
865         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
866                 AlignFrame.DEFAULT_HEIGHT);
867
868         af.statusBar.setText(MessageManager
869                 .getString("label.successfully_pasted_alignment_file"));
870
871         try
872         {
873           af.setMaximum(Cache.getDefault("SHOW_FULLSCREEN",
874                   false));
875         } catch (Exception ex)
876         {
877         }
878       }
879       else
880       {
881         alignFrame.viewport.addAlignment(al, title);
882       }
883     }
884     return al;
885   }
886
887   /**
888    * Hide columns not containing 'exon' features, provided there are exon
889    * features on the alignment
890    * 
891    * @param af
892    */
893   public void hideIntronsIfPresent(AlignFrame af)
894   {
895     boolean hasExons = af.avc.markColumnsContainingFeatures(false, false,
896             false,
897             SequenceOntologyI.EXON);
898     if (hasExons)
899     {
900       af.avc.markColumnsContainingFeatures(true, false, true,
901               SequenceOntologyI.EXON);
902       af.getViewport().hideSelectedColumns();
903     }
904   }
905
906   void showErrorMessage(final String error)
907   {
908     resetDialog();
909     javax.swing.SwingUtilities.invokeLater(new Runnable()
910     {
911       @Override
912       public void run()
913       {
914         JOptionPane.showInternalMessageDialog(Desktop.desktop, error,
915                 MessageManager.getString("label.error_retrieving_data"),
916                 JOptionPane.WARNING_MESSAGE);
917       }
918     });
919   }
920
921   public IProgressIndicator getProgressIndicator()
922   {
923     return progressIndicator;
924   }
925
926   public void setProgressIndicator(IProgressIndicator progressIndicator)
927   {
928     this.progressIndicator = progressIndicator;
929   }
930 }