JAL-2360 refactoring for JalviewColourScheme enum,
[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.DataSourceType;
32 import jalview.io.JalviewFileChooser;
33 import jalview.io.JalviewFileView;
34 import jalview.io.StructureFile;
35 import jalview.schemes.BuriedColourScheme;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.HelixColourScheme;
38 import jalview.schemes.HydrophobicColourScheme;
39 import jalview.schemes.PurinePyrimidineColourScheme;
40 import jalview.schemes.StrandColourScheme;
41 import jalview.schemes.TaylorColourScheme;
42 import jalview.schemes.TurnColourScheme;
43 import jalview.schemes.UserColourScheme;
44 import jalview.schemes.ZappoColourScheme;
45 import jalview.structures.models.AAStructureBindingModel;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
48 import jalview.ws.dbsources.Pdb;
49
50 import java.awt.Color;
51 import java.awt.event.ActionEvent;
52 import java.awt.event.ItemEvent;
53 import java.awt.event.ItemListener;
54 import java.io.BufferedReader;
55 import java.io.File;
56 import java.io.FileInputStream;
57 import java.io.FileOutputStream;
58 import java.io.FileReader;
59 import java.io.IOException;
60 import java.io.InputStream;
61 import java.io.PrintWriter;
62 import java.util.ArrayList;
63 import java.util.List;
64 import java.util.Random;
65 import java.util.Vector;
66
67 import javax.swing.JCheckBoxMenuItem;
68 import javax.swing.JColorChooser;
69 import javax.swing.JInternalFrame;
70 import javax.swing.JMenu;
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     jmb = new JalviewChimeraBindingModel(this,
252             ap.getStructureSelectionManager(), pdbentrys, seqs, null);
253     addAlignmentPanel(ap);
254     useAlignmentPanelForColourbyseq(ap);
255     if (pdbentrys.length > 1)
256     {
257       alignAddedStructures = true;
258       useAlignmentPanelForSuperposition(ap);
259     }
260     jmb.setColourBySequence(true);
261     setSize(400, 400); // probably should be a configurable/dynamic default here
262     initMenus();
263
264     addingStructures = false;
265     worker = new Thread(this);
266     worker.start();
267
268     this.addInternalFrameListener(new InternalFrameAdapter()
269     {
270       @Override
271       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
272       {
273         closeViewer(false);
274       }
275     });
276
277   }
278
279
280
281   /**
282    * Create a new viewer from saved session state data including Chimera session
283    * file
284    * 
285    * @param chimeraSessionFile
286    * @param alignPanel
287    * @param pdbArray
288    * @param seqsArray
289    * @param colourByChimera
290    * @param colourBySequence
291    * @param newViewId
292    */
293   public ChimeraViewFrame(String chimeraSessionFile,
294           AlignmentPanel alignPanel, PDBEntry[] pdbArray,
295           SequenceI[][] seqsArray, boolean colourByChimera,
296           boolean colourBySequence, String newViewId)
297   {
298     this();
299     setViewId(newViewId);
300     this.chimeraSessionFile = chimeraSessionFile;
301     openNewChimera(alignPanel, pdbArray, seqsArray);
302     if (colourByChimera)
303     {
304       jmb.setColourBySequence(false);
305       seqColour.setSelected(false);
306       viewerColour.setSelected(true);
307     }
308     else if (colourBySequence)
309     {
310       jmb.setColourBySequence(true);
311       seqColour.setSelected(true);
312       viewerColour.setSelected(false);
313     }
314   }
315
316   /**
317    * create a new viewer containing several structures superimposed using the
318    * given alignPanel.
319    * 
320    * @param pe
321    * @param seqs
322    * @param ap
323    */
324   public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
325           AlignmentPanel ap)
326   {
327     this();
328     openNewChimera(ap, pe, seqs);
329   }
330
331   /**
332    * Default constructor
333    */
334   public ChimeraViewFrame()
335   {
336     super();
337
338     /*
339      * closeViewer will decide whether or not to close this frame
340      * depending on whether user chooses to Cancel or not
341      */
342     setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
343   }
344
345   /**
346    * Returns a list of any Chimera viewers in the desktop. The list is
347    * restricted to those linked to the given alignment panel if it is not null.
348    */
349   @Override
350   protected List<StructureViewerBase> getViewersFor(AlignmentPanel ap)
351   {
352     List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
353     JInternalFrame[] frames = Desktop.instance.getAllFrames();
354
355     for (JInternalFrame frame : frames)
356     {
357       if (frame instanceof ChimeraViewFrame)
358       {
359         if (ap == null || ((StructureViewerBase) frame).isLinkedWith(ap))
360         {
361           result.add((StructureViewerBase) frame);
362         }
363       }
364     }
365     return result;
366   }
367
368   /**
369    * Launch Chimera. If we have a chimera session file name, send Chimera the
370    * command to open its saved session file.
371    */
372   void initChimera()
373   {
374     jmb.setFinishedInit(false);
375     jalview.gui.Desktop.addInternalFrame(this,
376             jmb.getViewerTitle("Chimera", true), getBounds().width,
377             getBounds().height);
378
379     if (!jmb.launchChimera())
380     {
381       JvOptionPane.showMessageDialog(Desktop.desktop,
382               MessageManager.getString("label.chimera_failed"),
383               MessageManager.getString("label.error_loading_file"),
384               JvOptionPane.ERROR_MESSAGE);
385       this.dispose();
386       return;
387     }
388
389     if (this.chimeraSessionFile != null)
390     {
391       boolean opened = jmb.openSession(chimeraSessionFile);
392       if (!opened)
393       {
394         System.err
395                 .println("An error occurred opening Chimera session file "
396                         + chimeraSessionFile);
397       }
398     }
399     jmb.setFinishedInit(true);
400
401     jmb.startChimeraListener();
402   }
403
404
405   /**
406    * Show only the selected chain(s) in the viewer
407    */
408   @Override
409   void showSelectedChains()
410   {
411     List<String> toshow = new ArrayList<String>();
412     for (int i = 0; i < chainMenu.getItemCount(); i++)
413     {
414       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
415       {
416         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
417         if (item.isSelected())
418         {
419           toshow.add(item.getText());
420         }
421       }
422     }
423     jmb.showChains(toshow);
424   }
425
426   /**
427    * Close down this instance of Jalview's Chimera viewer, giving the user the
428    * option to close the associated Chimera window (process). They may wish to
429    * keep it open until they have had an opportunity to save any work.
430    * 
431    * @param closeChimera
432    *          if true, close any linked Chimera process; if false, prompt first
433    */
434   @Override
435   public void closeViewer(boolean closeChimera)
436   {
437     if (jmb != null && jmb.isChimeraRunning())
438     {
439       if (!closeChimera)
440       {
441         String prompt = MessageManager.formatMessage(
442                 "label.confirm_close_chimera",
443                 new Object[] { jmb.getViewerTitle("Chimera", false) });
444         prompt = JvSwingUtils.wrapTooltip(true, prompt);
445         int confirm = JvOptionPane.showConfirmDialog(this, prompt,
446                 MessageManager.getString("label.close_viewer"),
447                 JvOptionPane.YES_NO_CANCEL_OPTION);
448         /*
449          * abort closure if user hits escape or Cancel
450          */
451         if (confirm == JvOptionPane.CANCEL_OPTION
452                 || confirm == JvOptionPane.CLOSED_OPTION)
453         {
454           return;
455         }
456         closeChimera = confirm == JvOptionPane.YES_OPTION;
457       }
458       jmb.closeViewer(closeChimera);
459     }
460     setAlignmentPanel(null);
461     _aps.clear();
462     _alignwith.clear();
463     _colourwith.clear();
464     // TODO: check for memory leaks where instance isn't finalised because jmb
465     // holds a reference to the window
466     jmb = null;
467     dispose();
468   }
469
470   /**
471    * Open any newly added PDB structures in Chimera, having first fetched data
472    * from PDB (if not already saved).
473    */
474   @Override
475   public void run()
476   {
477     _started = true;
478     // todo - record which pdbids were successfully imported.
479     StringBuilder errormsgs = new StringBuilder(128);
480     StringBuilder files = new StringBuilder(128);
481     List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
482     List<Integer> filePDBpos = new ArrayList<Integer>();
483     PDBEntry thePdbEntry = null;
484     StructureFile pdb = null;
485     try
486     {
487       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
488       // TODO: replace with reference fetching/transfer code (validate PDBentry
489       // as a DBRef?)
490       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
491       {
492         String file = null;
493         thePdbEntry = jmb.getPdbEntry(pi);
494         if (thePdbEntry.getFile() == null)
495         {
496           /*
497            * Retrieve PDB data, save to file, attach to PDBEntry
498            */
499           file = fetchPdbFile(thePdbEntry);
500           if (file == null)
501           {
502             errormsgs.append("'" + thePdbEntry.getId() + "' ");
503           }
504         }
505         else
506         {
507           /*
508            * Got file already - ignore if already loaded in Chimera.
509            */
510           file = new File(thePdbEntry.getFile()).getAbsoluteFile()
511                   .getPath();
512           if (curfiles != null && curfiles.length > 0)
513           {
514             addingStructures = true; // already files loaded.
515             for (int c = 0; c < curfiles.length; c++)
516             {
517               if (curfiles[c].equals(file))
518               {
519                 file = null;
520                 break;
521               }
522             }
523           }
524         }
525         if (file != null)
526         {
527           filePDB.add(thePdbEntry);
528           filePDBpos.add(Integer.valueOf(pi));
529           files.append(" \"" + Platform.escapeString(file) + "\"");
530         }
531       }
532     } catch (OutOfMemoryError oomerror)
533     {
534       new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
535               oomerror);
536     } catch (Exception ex)
537     {
538       ex.printStackTrace();
539       errormsgs.append("When retrieving pdbfiles for '"
540               + thePdbEntry.getId() + "'");
541     }
542     if (errormsgs.length() > 0)
543     {
544
545       JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
546               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
547                       new Object[] { errormsgs.toString() }),
548               MessageManager.getString("label.couldnt_load_file"),
549               JvOptionPane.ERROR_MESSAGE);
550     }
551
552     if (files.length() > 0)
553     {
554       if (!addingStructures)
555       {
556         try
557         {
558           initChimera();
559         } catch (Exception ex)
560         {
561           Cache.log.error("Couldn't open Chimera viewer!", ex);
562         }
563       }
564       int num = -1;
565       for (PDBEntry pe : filePDB)
566       {
567         num++;
568         if (pe.getFile() != null)
569         {
570           try
571           {
572             int pos = filePDBpos.get(num).intValue();
573             long startTime = startProgressBar("Chimera "
574                     + MessageManager.getString("status.opening_file_for")
575                     + " " + pe.getId());
576             jmb.openFile(pe);
577             jmb.addSequence(pos, jmb.getSequence()[pos]);
578             File fl = new File(pe.getFile());
579             DataSourceType protocol = DataSourceType.URL;
580             try
581             {
582               if (fl.exists())
583               {
584                 protocol = DataSourceType.FILE;
585               }
586             } catch (Throwable e)
587             {
588             } finally
589             {
590               stopProgressBar("", startTime);
591             }
592             // Explicitly map to the filename used by Chimera ;
593             pdb = jmb.getSsm().setMapping(jmb.getSequence()[pos],
594                     jmb.getChains()[pos], pe.getFile(), protocol);
595             stashFoundChains(pdb, pe.getFile());
596           } catch (OutOfMemoryError oomerror)
597           {
598             new OOMWarning(
599                     "When trying to open and map structures from Chimera!",
600                     oomerror);
601           } catch (Exception ex)
602           {
603             Cache.log.error("Couldn't open " + pe.getFile()
604                     + " in Chimera viewer!", ex);
605           } finally
606           {
607             Cache.log.debug("File locations are " + files);
608           }
609         }
610       }
611       jmb.refreshGUI();
612       jmb.setFinishedInit(true);
613       jmb.setLoadingFromArchive(false);
614
615       // refresh the sequence colours for the new structure(s)
616       for (AlignmentPanel ap : _colourwith)
617       {
618         jmb.updateColours(ap);
619       }
620       // do superposition if asked to
621       if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
622       {
623         new Thread(new Runnable()
624         {
625           @Override
626           public void run()
627           {
628             alignStructs_withAllAlignPanels();
629           }
630         }).start();
631         alignAddedStructures = false;
632       }
633       addingStructures = false;
634     }
635     _started = false;
636     worker = null;
637   }
638
639   /**
640    * Fetch PDB data and save to a local file. Returns the full path to the file,
641    * or null if fetch fails.
642    * 
643    * @param processingEntry
644    * @return
645    * @throws Exception
646    */
647
648   private void stashFoundChains(StructureFile pdb, String file)
649   {
650     for (int i = 0; i < pdb.getChains().size(); i++)
651     {
652       String chid = new String(pdb.getId() + ":"
653               + pdb.getChains().elementAt(i).id);
654       jmb.getChainNames().add(chid);
655       jmb.getChainFile().put(chid, file);
656     }
657   }
658   private String fetchPdbFile(PDBEntry processingEntry) throws Exception
659   {
660     // FIXME: this is duplicated code with Jmol frame ?
661     String filePath = null;
662     Pdb pdbclient = new Pdb();
663     AlignmentI pdbseq = null;
664     String pdbid = processingEntry.getId();
665     long handle = System.currentTimeMillis()
666             + Thread.currentThread().hashCode();
667
668     /*
669      * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
670      */
671     String msg = MessageManager.formatMessage("status.fetching_pdb",
672             new Object[] { pdbid });
673     getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
674     // long hdl = startProgressBar(MessageManager.formatMessage(
675     // "status.fetching_pdb", new Object[]
676     // { pdbid }));
677     try
678     {
679       pdbseq = pdbclient.getSequenceRecords(pdbid);
680     } catch (OutOfMemoryError oomerror)
681     {
682       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
683     } finally
684     {
685       msg = pdbid + " " + MessageManager.getString("label.state_completed");
686       getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
687       // stopProgressBar(msg, hdl);
688     }
689     /*
690      * If PDB data were saved and are not invalid (empty alignment), return the
691      * file path.
692      */
693     if (pdbseq != null && pdbseq.getHeight() > 0)
694     {
695       // just use the file name from the first sequence's first PDBEntry
696       filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
697               .elementAt(0).getFile()).getAbsolutePath();
698       processingEntry.setFile(filePath);
699     }
700     return filePath;
701   }
702
703   /**
704    * Convenience method to update the progress bar if there is one. Be sure to
705    * call stopProgressBar with the returned handle to remove the message.
706    * 
707    * @param msg
708    * @param handle
709    */
710   public long startProgressBar(String msg)
711   {
712     // TODO would rather have startProgress/stopProgress as the
713     // IProgressIndicator interface
714     long tm = random.nextLong();
715     if (progressBar != null)
716     {
717       progressBar.setProgressBar(msg, tm);
718     }
719     return tm;
720   }
721
722   /**
723    * End the progress bar with the specified handle, leaving a message (if not
724    * null) on the status bar
725    * 
726    * @param msg
727    * @param handle
728    */
729   public void stopProgressBar(String msg, long handle)
730   {
731     if (progressBar != null)
732     {
733       progressBar.setProgressBar(msg, handle);
734     }
735   }
736
737   @Override
738   public void pdbFile_actionPerformed(ActionEvent actionEvent)
739   {
740     JalviewFileChooser chooser = new JalviewFileChooser(
741             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
742
743     chooser.setFileView(new JalviewFileView());
744     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
745     chooser.setToolTipText(MessageManager.getString("action.save"));
746
747     int value = chooser.showSaveDialog(this);
748
749     if (value == JalviewFileChooser.APPROVE_OPTION)
750     {
751       BufferedReader in = null;
752       try
753       {
754         // TODO: cope with multiple PDB files in view
755         in = new BufferedReader(new FileReader(jmb.getPdbFile()[0]));
756         File outFile = chooser.getSelectedFile();
757
758         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
759         String data;
760         while ((data = in.readLine()) != null)
761         {
762           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
763           {
764             out.println(data);
765           }
766         }
767         out.close();
768       } catch (Exception ex)
769       {
770         ex.printStackTrace();
771       } finally
772       {
773         if (in != null)
774         {
775           try
776           {
777             in.close();
778           } catch (IOException e)
779           {
780             e.printStackTrace();
781           }
782         }
783       }
784     }
785   }
786
787   @Override
788   public void viewMapping_actionPerformed(ActionEvent actionEvent)
789   {
790     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
791     try
792     {
793       cap.appendText(jmb.printMappings());
794     } catch (OutOfMemoryError e)
795     {
796       new OOMWarning(
797               "composing sequence-structure alignments for display in text box.",
798               e);
799       cap.dispose();
800       return;
801     }
802     jalview.gui.Desktop.addInternalFrame(cap,
803             MessageManager.getString("label.pdb_sequence_mapping"), 550,
804             600);
805   }
806
807   @Override
808   public void eps_actionPerformed(ActionEvent e)
809   {
810     throw new Error(
811             MessageManager
812                     .getString("error.eps_generation_not_implemented"));
813   }
814
815   @Override
816   public void png_actionPerformed(ActionEvent e)
817   {
818     throw new Error(
819             MessageManager
820                     .getString("error.png_generation_not_implemented"));
821   }
822
823   @Override
824   public void viewerColour_actionPerformed(ActionEvent actionEvent)
825   {
826     if (viewerColour.isSelected())
827     {
828       // disable automatic sequence colouring.
829       jmb.setColourBySequence(false);
830     }
831   }
832
833   @Override
834   public void seqColour_actionPerformed(ActionEvent actionEvent)
835   {
836     jmb.setColourBySequence(seqColour.isSelected());
837     if (_colourwith == null)
838     {
839       _colourwith = new Vector<AlignmentPanel>();
840     }
841     if (jmb.isColourBySequence())
842     {
843       if (!jmb.isLoadingFromArchive())
844       {
845         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
846         {
847           // Make the currently displayed alignment panel the associated view
848           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
849         }
850       }
851       // Set the colour using the current view for the associated alignframe
852       for (AlignmentPanel ap : _colourwith)
853       {
854         jmb.colourBySequence(ap.av.isShowSequenceFeatures(), ap);
855       }
856     }
857   }
858
859   @Override
860   public void chainColour_actionPerformed(ActionEvent actionEvent)
861   {
862     chainColour.setSelected(true);
863     jmb.colourByChain();
864   }
865
866   @Override
867   public void chargeColour_actionPerformed(ActionEvent actionEvent)
868   {
869     chargeColour.setSelected(true);
870     jmb.colourByCharge();
871   }
872
873   @Override
874   public void zappoColour_actionPerformed(ActionEvent actionEvent)
875   {
876     zappoColour.setSelected(true);
877     jmb.setJalviewColourScheme(new ZappoColourScheme());
878   }
879
880   @Override
881   public void taylorColour_actionPerformed(ActionEvent actionEvent)
882   {
883     taylorColour.setSelected(true);
884     jmb.setJalviewColourScheme(new TaylorColourScheme());
885   }
886
887   @Override
888   public void hydroColour_actionPerformed(ActionEvent actionEvent)
889   {
890     hydroColour.setSelected(true);
891     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
892   }
893
894   @Override
895   public void helixColour_actionPerformed(ActionEvent actionEvent)
896   {
897     helixColour.setSelected(true);
898     jmb.setJalviewColourScheme(new HelixColourScheme());
899   }
900
901   @Override
902   public void strandColour_actionPerformed(ActionEvent actionEvent)
903   {
904     strandColour.setSelected(true);
905     jmb.setJalviewColourScheme(new StrandColourScheme());
906   }
907
908   @Override
909   public void turnColour_actionPerformed(ActionEvent actionEvent)
910   {
911     turnColour.setSelected(true);
912     jmb.setJalviewColourScheme(new TurnColourScheme());
913   }
914
915   @Override
916   public void buriedColour_actionPerformed(ActionEvent actionEvent)
917   {
918     buriedColour.setSelected(true);
919     jmb.setJalviewColourScheme(new BuriedColourScheme());
920   }
921
922   @Override
923   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
924   {
925     setJalviewColourScheme(new PurinePyrimidineColourScheme());
926   }
927
928   @Override
929   public void userColour_actionPerformed(ActionEvent e)
930   {
931     if (e.getActionCommand().equals(
932             MessageManager.getString("action.user_defined")))
933     {
934       new UserDefinedColours(this, null);
935     }
936     else
937     {
938       UserColourScheme udc = UserDefinedColours.getUserColourSchemes().get(
939               e.getActionCommand());
940       jmb.setJalviewColourScheme(udc);
941     }
942   }
943
944   @Override
945   public void backGround_actionPerformed(ActionEvent actionEvent)
946   {
947     Color col = JColorChooser.showDialog(this,
948             MessageManager.getString("label.select_background_colour"),
949             null);
950     if (col != null)
951     {
952       jmb.setBackgroundColour(col);
953     }
954   }
955
956   @Override
957   public void showHelp_actionPerformed(ActionEvent actionEvent)
958   {
959     try
960     {
961       jalview.util.BrowserLauncher
962               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
963     } catch (Exception ex)
964     {
965     }
966   }
967
968   public void updateTitleAndMenus()
969   {
970     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
971     {
972       repaint();
973       return;
974     }
975     setChainMenuItems(jmb.getChainNames());
976
977     this.setTitle(jmb.getViewerTitle("Chimera", true));
978     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
979     {
980       viewerActionMenu.setVisible(true);
981     }
982     if (!jmb.isLoadingFromArchive())
983     {
984       seqColour_actionPerformed(null);
985     }
986   }
987
988   /*
989    * (non-Javadoc)
990    * 
991    * @see
992    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
993    * .ActionEvent)
994    */
995   @Override
996   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
997   {
998     alignStructs_withAllAlignPanels();
999   }
1000
1001   private void alignStructs_withAllAlignPanels()
1002   {
1003     if (getAlignmentPanel() == null)
1004     {
1005       return;
1006     }
1007
1008     if (_alignwith.size() == 0)
1009     {
1010       _alignwith.add(getAlignmentPanel());
1011     }
1012
1013     try
1014     {
1015       AlignmentI[] als = new Alignment[_alignwith.size()];
1016       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1017       int[] alm = new int[_alignwith.size()];
1018       int a = 0;
1019
1020       for (AlignmentPanel ap : _alignwith)
1021       {
1022         als[a] = ap.av.getAlignment();
1023         alm[a] = -1;
1024         alc[a++] = ap.av.getColumnSelection();
1025       }
1026       jmb.superposeStructures(als, alm, alc);
1027     } catch (Exception e)
1028     {
1029       StringBuffer sp = new StringBuffer();
1030       for (AlignmentPanel ap : _alignwith)
1031       {
1032         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1033       }
1034       Cache.log.info("Couldn't align structures with the " + sp.toString()
1035               + "associated alignment panels.", e);
1036     }
1037   }
1038
1039   @Override
1040   public void setJalviewColourScheme(ColourSchemeI ucs)
1041   {
1042     jmb.setJalviewColourScheme(ucs);
1043
1044   }
1045
1046   /**
1047    * 
1048    * @param alignment
1049    * @return first alignment panel displaying given alignment, or the default
1050    *         alignment panel
1051    */
1052   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1053   {
1054     for (AlignmentPanel ap : getAllAlignmentPanels())
1055     {
1056       if (ap.av.getAlignment() == alignment)
1057       {
1058         return ap;
1059       }
1060     }
1061     return getAlignmentPanel();
1062   }
1063
1064   @Override
1065   public AAStructureBindingModel getBinding()
1066   {
1067     return jmb;
1068   }
1069
1070   /**
1071    * Ask Chimera to save its session to the designated file path, or to a
1072    * temporary file if the path is null. Returns the file path if successful,
1073    * else null.
1074    * 
1075    * @param filepath
1076    * @see getStateInfo
1077    */
1078   protected String saveSession(String filepath)
1079   {
1080     String pathUsed = filepath;
1081     try
1082     {
1083       if (pathUsed == null)
1084       {
1085         File tempFile = File.createTempFile("chimera", ".py");
1086         tempFile.deleteOnExit();
1087         pathUsed = tempFile.getPath();
1088       }
1089       boolean result = jmb.saveSession(pathUsed);
1090       if (result)
1091       {
1092         this.chimeraSessionFile = pathUsed;
1093         return pathUsed;
1094       }
1095     } catch (IOException e)
1096     {
1097     }
1098     return null;
1099   }
1100
1101   /**
1102    * Returns a string representing the state of the Chimera session. This is
1103    * done by requesting Chimera to save its session to a temporary file, then
1104    * reading the file contents. Returns an empty string on any error.
1105    */
1106   @Override
1107   public String getStateInfo()
1108   {
1109     String sessionFile = saveSession(null);
1110     if (sessionFile == null)
1111     {
1112       return "";
1113     }
1114     InputStream is = null;
1115     try
1116     {
1117       File f = new File(sessionFile);
1118       byte[] bytes = new byte[(int) f.length()];
1119       is = new FileInputStream(sessionFile);
1120       is.read(bytes);
1121       return new String(bytes);
1122     } catch (IOException e)
1123     {
1124       return "";
1125     } finally
1126     {
1127       if (is != null)
1128       {
1129         try
1130         {
1131           is.close();
1132         } catch (IOException e)
1133         {
1134           // ignore
1135         }
1136       }
1137     }
1138   }
1139
1140   @Override
1141   protected void fitToWindow_actionPerformed()
1142   {
1143     jmb.focusView();
1144   }
1145
1146   @Override
1147   public ViewerType getViewerType()
1148   {
1149     return ViewerType.CHIMERA;
1150   }
1151
1152   @Override
1153   protected AAStructureBindingModel getBindingModel()
1154   {
1155     return jmb;
1156   }
1157 }