JAL-2287 treat Escape like Cancel in dialog box
[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.bin.Cache;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.ColumnSelection;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
30 import jalview.gui.StructureViewer.ViewerType;
31 import jalview.io.AppletFormatAdapter;
32 import jalview.io.JalviewFileChooser;
33 import jalview.io.JalviewFileView;
34 import jalview.schemes.BuriedColourScheme;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.schemes.HelixColourScheme;
37 import jalview.schemes.HydrophobicColourScheme;
38 import jalview.schemes.PurinePyrimidineColourScheme;
39 import jalview.schemes.StrandColourScheme;
40 import jalview.schemes.TaylorColourScheme;
41 import jalview.schemes.TurnColourScheme;
42 import jalview.schemes.ZappoColourScheme;
43 import jalview.structures.models.AAStructureBindingModel;
44 import jalview.util.MessageManager;
45 import jalview.util.Platform;
46 import jalview.ws.dbsources.Pdb;
47
48 import java.awt.event.ActionEvent;
49 import java.awt.event.ActionListener;
50 import java.awt.event.ItemEvent;
51 import java.awt.event.ItemListener;
52 import java.io.BufferedReader;
53 import java.io.File;
54 import java.io.FileInputStream;
55 import java.io.FileOutputStream;
56 import java.io.FileReader;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.io.PrintWriter;
60 import java.util.ArrayList;
61 import java.util.List;
62 import java.util.Random;
63 import java.util.Vector;
64
65 import javax.swing.JCheckBoxMenuItem;
66 import javax.swing.JColorChooser;
67 import javax.swing.JInternalFrame;
68 import javax.swing.JMenu;
69 import javax.swing.JMenuItem;
70 import javax.swing.JOptionPane;
71 import javax.swing.event.InternalFrameAdapter;
72 import javax.swing.event.InternalFrameEvent;
73 import javax.swing.event.MenuEvent;
74 import javax.swing.event.MenuListener;
75
76 /**
77  * GUI elements for handling an external chimera display
78  * 
79  * @author jprocter
80  *
81  */
82 public class ChimeraViewFrame extends StructureViewerBase
83 {
84   private JalviewChimeraBinding jmb;
85
86   private boolean allChainsSelected = false;
87
88   private IProgressIndicator progressBar = null;
89
90   /*
91    * Path to Chimera session file. This is set when an open Jalview/Chimera
92    * session is saved, or on restore from a Jalview project (if it holds the
93    * filename of any saved Chimera sessions).
94    */
95   private String chimeraSessionFile = null;
96
97   private Random random = new Random();
98
99   /**
100    * Initialise menu options.
101    */
102   private void initMenus()
103   {
104     viewerActionMenu.setText(MessageManager.getString("label.chimera"));
105     viewerColour.setText(MessageManager
106             .getString("label.colour_with_chimera"));
107     viewerColour.setToolTipText(MessageManager
108             .getString("label.let_chimera_manage_structure_colours"));
109     helpItem.setText(MessageManager.getString("label.chimera_help"));
110     seqColour.setSelected(jmb.isColourBySequence());
111     viewerColour.setSelected(!jmb.isColourBySequence());
112     if (_colourwith == null)
113     {
114       _colourwith = new Vector<AlignmentPanel>();
115     }
116     if (_alignwith == null)
117     {
118       _alignwith = new Vector<AlignmentPanel>();
119     }
120
121     // save As not yet implemented
122     savemenu.setVisible(false);
123
124     ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
125             MessageManager.getString("label.colour_by"), this, _colourwith,
126             new ItemListener()
127             {
128               @Override
129               public void itemStateChanged(ItemEvent e)
130               {
131                 if (!seqColour.isSelected())
132                 {
133                   seqColour.doClick();
134                 }
135                 else
136                 {
137                   // update the Chimera display now.
138                   seqColour_actionPerformed(null);
139                 }
140               }
141             });
142     viewMenu.add(seqColourBy);
143     viewMenu.add(fitToWindow);
144
145     final ItemListener handler;
146     JMenu alpanels = new ViewSelectionMenu(
147             MessageManager.getString("label.superpose_with"), this,
148             _alignwith, handler = new ItemListener()
149             {
150               @Override
151               public void itemStateChanged(ItemEvent e)
152               {
153                 alignStructs.setEnabled(_alignwith.size() > 0);
154                 alignStructs.setToolTipText(MessageManager
155                         .formatMessage(
156                                 "label.align_structures_using_linked_alignment_views",
157                                 new Object[] { new Integer(_alignwith
158                                         .size()).toString() }));
159               }
160             });
161     handler.itemStateChanged(null);
162     viewerActionMenu.add(alpanels);
163     viewerActionMenu.addMenuListener(new MenuListener()
164     {
165
166       @Override
167       public void menuSelected(MenuEvent e)
168       {
169         handler.itemStateChanged(null);
170       }
171
172       @Override
173       public void menuDeselected(MenuEvent e)
174       {
175         // TODO Auto-generated method stub
176       }
177
178       @Override
179       public void menuCanceled(MenuEvent e)
180       {
181         // TODO Auto-generated method stub
182       }
183     });
184   }
185
186   /**
187    * add a single PDB structure to a new or existing Chimera view
188    * 
189    * @param pdbentry
190    * @param seq
191    * @param chains
192    * @param ap
193    */
194   public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
195           String[] chains, final AlignmentPanel ap)
196   {
197     this();
198     String pdbId = pdbentry.getId();
199
200     /*
201      * If the PDB file is already loaded, the user may just choose to add to an
202      * existing viewer (or cancel)
203      */
204     if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
205     {
206       return;
207     }
208
209     /*
210      * Check if there are other Chimera views involving this alignment and give
211      * user the option to add and align this molecule to one of them (or cancel)
212      */
213     if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
214     {
215       return;
216     }
217
218     /*
219      * If the options above are declined or do not apply, show the structure in
220      * a new viewer
221      */
222     openNewChimera(ap, new PDBEntry[] { pdbentry },
223             new SequenceI[][] { seq });
224   }
225
226   /**
227    * Create a helper to manage progress bar display
228    */
229   protected void createProgressBar()
230   {
231     if (progressBar == null)
232     {
233       progressBar = new ProgressBar(statusPanel, statusBar);
234     }
235   }
236
237   /**
238    * Answers true if this viewer already involves the given PDB ID
239    */
240   @Override
241   protected boolean hasPdbId(String pdbId)
242   {
243     return jmb.hasPdbId(pdbId);
244   }
245
246   private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
247           SequenceI[][] seqs)
248   {
249     createProgressBar();
250     // FIXME extractChains needs pdbentries to match IDs to PDBEntry(s) on seqs
251     String[][] chains = extractChains(seqs);
252     jmb = new JalviewChimeraBindingModel(this,
253             ap.getStructureSelectionManager(), pdbentrys, seqs, chains,
254             null);
255     addAlignmentPanel(ap);
256     useAlignmentPanelForColourbyseq(ap);
257     if (pdbentrys.length > 1)
258     {
259       alignAddedStructures = true;
260       useAlignmentPanelForSuperposition(ap);
261     }
262     jmb.setColourBySequence(true);
263     setSize(400, 400); // probably should be a configurable/dynamic default here
264     initMenus();
265
266     addingStructures = false;
267     worker = new Thread(this);
268     worker.start();
269
270     this.addInternalFrameListener(new InternalFrameAdapter()
271     {
272       @Override
273       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
274       {
275         closeViewer(false);
276       }
277     });
278
279   }
280
281   /**
282    * Retrieve chains for sequences by inspecting their PDB refs. The hope is
283    * that the first will be to the sequence's own chain. Really need a more
284    * managed way of doing this.
285    * 
286    * @param seqs
287    * @return
288    */
289   protected String[][] extractChains(SequenceI[][] seqs)
290   {
291     String[][] chains = new String[seqs.length][];
292     for (int i = 0; i < seqs.length; i++)
293     {
294       chains[i] = new String[seqs[i].length];
295       int seqno = 0;
296       for (SequenceI seq : seqs[i])
297       {
298         String chain = null;
299         if (seq.getDatasetSequence() != null)
300         {
301           Vector<PDBEntry> pdbrefs = seq.getDatasetSequence()
302                   .getAllPDBEntries();
303           if (pdbrefs != null && pdbrefs.size() > 0)
304           {
305             // FIXME: SequenceI.PDBEntry[0] chain mapping used for
306             // ChimeraViewFrame. Is this even used ???
307
308             chain = pdbrefs.get(0).getChainCode();
309           }
310         }
311         chains[i][seqno++] = chain;
312       }
313     }
314     return chains;
315   }
316
317   /**
318    * Create a new viewer from saved session state data including Chimera session
319    * file
320    * 
321    * @param chimeraSessionFile
322    * @param alignPanel
323    * @param pdbArray
324    * @param seqsArray
325    * @param colourByChimera
326    * @param colourBySequence
327    * @param newViewId
328    */
329   public ChimeraViewFrame(String chimeraSessionFile,
330           AlignmentPanel alignPanel, PDBEntry[] pdbArray,
331           SequenceI[][] seqsArray, boolean colourByChimera,
332           boolean colourBySequence, String newViewId)
333   {
334     this();
335     setViewId(newViewId);
336     this.chimeraSessionFile = chimeraSessionFile;
337     openNewChimera(alignPanel, pdbArray, seqsArray);
338     if (colourByChimera)
339     {
340       jmb.setColourBySequence(false);
341       seqColour.setSelected(false);
342       viewerColour.setSelected(true);
343     }
344     else if (colourBySequence)
345     {
346       jmb.setColourBySequence(true);
347       seqColour.setSelected(true);
348       viewerColour.setSelected(false);
349     }
350   }
351
352   /**
353    * create a new viewer containing several structures superimposed using the
354    * given alignPanel.
355    * 
356    * @param pe
357    * @param seqs
358    * @param ap
359    */
360   public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
361           AlignmentPanel ap)
362   {
363     this();
364     openNewChimera(ap, pe, seqs);
365   }
366
367   /**
368    * Default constructor
369    */
370   public ChimeraViewFrame()
371   {
372     super();
373
374     /*
375      * closeViewer will decide whether or not to close this frame
376      * depending on whether user chooses to Cancel or not
377      */
378     setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
379   }
380
381   /**
382    * Returns a list of any Chimera viewers in the desktop. The list is
383    * restricted to those linked to the given alignment panel if it is not null.
384    */
385   @Override
386   protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
387   {
388     List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
389     JInternalFrame[] frames = Desktop.instance.getAllFrames();
390
391     for (JInternalFrame frame : frames)
392     {
393       if (frame instanceof ChimeraViewFrame)
394       {
395         if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
396         {
397           result.add((StructureViewerBase) frame);
398         }
399       }
400     }
401     return result;
402   }
403
404   /**
405    * Launch Chimera. If we have a chimera session file name, send Chimera the
406    * command to open its saved session file.
407    */
408   void initChimera()
409   {
410     jmb.setFinishedInit(false);
411     jalview.gui.Desktop.addInternalFrame(this,
412             jmb.getViewerTitle("Chimera", true), getBounds().width,
413             getBounds().height);
414
415     if (!jmb.launchChimera())
416     {
417       JOptionPane.showMessageDialog(Desktop.desktop,
418               MessageManager.getString("label.chimera_failed"),
419               MessageManager.getString("label.error_loading_file"),
420               JOptionPane.ERROR_MESSAGE);
421       this.dispose();
422       return;
423     }
424
425     if (this.chimeraSessionFile != null)
426     {
427       boolean opened = jmb.openSession(chimeraSessionFile);
428       if (!opened)
429       {
430         System.err
431                 .println("An error occurred opening Chimera session file "
432                         + chimeraSessionFile);
433       }
434     }
435     jmb.setFinishedInit(true);
436
437     jmb.startChimeraListener();
438   }
439
440   /**
441    * If the list is not empty, add menu items for 'All' and each individual
442    * chain to the "View | Show Chain" sub-menu. Multiple selections are allowed.
443    * 
444    * @param chainNames
445    */
446   void setChainMenuItems(List<String> chainNames)
447   {
448     chainMenu.removeAll();
449     if (chainNames == null || chainNames.isEmpty())
450     {
451       return;
452     }
453     JMenuItem menuItem = new JMenuItem(
454             MessageManager.getString("label.all"));
455     menuItem.addActionListener(new ActionListener()
456     {
457       @Override
458       public void actionPerformed(ActionEvent evt)
459       {
460         allChainsSelected = true;
461         for (int i = 0; i < chainMenu.getItemCount(); i++)
462         {
463           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
464           {
465             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
466           }
467         }
468         showSelectedChains();
469         allChainsSelected = false;
470       }
471     });
472
473     chainMenu.add(menuItem);
474
475     for (String chainName : chainNames)
476     {
477       menuItem = new JCheckBoxMenuItem(chainName, true);
478       menuItem.addItemListener(new ItemListener()
479       {
480         @Override
481         public void itemStateChanged(ItemEvent evt)
482         {
483           if (!allChainsSelected)
484           {
485             showSelectedChains();
486           }
487         }
488       });
489
490       chainMenu.add(menuItem);
491     }
492   }
493
494   /**
495    * Show only the selected chain(s) in the viewer
496    */
497   void showSelectedChains()
498   {
499     List<String> toshow = new ArrayList<String>();
500     for (int i = 0; i < chainMenu.getItemCount(); i++)
501     {
502       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
503       {
504         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
505         if (item.isSelected())
506         {
507           toshow.add(item.getText());
508         }
509       }
510     }
511     jmb.showChains(toshow);
512   }
513
514   /**
515    * Close down this instance of Jalview's Chimera viewer, giving the user the
516    * option to close the associated Chimera window (process). They may wish to
517    * keep it open until they have had an opportunity to save any work.
518    * 
519    * @param closeChimera
520    *          if true, close any linked Chimera process; if false, prompt first
521    */
522   @Override
523   public void closeViewer(boolean closeChimera)
524   {
525     if (jmb != null && jmb.isChimeraRunning())
526     {
527       if (!closeChimera)
528       {
529         String prompt = MessageManager.formatMessage(
530                 "label.confirm_close_chimera",
531                 new Object[] { jmb.getViewerTitle("Chimera", false) });
532         prompt = JvSwingUtils.wrapTooltip(true, prompt);
533         int confirm = JOptionPane.showConfirmDialog(this, prompt,
534                 MessageManager.getString("label.close_viewer"),
535                 JOptionPane.YES_NO_CANCEL_OPTION);
536         /*
537          * abort closure if user hits escape or Cancel
538          */
539         if (confirm == JOptionPane.CANCEL_OPTION
540                 || confirm == JOptionPane.CLOSED_OPTION)
541         {
542           return;
543         }
544         closeChimera = confirm == JOptionPane.YES_OPTION;
545       }
546       jmb.closeViewer(closeChimera);
547     }
548     setAlignmentPanel(null);
549     _aps.clear();
550     _alignwith.clear();
551     _colourwith.clear();
552     // TODO: check for memory leaks where instance isn't finalised because jmb
553     // holds a reference to the window
554     jmb = null;
555     dispose();
556   }
557
558   /**
559    * Open any newly added PDB structures in Chimera, having first fetched data
560    * from PDB (if not already saved).
561    */
562   @Override
563   public void run()
564   {
565     _started = true;
566     // todo - record which pdbids were successfully imported.
567     StringBuilder errormsgs = new StringBuilder(128);
568     StringBuilder files = new StringBuilder(128);
569     List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
570     List<Integer> filePDBpos = new ArrayList<Integer>();
571     PDBEntry thePdbEntry = null;
572     try
573     {
574       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
575       // TODO: replace with reference fetching/transfer code (validate PDBentry
576       // as a DBRef?)
577       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
578       {
579         String file = null;
580         thePdbEntry = jmb.getPdbEntry(pi);
581         if (thePdbEntry.getFile() == null)
582         {
583           /*
584            * Retrieve PDB data, save to file, attach to PDBEntry
585            */
586           file = fetchPdbFile(thePdbEntry);
587           if (file == null)
588           {
589             errormsgs.append("'" + thePdbEntry.getId() + "' ");
590           }
591         }
592         else
593         {
594           /*
595            * Got file already - ignore if already loaded in Chimera.
596            */
597           file = new File(thePdbEntry.getFile()).getAbsoluteFile()
598                   .getPath();
599           if (curfiles != null && curfiles.length > 0)
600           {
601             addingStructures = true; // already files loaded.
602             for (int c = 0; c < curfiles.length; c++)
603             {
604               if (curfiles[c].equals(file))
605               {
606                 file = null;
607                 break;
608               }
609             }
610           }
611         }
612         if (file != null)
613         {
614           filePDB.add(thePdbEntry);
615           filePDBpos.add(Integer.valueOf(pi));
616           files.append(" \"" + Platform.escapeString(file) + "\"");
617         }
618       }
619     } catch (OutOfMemoryError oomerror)
620     {
621       new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
622               oomerror);
623     } catch (Exception ex)
624     {
625       ex.printStackTrace();
626       errormsgs.append("When retrieving pdbfiles for '"
627               + thePdbEntry.getId() + "'");
628     }
629     if (errormsgs.length() > 0)
630     {
631
632       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
633               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
634                       new Object[] { errormsgs.toString() }),
635               MessageManager.getString("label.couldnt_load_file"),
636               JOptionPane.ERROR_MESSAGE);
637     }
638
639     if (files.length() > 0)
640     {
641       if (!addingStructures)
642       {
643         try
644         {
645           initChimera();
646         } catch (Exception ex)
647         {
648           Cache.log.error("Couldn't open Chimera viewer!", ex);
649         }
650       }
651       int num = -1;
652       for (PDBEntry pe : filePDB)
653       {
654         num++;
655         if (pe.getFile() != null)
656         {
657           try
658           {
659             int pos = filePDBpos.get(num).intValue();
660             long startTime = startProgressBar("Chimera "
661                     + MessageManager.getString("status.opening_file_for")
662                     + " " + pe.getId());
663             jmb.openFile(pe);
664             jmb.addSequence(pos, jmb.getSequence()[pos]);
665             File fl = new File(pe.getFile());
666             String protocol = AppletFormatAdapter.URL;
667             try
668             {
669               if (fl.exists())
670               {
671                 protocol = AppletFormatAdapter.FILE;
672               }
673             } catch (Throwable e)
674             {
675             } finally
676             {
677               stopProgressBar("", startTime);
678             }
679             // Explicitly map to the filename used by Chimera ;
680             jmb.getSsm().setMapping(jmb.getSequence()[pos],
681                     jmb.getChains()[pos], pe.getFile(), protocol);
682           } catch (OutOfMemoryError oomerror)
683           {
684             new OOMWarning(
685                     "When trying to open and map structures from Chimera!",
686                     oomerror);
687           } catch (Exception ex)
688           {
689             Cache.log.error("Couldn't open " + pe.getFile()
690                     + " in Chimera viewer!", ex);
691           } finally
692           {
693             Cache.log.debug("File locations are " + files);
694           }
695         }
696       }
697       jmb.setFinishedInit(true);
698       jmb.setLoadingFromArchive(false);
699
700       // refresh the sequence colours for the new structure(s)
701       for (AlignmentPanel ap : _colourwith)
702       {
703         jmb.updateColours(ap);
704       }
705       // do superposition if asked to
706       if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
707       {
708         new Thread(new Runnable()
709         {
710           @Override
711           public void run()
712           {
713             alignStructs_withAllAlignPanels();
714           }
715         }).start();
716         alignAddedStructures = false;
717       }
718       addingStructures = false;
719     }
720     _started = false;
721     worker = null;
722   }
723
724   /**
725    * Fetch PDB data and save to a local file. Returns the full path to the file,
726    * or null if fetch fails.
727    * 
728    * @param processingEntry
729    * @return
730    * @throws Exception
731    */
732   private String fetchPdbFile(PDBEntry processingEntry) throws Exception
733   {
734     // FIXME: this is duplicated code with Jmol frame ?
735     String filePath = null;
736     Pdb pdbclient = new Pdb();
737     AlignmentI pdbseq = null;
738     String pdbid = processingEntry.getId();
739     long handle = System.currentTimeMillis()
740             + Thread.currentThread().hashCode();
741
742     /*
743      * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
744      */
745     String msg = MessageManager.formatMessage("status.fetching_pdb",
746             new Object[] { pdbid });
747     getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
748     // long hdl = startProgressBar(MessageManager.formatMessage(
749     // "status.fetching_pdb", new Object[]
750     // { pdbid }));
751     try
752     {
753       pdbseq = pdbclient.getSequenceRecords(pdbid);
754     } catch (OutOfMemoryError oomerror)
755     {
756       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
757     } finally
758     {
759       msg = pdbid + " " + MessageManager.getString("label.state_completed");
760       getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
761       // stopProgressBar(msg, hdl);
762     }
763     /*
764      * If PDB data were saved and are not invalid (empty alignment), return the
765      * file path.
766      */
767     if (pdbseq != null && pdbseq.getHeight() > 0)
768     {
769       // just use the file name from the first sequence's first PDBEntry
770       filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
771               .elementAt(0).getFile()).getAbsolutePath();
772       processingEntry.setFile(filePath);
773     }
774     return filePath;
775   }
776
777   /**
778    * Convenience method to update the progress bar if there is one. Be sure to
779    * call stopProgressBar with the returned handle to remove the message.
780    * 
781    * @param msg
782    * @param handle
783    */
784   public long startProgressBar(String msg)
785   {
786     // TODO would rather have startProgress/stopProgress as the
787     // IProgressIndicator interface
788     long tm = random.nextLong();
789     if (progressBar != null)
790     {
791       progressBar.setProgressBar(msg, tm);
792     }
793     return tm;
794   }
795
796   /**
797    * End the progress bar with the specified handle, leaving a message (if not
798    * null) on the status bar
799    * 
800    * @param msg
801    * @param handle
802    */
803   public void stopProgressBar(String msg, long handle)
804   {
805     if (progressBar != null)
806     {
807       progressBar.setProgressBar(msg, handle);
808     }
809   }
810
811   @Override
812   public void pdbFile_actionPerformed(ActionEvent actionEvent)
813   {
814     JalviewFileChooser chooser = new JalviewFileChooser(
815             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
816
817     chooser.setFileView(new JalviewFileView());
818     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
819     chooser.setToolTipText(MessageManager.getString("action.save"));
820
821     int value = chooser.showSaveDialog(this);
822
823     if (value == JalviewFileChooser.APPROVE_OPTION)
824     {
825       BufferedReader in = null;
826       try
827       {
828         // TODO: cope with multiple PDB files in view
829         in = new BufferedReader(new FileReader(jmb.getPdbFile()[0]));
830         File outFile = chooser.getSelectedFile();
831
832         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
833         String data;
834         while ((data = in.readLine()) != null)
835         {
836           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
837           {
838             out.println(data);
839           }
840         }
841         out.close();
842       } catch (Exception ex)
843       {
844         ex.printStackTrace();
845       } finally
846       {
847         if (in != null)
848         {
849           try
850           {
851             in.close();
852           } catch (IOException e)
853           {
854             e.printStackTrace();
855           }
856         }
857       }
858     }
859   }
860
861   @Override
862   public void viewMapping_actionPerformed(ActionEvent actionEvent)
863   {
864     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
865     try
866     {
867       cap.appendText(jmb.printMappings());
868     } catch (OutOfMemoryError e)
869     {
870       new OOMWarning(
871               "composing sequence-structure alignments for display in text box.",
872               e);
873       cap.dispose();
874       return;
875     }
876     jalview.gui.Desktop.addInternalFrame(cap,
877             MessageManager.getString("label.pdb_sequence_mapping"), 550,
878             600);
879   }
880
881   @Override
882   public void eps_actionPerformed(ActionEvent e)
883   {
884     throw new Error(
885             MessageManager
886                     .getString("error.eps_generation_not_implemented"));
887   }
888
889   @Override
890   public void png_actionPerformed(ActionEvent e)
891   {
892     throw new Error(
893             MessageManager
894                     .getString("error.png_generation_not_implemented"));
895   }
896
897   @Override
898   public void viewerColour_actionPerformed(ActionEvent actionEvent)
899   {
900     if (viewerColour.isSelected())
901     {
902       // disable automatic sequence colouring.
903       jmb.setColourBySequence(false);
904     }
905   }
906
907   @Override
908   public void seqColour_actionPerformed(ActionEvent actionEvent)
909   {
910     jmb.setColourBySequence(seqColour.isSelected());
911     if (_colourwith == null)
912     {
913       _colourwith = new Vector<AlignmentPanel>();
914     }
915     if (jmb.isColourBySequence())
916     {
917       if (!jmb.isLoadingFromArchive())
918       {
919         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
920         {
921           // Make the currently displayed alignment panel the associated view
922           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
923         }
924       }
925       // Set the colour using the current view for the associated alignframe
926       for (AlignmentPanel ap : _colourwith)
927       {
928         jmb.colourBySequence(ap.av.isShowSequenceFeatures(), ap);
929       }
930     }
931   }
932
933   @Override
934   public void chainColour_actionPerformed(ActionEvent actionEvent)
935   {
936     chainColour.setSelected(true);
937     jmb.colourByChain();
938   }
939
940   @Override
941   public void chargeColour_actionPerformed(ActionEvent actionEvent)
942   {
943     chargeColour.setSelected(true);
944     jmb.colourByCharge();
945   }
946
947   @Override
948   public void zappoColour_actionPerformed(ActionEvent actionEvent)
949   {
950     zappoColour.setSelected(true);
951     jmb.setJalviewColourScheme(new ZappoColourScheme());
952   }
953
954   @Override
955   public void taylorColour_actionPerformed(ActionEvent actionEvent)
956   {
957     taylorColour.setSelected(true);
958     jmb.setJalviewColourScheme(new TaylorColourScheme());
959   }
960
961   @Override
962   public void hydroColour_actionPerformed(ActionEvent actionEvent)
963   {
964     hydroColour.setSelected(true);
965     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
966   }
967
968   @Override
969   public void helixColour_actionPerformed(ActionEvent actionEvent)
970   {
971     helixColour.setSelected(true);
972     jmb.setJalviewColourScheme(new HelixColourScheme());
973   }
974
975   @Override
976   public void strandColour_actionPerformed(ActionEvent actionEvent)
977   {
978     strandColour.setSelected(true);
979     jmb.setJalviewColourScheme(new StrandColourScheme());
980   }
981
982   @Override
983   public void turnColour_actionPerformed(ActionEvent actionEvent)
984   {
985     turnColour.setSelected(true);
986     jmb.setJalviewColourScheme(new TurnColourScheme());
987   }
988
989   @Override
990   public void buriedColour_actionPerformed(ActionEvent actionEvent)
991   {
992     buriedColour.setSelected(true);
993     jmb.setJalviewColourScheme(new BuriedColourScheme());
994   }
995
996   @Override
997   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
998   {
999     setJalviewColourScheme(new PurinePyrimidineColourScheme());
1000   }
1001
1002   @Override
1003   public void userColour_actionPerformed(ActionEvent actionEvent)
1004   {
1005     userColour.setSelected(true);
1006     new UserDefinedColours(this, null);
1007   }
1008
1009   @Override
1010   public void backGround_actionPerformed(ActionEvent actionEvent)
1011   {
1012     java.awt.Color col = JColorChooser
1013             .showDialog(this, MessageManager
1014                     .getString("label.select_backgroud_colour"), null);
1015     if (col != null)
1016     {
1017       jmb.setBackgroundColour(col);
1018     }
1019   }
1020
1021   @Override
1022   public void showHelp_actionPerformed(ActionEvent actionEvent)
1023   {
1024     try
1025     {
1026       jalview.util.BrowserLauncher
1027               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
1028     } catch (Exception ex)
1029     {
1030     }
1031   }
1032
1033   public void updateTitleAndMenus()
1034   {
1035     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1036     {
1037       repaint();
1038       return;
1039     }
1040     setChainMenuItems(jmb.getChainNames());
1041
1042     this.setTitle(jmb.getViewerTitle("Chimera", true));
1043     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1044     {
1045       viewerActionMenu.setVisible(true);
1046     }
1047     if (!jmb.isLoadingFromArchive())
1048     {
1049       seqColour_actionPerformed(null);
1050     }
1051   }
1052
1053   /*
1054    * (non-Javadoc)
1055    * 
1056    * @see
1057    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1058    * .ActionEvent)
1059    */
1060   @Override
1061   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1062   {
1063     alignStructs_withAllAlignPanels();
1064   }
1065
1066   private void alignStructs_withAllAlignPanels()
1067   {
1068     if (getAlignmentPanel() == null)
1069     {
1070       return;
1071     }
1072
1073     if (_alignwith.size() == 0)
1074     {
1075       _alignwith.add(getAlignmentPanel());
1076     }
1077
1078     try
1079     {
1080       AlignmentI[] als = new Alignment[_alignwith.size()];
1081       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1082       int[] alm = new int[_alignwith.size()];
1083       int a = 0;
1084
1085       for (AlignmentPanel ap : _alignwith)
1086       {
1087         als[a] = ap.av.getAlignment();
1088         alm[a] = -1;
1089         alc[a++] = ap.av.getColumnSelection();
1090       }
1091       jmb.superposeStructures(als, alm, alc);
1092     } catch (Exception e)
1093     {
1094       StringBuffer sp = new StringBuffer();
1095       for (AlignmentPanel ap : _alignwith)
1096       {
1097         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1098       }
1099       Cache.log.info("Couldn't align structures with the " + sp.toString()
1100               + "associated alignment panels.", e);
1101     }
1102   }
1103
1104   @Override
1105   public void setJalviewColourScheme(ColourSchemeI ucs)
1106   {
1107     jmb.setJalviewColourScheme(ucs);
1108
1109   }
1110
1111   /**
1112    * 
1113    * @param alignment
1114    * @return first alignment panel displaying given alignment, or the default
1115    *         alignment panel
1116    */
1117   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1118   {
1119     for (AlignmentPanel ap : getAllAlignmentPanels())
1120     {
1121       if (ap.av.getAlignment() == alignment)
1122       {
1123         return ap;
1124       }
1125     }
1126     return getAlignmentPanel();
1127   }
1128
1129   @Override
1130   public AAStructureBindingModel getBinding()
1131   {
1132     return jmb;
1133   }
1134
1135   /**
1136    * Ask Chimera to save its session to the designated file path, or to a
1137    * temporary file if the path is null. Returns the file path if successful,
1138    * else null.
1139    * 
1140    * @param filepath
1141    * @see getStateInfo
1142    */
1143   protected String saveSession(String filepath)
1144   {
1145     String pathUsed = filepath;
1146     try
1147     {
1148       if (pathUsed == null)
1149       {
1150         File tempFile = File.createTempFile("chimera", ".py");
1151         tempFile.deleteOnExit();
1152         pathUsed = tempFile.getPath();
1153       }
1154       boolean result = jmb.saveSession(pathUsed);
1155       if (result)
1156       {
1157         this.chimeraSessionFile = pathUsed;
1158         return pathUsed;
1159       }
1160     } catch (IOException e)
1161     {
1162     }
1163     return null;
1164   }
1165
1166   /**
1167    * Returns a string representing the state of the Chimera session. This is
1168    * done by requesting Chimera to save its session to a temporary file, then
1169    * reading the file contents. Returns an empty string on any error.
1170    */
1171   @Override
1172   public String getStateInfo()
1173   {
1174     String sessionFile = saveSession(null);
1175     if (sessionFile == null)
1176     {
1177       return "";
1178     }
1179     InputStream is = null;
1180     try
1181     {
1182       File f = new File(sessionFile);
1183       byte[] bytes = new byte[(int) f.length()];
1184       is = new FileInputStream(sessionFile);
1185       is.read(bytes);
1186       return new String(bytes);
1187     } catch (IOException e)
1188     {
1189       return "";
1190     } finally
1191     {
1192       if (is != null)
1193       {
1194         try
1195         {
1196           is.close();
1197         } catch (IOException e)
1198         {
1199           // ignore
1200         }
1201       }
1202     }
1203   }
1204
1205   @Override
1206   protected void fitToWindow_actionPerformed()
1207   {
1208     jmb.focusView();
1209   }
1210
1211   @Override
1212   public ViewerType getViewerType()
1213   {
1214     return ViewerType.CHIMERA;
1215   }
1216
1217   @Override
1218   protected AAStructureBindingModel getBindingModel()
1219   {
1220     return jmb;
1221   }
1222 }