Merge branch 'codereviews/JAL-1990_IProgressIndicator_jalview.structure' into patch...
[jalview.git] / src / jalview / gui / ChimeraViewFrame.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.FeatureRenderer;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.ext.rbvi.chimera.ChimeraCommands;
29 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
30 import jalview.gui.StructureViewer.ViewerType;
31 import jalview.io.DataSourceType;
32 import jalview.io.StructureFile;
33 import jalview.structures.models.AAStructureBindingModel;
34 import jalview.util.BrowserLauncher;
35 import jalview.util.MessageManager;
36 import jalview.util.Platform;
37 import jalview.ws.dbsources.Pdb;
38
39 import java.awt.event.ActionEvent;
40 import java.awt.event.ActionListener;
41 import java.awt.event.MouseAdapter;
42 import java.awt.event.MouseEvent;
43 import java.io.File;
44 import java.io.FileInputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.util.ArrayList;
48 import java.util.Collections;
49 import java.util.List;
50 import java.util.Random;
51
52 import javax.swing.JCheckBoxMenuItem;
53 import javax.swing.JInternalFrame;
54 import javax.swing.JMenu;
55 import javax.swing.JMenuItem;
56 import javax.swing.event.InternalFrameAdapter;
57 import javax.swing.event.InternalFrameEvent;
58
59 /**
60  * GUI elements for handling an external chimera display
61  * 
62  * @author jprocter
63  *
64  */
65 public class ChimeraViewFrame extends StructureViewerBase
66 {
67   private JalviewChimeraBinding jmb;
68
69   private IProgressIndicator progressBar = null;
70
71   /*
72    * Path to Chimera session file. This is set when an open Jalview/Chimera
73    * session is saved, or on restore from a Jalview project (if it holds the
74    * filename of any saved Chimera sessions).
75    */
76   private String chimeraSessionFile = null;
77
78   private Random random = new Random();
79
80   private int myWidth = 500;
81
82   private int myHeight = 150;
83
84   /**
85    * Initialise menu options.
86    */
87   @Override
88   protected void initMenus()
89   {
90     super.initMenus();
91
92     viewerActionMenu.setText(MessageManager.getString("label.chimera"));
93
94     viewerColour
95             .setText(MessageManager.getString("label.colour_with_chimera"));
96     viewerColour.setToolTipText(MessageManager
97             .getString("label.let_chimera_manage_structure_colours"));
98
99     helpItem.setText(MessageManager.getString("label.chimera_help"));
100     savemenu.setVisible(false); // not yet implemented
101     viewMenu.add(fitToWindow);
102
103     /*
104      * exchange of Jalview features and Chimera attributes is for now
105      * an optionally enabled experimental feature
106      */
107     if (Desktop.instance.showExperimental())
108     {
109       JMenuItem writeFeatures = new JMenuItem(
110               MessageManager.getString("label.create_chimera_attributes"));
111       writeFeatures.setToolTipText(MessageManager
112               .getString("label.create_chimera_attributes_tip"));
113       writeFeatures.addActionListener(new ActionListener()
114       {
115         @Override
116         public void actionPerformed(ActionEvent e)
117         {
118           sendFeaturesToChimera();
119         }
120       });
121       viewerActionMenu.add(writeFeatures);
122
123       final JMenu fetchAttributes = new JMenu(
124               MessageManager.getString("label.fetch_chimera_attributes"));
125       fetchAttributes.setToolTipText(MessageManager
126               .getString("label.fetch_chimera_attributes_tip"));
127       fetchAttributes.addMouseListener(new MouseAdapter()
128       {
129
130         @Override
131         public void mouseEntered(MouseEvent e)
132         {
133           buildAttributesMenu(fetchAttributes);
134         }
135       });
136       viewerActionMenu.add(fetchAttributes);
137     }
138   }
139
140   /**
141    * Query Chimera for its residue attribute names and add them as items off the
142    * attributes menu
143    * 
144    * @param attributesMenu
145    */
146   protected void buildAttributesMenu(JMenu attributesMenu)
147   {
148     List<String> atts = jmb.sendChimeraCommand("list resattr", true);
149     if (atts == null)
150     {
151       return;
152     }
153     attributesMenu.removeAll();
154     Collections.sort(atts);
155     for (String att : atts)
156     {
157       final String attName = att.split(" ")[1];
158
159       /*
160        * ignore 'jv_*' attributes, as these are Jalview features that have
161        * been transferred to residue attributes in Chimera!
162        */
163       if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
164       {
165         JMenuItem menuItem = new JMenuItem(attName);
166         menuItem.addActionListener(new ActionListener()
167         {
168           @Override
169           public void actionPerformed(ActionEvent e)
170           {
171             getChimeraAttributes(attName);
172           }
173         });
174         attributesMenu.add(menuItem);
175       }
176     }
177   }
178
179   /**
180    * Read residues in Chimera with the given attribute name, and set as features
181    * on the corresponding sequence positions (if any)
182    * 
183    * @param attName
184    */
185   protected void getChimeraAttributes(String attName)
186   {
187     jmb.copyStructureAttributesToFeatures(attName, getAlignmentPanel());
188   }
189
190   /**
191    * Send a command to Chimera to create residue attributes for Jalview features
192    * <p>
193    * The syntax is: setattr r <attName> <attValue> <atomSpec>
194    * <p>
195    * For example: setattr r jv:chain "Ferredoxin-1, Chloroplastic" #0:94.A
196    */
197   protected void sendFeaturesToChimera()
198   {
199     int count = jmb.sendFeaturesToViewer(getAlignmentPanel());
200     statusBar.setText(
201             MessageManager.formatMessage("label.attributes_set", count));
202   }
203
204   /**
205    * add a single PDB structure to a new or existing Chimera view
206    * 
207    * @param pdbentry
208    * @param seq
209    * @param chains
210    * @param ap
211    */
212   public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
213           String[] chains, final AlignmentPanel ap)
214   {
215     this();
216     String pdbId = pdbentry.getId();
217
218     /*
219      * If the PDB file is already loaded, the user may just choose to add to an
220      * existing viewer (or cancel)
221      */
222     if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
223     {
224       return;
225     }
226
227     /*
228      * Check if there are other Chimera views involving this alignment and give
229      * user the option to add and align this molecule to one of them (or cancel)
230      */
231     if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
232     {
233       return;
234     }
235
236     /*
237      * If the options above are declined or do not apply, show the structure in
238      * a new viewer
239      */
240     openNewChimera(ap, new PDBEntry[] { pdbentry },
241             new SequenceI[][]
242             { seq });
243   }
244
245   /**
246    * Create a helper to manage progress bar display
247    */
248   protected void createProgressBar()
249   {
250     if (progressBar == null)
251     {
252       progressBar = new ProgressBar(statusPanel, statusBar);
253     }
254   }
255
256   private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
257           SequenceI[][] seqs)
258   {
259     createProgressBar();
260     jmb = new JalviewChimeraBindingModel(this,
261             ap.getStructureSelectionManager(), pdbentrys, seqs, null);
262     addAlignmentPanel(ap);
263     useAlignmentPanelForColourbyseq(ap);
264
265     if (pdbentrys.length > 1)
266     {
267       alignAddedStructures = true;
268       useAlignmentPanelForSuperposition(ap);
269     }
270     jmb.setColourBySequence(true);
271     setSize(myWidth, myHeight);
272     initMenus();
273
274     addingStructures = false;
275     worker = new Thread(this);
276     worker.start();
277
278     this.addInternalFrameListener(new InternalFrameAdapter()
279     {
280       @Override
281       public void internalFrameClosing(
282               InternalFrameEvent internalFrameEvent)
283       {
284         closeViewer(false);
285       }
286     });
287
288   }
289
290   /**
291    * Create a new viewer from saved session state data including Chimera session
292    * file
293    * 
294    * @param chimeraSessionFile
295    * @param alignPanel
296    * @param pdbArray
297    * @param seqsArray
298    * @param colourByChimera
299    * @param colourBySequence
300    * @param newViewId
301    */
302   public ChimeraViewFrame(String chimeraSessionFile,
303           AlignmentPanel alignPanel, PDBEntry[] pdbArray,
304           SequenceI[][] seqsArray, boolean colourByChimera,
305           boolean colourBySequence, String newViewId)
306   {
307     this();
308     setViewId(newViewId);
309     this.chimeraSessionFile = chimeraSessionFile;
310     openNewChimera(alignPanel, pdbArray, seqsArray);
311     if (colourByChimera)
312     {
313       jmb.setColourBySequence(false);
314       seqColour.setSelected(false);
315       viewerColour.setSelected(true);
316     }
317     else if (colourBySequence)
318     {
319       jmb.setColourBySequence(true);
320       seqColour.setSelected(true);
321       viewerColour.setSelected(false);
322     }
323   }
324
325   /**
326    * create a new viewer containing several structures superimposed using the
327    * given alignPanel.
328    * 
329    * @param pe
330    * @param seqs
331    * @param ap
332    */
333   public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
334           AlignmentPanel ap)
335   {
336     this();
337     openNewChimera(ap, pe, seqs);
338   }
339
340   /**
341    * Default constructor
342    */
343   public ChimeraViewFrame()
344   {
345     super();
346
347     /*
348      * closeViewer will decide whether or not to close this frame
349      * depending on whether user chooses to Cancel or not
350      */
351     setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
352   }
353
354   /**
355    * Returns a list of any Chimera viewers in the desktop. The list is
356    * restricted to those linked to the given alignment panel if it is not null.
357    */
358   @Override
359   protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
360   {
361     List<StructureViewerBase> result = new ArrayList<>();
362     JInternalFrame[] frames = Desktop.instance.getAllFrames();
363
364     for (JInternalFrame frame : frames)
365     {
366       if (frame instanceof ChimeraViewFrame)
367       {
368         if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
369         {
370           result.add((StructureViewerBase) frame);
371         }
372       }
373     }
374     return result;
375   }
376
377   /**
378    * Launch Chimera. If we have a chimera session file name, send Chimera the
379    * command to open its saved session file.
380    */
381   void initChimera()
382   {
383     jmb.setFinishedInit(false);
384     Desktop.addInternalFrame(this,
385             jmb.getViewerTitle(getViewerName(), true), getBounds().width,
386             getBounds().height);
387
388     if (!jmb.launchChimera())
389     {
390       JvOptionPane.showMessageDialog(Desktop.desktop,
391               MessageManager.getString("label.chimera_failed"),
392               MessageManager.getString("label.error_loading_file"),
393               JvOptionPane.ERROR_MESSAGE);
394       this.dispose();
395       return;
396     }
397
398     if (this.chimeraSessionFile != null)
399     {
400       boolean opened = jmb.openSession(chimeraSessionFile);
401       if (!opened)
402       {
403         System.err.println("An error occurred opening Chimera session file "
404                 + chimeraSessionFile);
405       }
406     }
407
408     jmb.startChimeraListener();
409   }
410
411   /**
412    * Show only the selected chain(s) in the viewer
413    */
414   @Override
415   void showSelectedChains()
416   {
417     List<String> toshow = new ArrayList<>();
418     for (int i = 0; i < chainMenu.getItemCount(); i++)
419     {
420       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
421       {
422         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
423         if (item.isSelected())
424         {
425           toshow.add(item.getText());
426         }
427       }
428     }
429     jmb.showChains(toshow);
430   }
431
432   /**
433    * Close down this instance of Jalview's Chimera viewer, giving the user the
434    * option to close the associated Chimera window (process). They may wish to
435    * keep it open until they have had an opportunity to save any work.
436    * 
437    * @param closeChimera
438    *          if true, close any linked Chimera process; if false, prompt first
439    */
440   @Override
441   public void closeViewer(boolean closeChimera)
442   {
443     if (jmb != null && jmb.isChimeraRunning())
444     {
445       if (!closeChimera)
446       {
447         String prompt = MessageManager
448                 .formatMessage("label.confirm_close_chimera", new Object[]
449                 { jmb.getViewerTitle(getViewerName(), false) });
450         prompt = JvSwingUtils.wrapTooltip(true, prompt);
451         int confirm = JvOptionPane.showConfirmDialog(this, prompt,
452                 MessageManager.getString("label.close_viewer"),
453                 JvOptionPane.YES_NO_CANCEL_OPTION);
454         /*
455          * abort closure if user hits escape or Cancel
456          */
457         if (confirm == JvOptionPane.CANCEL_OPTION
458                 || confirm == JvOptionPane.CLOSED_OPTION)
459         {
460           return;
461         }
462         closeChimera = confirm == JvOptionPane.YES_OPTION;
463       }
464       jmb.closeViewer(closeChimera);
465     }
466     setAlignmentPanel(null);
467     _aps.clear();
468     _alignwith.clear();
469     _colourwith.clear();
470     // TODO: check for memory leaks where instance isn't finalised because jmb
471     // holds a reference to the window
472     jmb = null;
473     dispose();
474   }
475
476   /**
477    * Open any newly added PDB structures in Chimera, having first fetched data
478    * from PDB (if not already saved).
479    */
480   @Override
481   public void run()
482   {
483     _started = true;
484     // todo - record which pdbids were successfully imported.
485     StringBuilder errormsgs = new StringBuilder(128);
486     StringBuilder files = new StringBuilder(128);
487     List<PDBEntry> filePDB = new ArrayList<>();
488     List<Integer> filePDBpos = new ArrayList<>();
489     PDBEntry thePdbEntry = null;
490     StructureFile pdb = null;
491     try
492     {
493       String[] curfiles = jmb.getStructureFiles(); // files currently in viewer
494       // TODO: replace with reference fetching/transfer code (validate PDBentry
495       // as a DBRef?)
496       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
497       {
498         String file = null;
499         thePdbEntry = jmb.getPdbEntry(pi);
500         if (thePdbEntry.getFile() == null)
501         {
502           /*
503            * Retrieve PDB data, save to file, attach to PDBEntry
504            */
505           file = fetchPdbFile(thePdbEntry);
506           if (file == null)
507           {
508             errormsgs.append("'" + thePdbEntry.getId() + "' ");
509           }
510         }
511         else
512         {
513           /*
514            * Got file already - ignore if already loaded in Chimera.
515            */
516           file = new File(thePdbEntry.getFile()).getAbsoluteFile()
517                   .getPath();
518           if (curfiles != null && curfiles.length > 0)
519           {
520             addingStructures = true; // already files loaded.
521             for (int c = 0; c < curfiles.length; c++)
522             {
523               if (curfiles[c].equals(file))
524               {
525                 file = null;
526                 break;
527               }
528             }
529           }
530         }
531         if (file != null)
532         {
533           filePDB.add(thePdbEntry);
534           filePDBpos.add(Integer.valueOf(pi));
535           files.append(" \"" + Platform.escapeString(file) + "\"");
536         }
537       }
538     } catch (OutOfMemoryError oomerror)
539     {
540       new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
541               oomerror);
542     } catch (Exception ex)
543     {
544       ex.printStackTrace();
545       errormsgs.append(
546               "When retrieving pdbfiles for '" + thePdbEntry.getId() + "'");
547     }
548     if (errormsgs.length() > 0)
549     {
550
551       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
552               MessageManager.formatMessage(
553                       "label.pdb_entries_couldnt_be_retrieved", new Object[]
554                       { errormsgs.toString() }),
555               MessageManager.getString("label.couldnt_load_file"),
556               JvOptionPane.ERROR_MESSAGE);
557     }
558
559     if (files.length() > 0)
560     {
561       jmb.setFinishedInit(false);
562       if (!addingStructures)
563       {
564         try
565         {
566           initChimera();
567         } catch (Exception ex)
568         {
569           Cache.log.error("Couldn't open Chimera viewer!", ex);
570         }
571       }
572       int num = -1;
573       for (PDBEntry pe : filePDB)
574       {
575         num++;
576         if (pe.getFile() != null)
577         {
578           try
579           {
580             int pos = filePDBpos.get(num).intValue();
581             long startTime = startProgressBar(getViewerName() + " "
582                     + MessageManager.getString("status.opening_file_for")
583                     + " " + pe.getId());
584             jmb.openFile(pe);
585             jmb.addSequence(pos, jmb.getSequence()[pos]);
586             File fl = new File(pe.getFile());
587             DataSourceType protocol = DataSourceType.URL;
588             try
589             {
590               if (fl.exists())
591               {
592                 protocol = DataSourceType.FILE;
593               }
594             } catch (Throwable e)
595             {
596             } finally
597             {
598               stopProgressBar("", startTime);
599             }
600             // Explicitly map to the filename used by Chimera ;
601
602             pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
603                     jmb.getChains()[pos], pe.getFile(), protocol,
604                     progressBar);
605             stashFoundChains(pdb, pe.getFile());
606
607           } catch (OutOfMemoryError oomerror)
608           {
609             new OOMWarning(
610                     "When trying to open and map structures from Chimera!",
611                     oomerror);
612           } catch (Exception ex)
613           {
614             Cache.log.error(
615                     "Couldn't open " + pe.getFile() + " in Chimera viewer!",
616                     ex);
617           } finally
618           {
619             Cache.log.debug("File locations are " + files);
620           }
621         }
622       }
623
624       jmb.refreshGUI();
625       jmb.setFinishedInit(true);
626       jmb.setLoadingFromArchive(false);
627
628       /*
629        * ensure that any newly discovered features (e.g. RESNUM)
630        * are added to any open feature settings dialog
631        */
632       FeatureRenderer fr = getBinding().getFeatureRenderer(null);
633       if (fr != null)
634       {
635         fr.featuresAdded();
636       }
637
638       // refresh the sequence colours for the new structure(s)
639       for (AlignmentPanel ap : _colourwith)
640       {
641         jmb.updateColours(ap);
642       }
643       // do superposition if asked to
644       if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
645       {
646         new Thread(new Runnable()
647         {
648           @Override
649           public void run()
650           {
651             alignStructs_withAllAlignPanels();
652           }
653         }).start();
654         alignAddedStructures = false;
655       }
656       addingStructures = false;
657     }
658     _started = false;
659     worker = null;
660   }
661
662   /**
663    * Fetch PDB data and save to a local file. Returns the full path to the file,
664    * or null if fetch fails. TODO: refactor to common with Jmol ? duplication
665    * 
666    * @param processingEntry
667    * @return
668    * @throws Exception
669    */
670
671   private void stashFoundChains(StructureFile pdb, String file)
672   {
673     for (int i = 0; i < pdb.getChains().size(); i++)
674     {
675       String chid = new String(
676               pdb.getId() + ":" + pdb.getChains().elementAt(i).id);
677       jmb.getChainNames().add(chid);
678       jmb.getChainFile().put(chid, file);
679     }
680   }
681
682   private String fetchPdbFile(PDBEntry processingEntry) throws Exception
683   {
684     // FIXME: this is duplicated code with Jmol frame ?
685     String filePath = null;
686     Pdb pdbclient = new Pdb();
687     AlignmentI pdbseq = null;
688     String pdbid = processingEntry.getId();
689     long handle = System.currentTimeMillis()
690             + Thread.currentThread().hashCode();
691
692     /*
693      * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
694      */
695     String msg = MessageManager.formatMessage("status.fetching_pdb",
696             new Object[]
697             { pdbid });
698     getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
699     // long hdl = startProgressBar(MessageManager.formatMessage(
700     // "status.fetching_pdb", new Object[]
701     // { pdbid }));
702     try
703     {
704       pdbseq = pdbclient.getSequenceRecords(pdbid);
705     } catch (OutOfMemoryError oomerror)
706     {
707       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
708     } finally
709     {
710       msg = pdbid + " " + MessageManager.getString("label.state_completed");
711       getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
712       // stopProgressBar(msg, hdl);
713     }
714     /*
715      * If PDB data were saved and are not invalid (empty alignment), return the
716      * file path.
717      */
718     if (pdbseq != null && pdbseq.getHeight() > 0)
719     {
720       // just use the file name from the first sequence's first PDBEntry
721       filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
722               .elementAt(0).getFile()).getAbsolutePath();
723       processingEntry.setFile(filePath);
724     }
725     return filePath;
726   }
727
728   /**
729    * Convenience method to update the progress bar if there is one. Be sure to
730    * call stopProgressBar with the returned handle to remove the message.
731    * 
732    * @param msg
733    * @param handle
734    */
735   public long startProgressBar(String msg)
736   {
737     // TODO would rather have startProgress/stopProgress as the
738     // IProgressIndicator interface
739     long tm = random.nextLong();
740     if (progressBar != null)
741     {
742       progressBar.setProgressBar(msg, tm);
743     }
744     return tm;
745   }
746
747   /**
748    * End the progress bar with the specified handle, leaving a message (if not
749    * null) on the status bar
750    * 
751    * @param msg
752    * @param handle
753    */
754   public void stopProgressBar(String msg, long handle)
755   {
756     if (progressBar != null)
757     {
758       progressBar.setProgressBar(msg, handle);
759     }
760   }
761
762   @Override
763   public void eps_actionPerformed(ActionEvent e)
764   {
765     throw new Error(MessageManager
766             .getString("error.eps_generation_not_implemented"));
767   }
768
769   @Override
770   public void png_actionPerformed(ActionEvent e)
771   {
772     throw new Error(MessageManager
773             .getString("error.png_generation_not_implemented"));
774   }
775
776   @Override
777   public void showHelp_actionPerformed(ActionEvent actionEvent)
778   {
779     try
780     {
781       BrowserLauncher
782               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
783     } catch (IOException ex)
784     {
785     }
786   }
787
788   @Override
789   public AAStructureBindingModel getBinding()
790   {
791     return jmb;
792   }
793
794   /**
795    * Ask Chimera to save its session to the designated file path, or to a
796    * temporary file if the path is null. Returns the file path if successful,
797    * else null.
798    * 
799    * @param filepath
800    * @see getStateInfo
801    */
802   protected String saveSession(String filepath)
803   {
804     String pathUsed = filepath;
805     try
806     {
807       if (pathUsed == null)
808       {
809         File tempFile = File.createTempFile("chimera", ".py");
810         tempFile.deleteOnExit();
811         pathUsed = tempFile.getPath();
812       }
813       boolean result = jmb.saveSession(pathUsed);
814       if (result)
815       {
816         this.chimeraSessionFile = pathUsed;
817         return pathUsed;
818       }
819     } catch (IOException e)
820     {
821     }
822     return null;
823   }
824
825   /**
826    * Returns a string representing the state of the Chimera session. This is
827    * done by requesting Chimera to save its session to a temporary file, then
828    * reading the file contents. Returns an empty string on any error.
829    */
830   @Override
831   public String getStateInfo()
832   {
833     String sessionFile = saveSession(null);
834     if (sessionFile == null)
835     {
836       return "";
837     }
838     InputStream is = null;
839     try
840     {
841       File f = new File(sessionFile);
842       byte[] bytes = new byte[(int) f.length()];
843       is = new FileInputStream(sessionFile);
844       is.read(bytes);
845       return new String(bytes);
846     } catch (IOException e)
847     {
848       return "";
849     } finally
850     {
851       if (is != null)
852       {
853         try
854         {
855           is.close();
856         } catch (IOException e)
857         {
858           // ignore
859         }
860       }
861     }
862   }
863
864   @Override
865   protected void fitToWindow_actionPerformed()
866   {
867     jmb.focusView();
868   }
869
870   @Override
871   public ViewerType getViewerType()
872   {
873     return ViewerType.CHIMERA;
874   }
875
876   @Override
877   protected String getViewerName()
878   {
879     return "Chimera";
880   }
881
882   /**
883    * Sends commands to align structures according to associated alignment(s).
884    * 
885    * @return
886    */
887   @Override
888   protected String alignStructs_withAllAlignPanels()
889   {
890     String reply = super.alignStructs_withAllAlignPanels();
891     if (reply != null)
892     {
893       statusBar.setText("Superposition failed: " + reply);
894     }
895     return reply;
896   }
897
898   @Override
899   protected IProgressIndicator getIProgressIndicator()
900   {
901     return progressBar;
902   }
903 }