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