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