4e313b5fecf619691875f825465479f140d3545b
[jalview.git] / src / jalview / gui / ChimeraViewFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.Jalview2XML.ViewerData;
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.FileOutputStream;
55 import java.io.FileReader;
56 import java.io.IOException;
57 import java.io.PrintWriter;
58 import java.util.ArrayList;
59 import java.util.List;
60 import java.util.Vector;
61
62 import javax.swing.JCheckBoxMenuItem;
63 import javax.swing.JColorChooser;
64 import javax.swing.JInternalFrame;
65 import javax.swing.JMenu;
66 import javax.swing.JMenuItem;
67 import javax.swing.JOptionPane;
68 import javax.swing.event.InternalFrameAdapter;
69 import javax.swing.event.InternalFrameEvent;
70 import javax.swing.event.MenuEvent;
71 import javax.swing.event.MenuListener;
72
73 /**
74  * GUI elements for handlnig an external chimera display
75  * 
76  * @author jprocter
77  *
78  */
79 public class ChimeraViewFrame extends StructureViewerBase
80 {
81   private JalviewChimeraBinding jmb;
82
83   private boolean allChainsSelected = false;
84
85   private boolean alignAddedStructures = false;
86
87   /*
88    * state flag for PDB retrieval thread
89    */
90   private boolean _started = false;
91
92   private boolean addingStructures = false;
93
94   private IProgressIndicator progressBar = null;
95
96   /*
97    * pdb retrieval thread.
98    */
99   private Thread worker = null;
100
101   /*
102    * Path to Chimera session file - set in saveSession()
103    */
104   private String chimeraSessionFile = "";
105
106   /**
107    * Initialise menu options.
108    */
109   private void initMenus()
110   {
111     viewerActionMenu.setText(MessageManager.getString("label.chimera"));
112     viewerColour.setText(MessageManager
113             .getString("label.colour_with_chimera"));
114     viewerColour.setToolTipText(MessageManager
115             .getString("label.let_chimera_manage_structure_colours"));
116     helpItem.setText(MessageManager.getString("label.chimera_help"));
117     seqColour.setSelected(jmb.isColourBySequence());
118     viewerColour.setSelected(!jmb.isColourBySequence());
119     if (_colourwith == null)
120     {
121       _colourwith = new Vector<AlignmentPanel>();
122     }
123     if (_alignwith == null)
124     {
125       _alignwith = new Vector<AlignmentPanel>();
126     }
127
128     // save As not yet implemented
129     savemenu.setVisible(false);
130
131     ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
132             MessageManager.getString("label.colour_by"), this, _colourwith,
133             new ItemListener()
134             {
135               @Override
136               public void itemStateChanged(ItemEvent e)
137               {
138                 if (!seqColour.isSelected())
139                 {
140                   seqColour.doClick();
141                 }
142                 else
143                 {
144                   // update the Chimera display now.
145                   seqColour_actionPerformed(null);
146                 }
147               }
148             });
149     viewMenu.add(seqColourBy);
150     final ItemListener handler;
151     JMenu alpanels = new ViewSelectionMenu(
152             MessageManager.getString("label.superpose_with"), this,
153             _alignwith, handler = new ItemListener()
154             {
155               @Override
156               public void itemStateChanged(ItemEvent e)
157               {
158                 alignStructs.setEnabled(_alignwith.size() > 0);
159                 alignStructs.setToolTipText(MessageManager
160                         .formatMessage(
161                                 "label.align_structures_using_linked_alignment_views",
162                                 new Object[]
163                                 { new Integer(_alignwith.size()).toString() }));
164               }
165             });
166     handler.itemStateChanged(null);
167     viewerActionMenu.add(alpanels);
168     viewerActionMenu.addMenuListener(new MenuListener()
169     {
170
171       @Override
172       public void menuSelected(MenuEvent e)
173       {
174         handler.itemStateChanged(null);
175       }
176
177       @Override
178       public void menuDeselected(MenuEvent e)
179       {
180         // TODO Auto-generated method stub
181       }
182
183       @Override
184       public void menuCanceled(MenuEvent e)
185       {
186         // TODO Auto-generated method stub
187       }
188     });
189   }
190
191   /**
192    * add a single PDB structure to a new or existing Chimera view
193    * 
194    * @param pdbentry
195    * @param seq
196    * @param chains
197    * @param ap
198    */
199   public ChimeraViewFrame(PDBEntry pdbentry, SequenceI[] seq,
200           String[] chains, final AlignmentPanel ap)
201   {
202     super();
203     progressBar = ap.alignFrame;
204     // ////////////////////////////////
205     // Is the pdb file already loaded?
206     String alreadyMapped = ap.getStructureSelectionManager()
207             .alreadyMappedToFile(pdbentry.getId());
208
209     if (alreadyMapped != null)
210     {
211       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
212               MessageManager.formatMessage(
213                       "label.pdb_entry_is_already_displayed", new Object[]
214                       { pdbentry.getId() }), MessageManager.formatMessage(
215                       "label.map_sequences_to_visible_window", new Object[]
216                       { pdbentry.getId() }),
217               JOptionPane.YES_NO_CANCEL_OPTION);
218
219       if (option == JOptionPane.CANCEL_OPTION)
220       {
221         return;
222       }
223       if (option == JOptionPane.YES_OPTION)
224       {
225         // TODO : Fix multiple seq to one chain issue here.
226         ap.getStructureSelectionManager().setMapping(seq, chains,
227                 alreadyMapped, AppletFormatAdapter.FILE);
228         if (ap.getSeqPanel().seqCanvas.fr != null)
229         {
230           ap.getSeqPanel().seqCanvas.fr.featuresAdded();
231           ap.paintAlignment(true);
232         }
233
234         // Now this ChimeraViewFrame is mapped to new sequences. We must add
235         // them to the existing array
236         JInternalFrame[] frames = Desktop.instance.getAllFrames();
237
238         for (JInternalFrame frame : frames)
239         {
240           if (frame instanceof ChimeraViewFrame)
241           {
242             final ChimeraViewFrame topView = ((ChimeraViewFrame) frame);
243             // JBPNOTE: this looks like a binding routine, rather than a gui
244             // routine
245             for (int pe = 0; pe < topView.jmb.getPdbCount(); pe++)
246             {
247               if (topView.jmb.getPdbEntry(pe).getFile()
248                       .equals(
249                       alreadyMapped))
250               {
251                 topView.jmb.addSequence(pe, seq);
252                 topView.addAlignmentPanel(ap);
253                 // add it to the set used for colouring
254                 topView.useAlignmentPanelForColourbyseq(ap);
255                 topView.buildActionMenu();
256                 ap.getStructureSelectionManager()
257                         .sequenceColoursChanged(ap);
258                 break;
259               }
260             }
261           }
262         }
263
264         return;
265       }
266     }
267     // /////////////////////////////////
268     // Check if there are other Chimera views involving this alignment
269     // and prompt user about adding this molecule to one of them
270     List<ChimeraViewFrame> existingViews = getChimeraWindowsFor(ap);
271     for (ChimeraViewFrame topView : existingViews)
272     {
273       // TODO: highlight topView in view somehow
274       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
275               MessageManager.formatMessage("label.add_pdbentry_to_view",
276                       new Object[]
277                       { pdbentry.getId(), topView.getTitle() }),
278               MessageManager
279                       .getString("label.align_to_existing_structure_view"),
280               JOptionPane.YES_NO_CANCEL_OPTION);
281       if (option == JOptionPane.CANCEL_OPTION)
282       {
283         return;
284       }
285       if (option == JOptionPane.YES_OPTION)
286       {
287         topView.useAlignmentPanelForSuperposition(ap);
288         topView.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
289         return;
290       }
291     }
292     // /////////////////////////////////
293     openNewChimera(ap, new PDBEntry[]
294     { pdbentry }, new SequenceI[][]
295     { seq });
296   }
297
298   private void openNewChimera(AlignmentPanel ap, PDBEntry[] pdbentrys,
299           SequenceI[][] seqs)
300   {
301     progressBar = ap.alignFrame;
302     jmb = new JalviewChimeraBindingModel(this,
303             ap.getStructureSelectionManager(), pdbentrys, seqs, null, null);
304     addAlignmentPanel(ap);
305     useAlignmentPanelForColourbyseq(ap);
306     if (pdbentrys.length > 1)
307     {
308       alignAddedStructures = true;
309       useAlignmentPanelForSuperposition(ap);
310     }
311     jmb.setColourBySequence(true);
312     setSize(400, 400); // probably should be a configurable/dynamic default here
313     initMenus();
314     worker = null;
315     {
316       addingStructures = false;
317       worker = new Thread(this);
318       worker.start();
319     }
320     this.addInternalFrameListener(new InternalFrameAdapter()
321     {
322       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
323       {
324         closeViewer();
325       }
326     });
327
328   }
329
330   /**
331    * create a new viewer containing several structures superimposed using the
332    * given alignPanel.
333    * 
334    * @param ap
335    * @param pe
336    * @param seqs
337    */
338   public ChimeraViewFrame(AlignmentPanel ap, PDBEntry[] pe,
339           SequenceI[][] seqs)
340   {
341     super();
342     openNewChimera(ap, pe, seqs);
343   }
344
345   /**
346    * Create a new viewer from saved session state data.
347    * 
348    * @param viewerData
349    * @param af
350    */
351   public ChimeraViewFrame(ViewerData viewerData, AlignFrame af)
352   {
353     super();
354     String chimeraSessionFile = viewerData.stateData;
355     openNewChimera(af.alignPanel, new PDBEntry[]
356     {}, new SequenceI[][]
357     {});
358     initChimera("open " + chimeraSessionFile);
359     // TODO restore mappings
360   }
361
362   /**
363    * add a new structure (with associated sequences and chains) to this viewer,
364    * retrieving it if necessary first.
365    * 
366    * @param pdbentry
367    * @param seq
368    * @param chains
369    * @param alignFrame
370    * @param align
371    *          if true, new structure(s) will be align using associated alignment
372    */
373   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
374           final String[] chains, final boolean b,
375           final IProgressIndicator alignFrame)
376   {
377     if (pdbentry.getFile() == null)
378     {
379       if (worker != null && worker.isAlive())
380       {
381         // a retrieval is in progress, wait around and add ourselves to the
382         // queue.
383         new Thread(new Runnable()
384         {
385           public void run()
386           {
387             while (worker != null && worker.isAlive() && _started)
388             {
389               try
390               {
391                 Thread.sleep(100 + ((int) Math.random() * 100));
392
393               } catch (Exception e)
394               {
395               }
396
397             }
398             // and call ourselves again.
399             addStructure(pdbentry, seq, chains, b, alignFrame);
400           }
401         }).start();
402         return;
403       }
404     }
405     // otherwise, start adding the structure.
406     jmb.addSequenceAndChain(new PDBEntry[]
407     { pdbentry }, new SequenceI[][]
408     { seq }, new String[][]
409     { chains });
410     addingStructures = true;
411     _started = false;
412     alignAddedStructures = b;
413     progressBar = alignFrame; // visual indication happens on caller frame.
414     (worker = new Thread(this)).start();
415     return;
416   }
417
418   private List<ChimeraViewFrame> getChimeraWindowsFor(AlignmentPanel apanel)
419   {
420     List<ChimeraViewFrame> result = new ArrayList<ChimeraViewFrame>();
421     JInternalFrame[] frames = Desktop.instance.getAllFrames();
422
423     for (JInternalFrame frame : frames)
424     {
425       if (frame instanceof ChimeraViewFrame)
426       {
427         if (((StructureViewerBase) frame).isLinkedWith(apanel))
428         {
429           result.add((ChimeraViewFrame) frame);
430         }
431       }
432     }
433     return result;
434   }
435
436   void initChimera(String command)
437   {
438     jmb.setFinishedInit(false);
439     // TODO: consider waiting until the structure/view is fully loaded before
440     // displaying
441     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle("Chimera", true),
442             getBounds().width, getBounds().height);
443     if (command == null)
444     {
445       command = "";
446     }
447     jmb.evalStateCommand(command, false);
448     jmb.setFinishedInit(true);
449   }
450
451   void setChainMenuItems(List<String> chainNames)
452   {
453     chainMenu.removeAll();
454     if (chainNames == null)
455     {
456       return;
457     }
458     JMenuItem menuItem = new JMenuItem(
459             MessageManager.getString("label.all"));
460     menuItem.addActionListener(new ActionListener()
461     {
462       public void actionPerformed(ActionEvent evt)
463       {
464         allChainsSelected = true;
465         for (int i = 0; i < chainMenu.getItemCount(); i++)
466         {
467           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
468           {
469             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
470           }
471         }
472         centerViewer();
473         allChainsSelected = false;
474       }
475     });
476
477     chainMenu.add(menuItem);
478
479     for (String chainName : chainNames)
480     {
481       menuItem = new JCheckBoxMenuItem(chainName, true);
482       menuItem.addItemListener(new ItemListener()
483       {
484         public void itemStateChanged(ItemEvent evt)
485         {
486           if (!allChainsSelected)
487           {
488             centerViewer();
489           }
490         }
491       });
492
493       chainMenu.add(menuItem);
494     }
495   }
496
497   void centerViewer()
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.centerViewer(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   public void closeViewer()
520   {
521     if (jmb.isChimeraRunning())
522     {
523       String prompt = MessageManager
524               .formatMessage("label.confirm_close_chimera", new Object[]
525               { jmb.getViewerTitle("Chimera", false) });
526       prompt = JvSwingUtils.wrapTooltip(true, prompt);
527       int confirm = JOptionPane.showConfirmDialog(this, prompt,
528               MessageManager.getString("label.close_viewer"),
529               JOptionPane.YES_NO_OPTION);
530       jmb.closeViewer(confirm == JOptionPane.YES_OPTION);
531     }
532     setAlignmentPanel(null);
533     _aps.clear();
534     _alignwith.clear();
535     _colourwith.clear();
536     // TODO: check for memory leaks where instance isn't finalised because jmb
537     // holds a reference to the window
538     jmb = null;
539   }
540
541   /**
542    * Open any newly added PDB structures in Chimera, having first fetched data
543    * from PDB (if not already saved).
544    */
545   public void run()
546   {
547     _started = true;
548     // todo - record which pdbids were successfully imported.
549     StringBuilder errormsgs = new StringBuilder(128);
550     StringBuilder files = new StringBuilder(128);
551     List<PDBEntry> filePDB = new ArrayList<PDBEntry>();
552     List<Integer> filePDBpos = new ArrayList<Integer>();
553     PDBEntry thePdbEntry = null;
554     try
555     {
556       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
557       // TODO: replace with reference fetching/transfer code (validate PDBentry
558       // as a DBRef?)
559       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
560       {
561         String file = null;
562         thePdbEntry = jmb.getPdbEntry(pi);
563         if (thePdbEntry.getFile() == null)
564         {
565           /*
566            * Retrieve PDB data, save to file, attach to PDBEntry
567            */
568           file = fetchPdbFile(thePdbEntry);
569           if (file == null)
570           {
571             errormsgs.append("'" + thePdbEntry.getId() + "' ");
572           }
573         }
574         else
575         {
576           /*
577            * Got file already - ignore if already loaded in Chimera.
578            */
579           file = new File(thePdbEntry.getFile()).getAbsoluteFile()
580                   .getPath();
581           if (curfiles != null && curfiles.length > 0)
582           {
583             addingStructures = true; // already files loaded.
584             for (int c = 0; c < curfiles.length; c++)
585             {
586               if (curfiles[c].equals(file))
587               {
588                 file = null;
589                 break;
590               }
591             }
592           }
593         }
594         if (file != null)
595         {
596           filePDB.add(thePdbEntry);
597           filePDBpos.add(Integer.valueOf(pi));
598           files.append(" \"" + Platform.escapeString(file) + "\"");
599         }
600       }
601     } catch (OutOfMemoryError oomerror)
602     {
603       new OOMWarning("Retrieving PDB files: " + thePdbEntry.getId(),
604               oomerror);
605     } catch (Exception ex)
606     {
607       ex.printStackTrace();
608       errormsgs.append("When retrieving pdbfiles for '"
609               + thePdbEntry.getId() + "'");
610     }
611     if (errormsgs.length() > 0)
612     {
613
614       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
615               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
616                       new Object[]
617                       { errormsgs.toString() }), MessageManager
618               .getString("label.couldnt_load_file"),
619               JOptionPane.ERROR_MESSAGE);
620     }
621
622     if (files.length() > 0)
623     {
624       if (!addingStructures)
625       {
626         try
627         {
628           initChimera("");
629         } catch (Exception ex)
630         {
631           Cache.log.error("Couldn't open Chimera viewer!", ex);
632         }
633       }
634       int num = -1;
635       for (PDBEntry pe : filePDB)
636       {
637         num++;
638         if (pe.getFile() != null)
639         {
640           try
641           {
642             int pos = filePDBpos.get(num).intValue();
643             jmb.openFile(pe);
644             jmb.addSequence(pos, jmb.getSequence()[pos]);
645             File fl = new File(pe.getFile());
646             String protocol = AppletFormatAdapter.URL;
647             try
648             {
649               if (fl.exists())
650               {
651                 protocol = AppletFormatAdapter.FILE;
652               }
653             } catch (Throwable e)
654             {
655             }
656             // Explicitly map to the filename used by Chimera ;
657             // TODO: use pe.getId() instead of pe.getFile() ?
658             jmb.getSsm().setMapping(jmb.getSequence()[pos], null,
659                     pe.getFile(),
660                     protocol);
661           } catch (OutOfMemoryError oomerror)
662           {
663             new OOMWarning(
664                     "When trying to open and map structures from Chimera!",
665                     oomerror);
666           } catch (Exception ex)
667           {
668             Cache.log.error("Couldn't open " + pe.getFile()
669                     + " in Chimera viewer!", ex);
670           } finally
671           {
672             Cache.log.debug("File locations are " + files);
673           }
674         }
675       }
676       jmb.setFinishedInit(true);
677       jmb.setLoadingFromArchive(false);
678
679       // refresh the sequence colours for the new structure(s)
680       for (AlignmentPanel ap : _colourwith)
681       {
682         jmb.updateColours(ap);
683       }
684       // do superposition if asked to
685       if (alignAddedStructures)
686       {
687         new Thread(new Runnable()
688         {
689           public void run()
690           {
691             alignStructs_withAllAlignPanels();
692           }
693         }).start();
694         alignAddedStructures = false;
695       }
696       addingStructures = false;
697     }
698     _started = false;
699     worker = null;
700   }
701
702   /**
703    * Fetch PDB data and save to a local file. Returns the full path to the file,
704    * or null if fetch fails.
705    * 
706    * @param processingEntry
707    * @return
708    * @throws Exception
709    */
710   private String fetchPdbFile(PDBEntry processingEntry) throws Exception
711   {
712     String filePath = null;
713     Pdb pdbclient = new Pdb();
714     AlignmentI pdbseq = null;
715     String pdbid = processingEntry.getId();
716     long hdl = pdbid.hashCode() - System.currentTimeMillis();
717     if (progressBar != null)
718     {
719       progressBar.setProgressBar(MessageManager.formatMessage(
720               "status.fetching_pdb", new Object[]
721               { pdbid }), hdl);
722     }
723     try
724     {
725       pdbseq = pdbclient.getSequenceRecords(pdbid);
726     } catch (OutOfMemoryError oomerror)
727     {
728       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
729     } finally
730     {
731       if (progressBar != null)
732       {
733         progressBar
734                 .setProgressBar(
735                         pdbid
736                                 + " "
737                                 + MessageManager
738                                         .getString("label.state_completed"),
739                         hdl);
740       }
741     }
742     /*
743      * If PDB data were saved and are not invalid (empty alignment), return the
744      * file path.
745      */
746     if (pdbseq != null && pdbseq.getHeight() > 0)
747     {
748       // just use the file name from the first sequence's first PDBEntry
749       filePath = new File(((PDBEntry) pdbseq.getSequenceAt(0).getPDBId()
750               .elementAt(0)).getFile()).getAbsolutePath();
751       processingEntry.setFile(filePath);
752     }
753     return filePath;
754   }
755
756   @Override
757   public void pdbFile_actionPerformed(ActionEvent actionEvent)
758   {
759     JalviewFileChooser chooser = new JalviewFileChooser(
760             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
761
762     chooser.setFileView(new JalviewFileView());
763     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
764     chooser.setToolTipText(MessageManager.getString("action.save"));
765
766     int value = chooser.showSaveDialog(this);
767
768     if (value == JalviewFileChooser.APPROVE_OPTION)
769     {
770       BufferedReader in = null;
771       try
772       {
773         // TODO: cope with multiple PDB files in view
774         in = new BufferedReader(new FileReader(jmb.getPdbFile()[0]));
775         File outFile = chooser.getSelectedFile();
776
777         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
778         String data;
779         while ((data = in.readLine()) != null)
780         {
781           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
782           {
783             out.println(data);
784           }
785         }
786         out.close();
787       } catch (Exception ex)
788       {
789         ex.printStackTrace();
790       } finally
791       {
792         if (in != null)
793         {
794           try
795           {
796             in.close();
797           } catch (IOException e)
798           {
799             e.printStackTrace();
800           }
801         }
802       }
803     }
804   }
805
806   @Override
807   public void viewMapping_actionPerformed(ActionEvent actionEvent)
808   {
809     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
810     try
811     {
812       for (int pdbe = 0; pdbe < jmb.getPdbCount(); pdbe++)
813       {
814         cap.appendText(jmb.printMapping(jmb.getPdbEntry(pdbe).getFile()));
815         cap.appendText("\n");
816       }
817     } catch (OutOfMemoryError e)
818     {
819       new OOMWarning(
820               "composing sequence-structure alignments for display in text box.",
821               e);
822       cap.dispose();
823       return;
824     }
825     jalview.gui.Desktop.addInternalFrame(cap,
826             MessageManager.getString("label.pdb_sequence_mapping"), 550,
827             600);
828   }
829
830   @Override
831   public void eps_actionPerformed(ActionEvent e)
832   {
833     throw new Error(
834             MessageManager
835                     .getString("error.eps_generation_not_implemented"));
836   }
837
838   @Override
839   public void png_actionPerformed(ActionEvent e)
840   {
841     throw new Error(
842             MessageManager
843                     .getString("error.png_generation_not_implemented"));
844   }
845
846   @Override
847   public void viewerColour_actionPerformed(ActionEvent actionEvent)
848   {
849     if (viewerColour.isSelected())
850     {
851       // disable automatic sequence colouring.
852       jmb.setColourBySequence(false);
853     }
854   }
855
856   @Override
857   public void seqColour_actionPerformed(ActionEvent actionEvent)
858   {
859     jmb.setColourBySequence(seqColour.isSelected());
860     if (_colourwith == null)
861     {
862       _colourwith = new Vector<AlignmentPanel>();
863     }
864     if (jmb.isColourBySequence())
865     {
866       if (!jmb.isLoadingFromArchive())
867       {
868         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
869         {
870           // Make the currently displayed alignment panel the associated view
871           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
872         }
873       }
874       // Set the colour using the current view for the associated alignframe
875       for (AlignmentPanel ap : _colourwith)
876       {
877         jmb.colourBySequence(ap.av.showSequenceFeatures, ap);
878       }
879     }
880   }
881
882   @Override
883   public void chainColour_actionPerformed(ActionEvent actionEvent)
884   {
885     chainColour.setSelected(true);
886     jmb.colourByChain();
887   }
888
889   @Override
890   public void chargeColour_actionPerformed(ActionEvent actionEvent)
891   {
892     chargeColour.setSelected(true);
893     jmb.colourByCharge();
894   }
895
896   @Override
897   public void zappoColour_actionPerformed(ActionEvent actionEvent)
898   {
899     zappoColour.setSelected(true);
900     jmb.setJalviewColourScheme(new ZappoColourScheme());
901   }
902
903   @Override
904   public void taylorColour_actionPerformed(ActionEvent actionEvent)
905   {
906     taylorColour.setSelected(true);
907     jmb.setJalviewColourScheme(new TaylorColourScheme());
908   }
909
910   @Override
911   public void hydroColour_actionPerformed(ActionEvent actionEvent)
912   {
913     hydroColour.setSelected(true);
914     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
915   }
916
917   @Override
918   public void helixColour_actionPerformed(ActionEvent actionEvent)
919   {
920     helixColour.setSelected(true);
921     jmb.setJalviewColourScheme(new HelixColourScheme());
922   }
923
924   @Override
925   public void strandColour_actionPerformed(ActionEvent actionEvent)
926   {
927     strandColour.setSelected(true);
928     jmb.setJalviewColourScheme(new StrandColourScheme());
929   }
930
931   @Override
932   public void turnColour_actionPerformed(ActionEvent actionEvent)
933   {
934     turnColour.setSelected(true);
935     jmb.setJalviewColourScheme(new TurnColourScheme());
936   }
937
938   @Override
939   public void buriedColour_actionPerformed(ActionEvent actionEvent)
940   {
941     buriedColour.setSelected(true);
942     jmb.setJalviewColourScheme(new BuriedColourScheme());
943   }
944
945   @Override
946   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
947   {
948     setJalviewColourScheme(new PurinePyrimidineColourScheme());
949   }
950
951   @Override
952   public void userColour_actionPerformed(ActionEvent actionEvent)
953   {
954     userColour.setSelected(true);
955     new UserDefinedColours(this, null);
956   }
957
958   @Override
959   public void backGround_actionPerformed(ActionEvent actionEvent)
960   {
961     java.awt.Color col = JColorChooser
962             .showDialog(this, MessageManager
963                     .getString("label.select_backgroud_colour"), null);
964     if (col != null)
965     {
966       jmb.setBackgroundColour(col);
967     }
968   }
969
970   @Override
971   public void showHelp_actionPerformed(ActionEvent actionEvent)
972   {
973     try
974     {
975       jalview.util.BrowserLauncher
976               .openURL("https://www.cgl.ucsf.edu/chimera/docs/UsersGuide");
977     } catch (Exception ex)
978     {
979     }
980   }
981
982   public void updateTitleAndMenus()
983   {
984     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
985     {
986       repaint();
987       return;
988     }
989     setChainMenuItems(jmb.chainNames);
990
991     this.setTitle(jmb.getViewerTitle("Chimera", true));
992     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
993     {
994       viewerActionMenu.setVisible(true);
995     }
996     if (!jmb.isLoadingFromArchive())
997     {
998       seqColour_actionPerformed(null);
999     }
1000   }
1001
1002   /*
1003    * (non-Javadoc)
1004    * 
1005    * @see
1006    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1007    * .ActionEvent)
1008    */
1009   @Override
1010   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1011   {
1012     alignStructs_withAllAlignPanels();
1013   }
1014
1015   private void alignStructs_withAllAlignPanels()
1016   {
1017     if (getAlignmentPanel() == null)
1018     {
1019       return;
1020     }
1021     ;
1022     if (_alignwith.size() == 0)
1023     {
1024       _alignwith.add(getAlignmentPanel());
1025     }
1026     ;
1027     try
1028     {
1029       AlignmentI[] als = new Alignment[_alignwith.size()];
1030       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1031       int[] alm = new int[_alignwith.size()];
1032       int a = 0;
1033
1034       for (AlignmentPanel ap : _alignwith)
1035       {
1036         als[a] = ap.av.getAlignment();
1037         alm[a] = -1;
1038         alc[a++] = ap.av.getColumnSelection();
1039       }
1040       jmb.superposeStructures(als, alm, alc);
1041     } catch (Exception e)
1042     {
1043       StringBuffer sp = new StringBuffer();
1044       for (AlignmentPanel ap : _alignwith)
1045       {
1046         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1047       }
1048       Cache.log.info("Couldn't align structures with the " + sp.toString()
1049               + "associated alignment panels.", e);
1050
1051     }
1052
1053   }
1054
1055   public void setJalviewColourScheme(ColourSchemeI ucs)
1056   {
1057     jmb.setJalviewColourScheme(ucs);
1058
1059   }
1060
1061   /**
1062    * 
1063    * @param alignment
1064    * @return first alignment panel displaying given alignment, or the default
1065    *         alignment panel
1066    */
1067   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1068   {
1069     for (AlignmentPanel ap : getAllAlignmentPanels())
1070     {
1071       if (ap.av.getAlignment() == alignment)
1072       {
1073         return ap;
1074       }
1075     }
1076     return getAlignmentPanel();
1077   }
1078
1079   @Override
1080   public AAStructureBindingModel getBinding()
1081   {
1082     return jmb;
1083   }
1084
1085   /**
1086    * Ask Chimera to save its session to the designated file path. Returns true
1087    * if successful, else false.
1088    * 
1089    * @param filepath
1090    * @see getStateInfo
1091    */
1092   public boolean saveSession(String filepath)
1093   {
1094     boolean result = jmb.saveSession(filepath);
1095     if (result)
1096     {
1097       this.chimeraSessionFile = filepath;
1098     }
1099     return result;
1100   }
1101
1102   /**
1103    * Returns the file path of the Chimera session file the last time it was
1104    * saved. If it was never saved, returns an empty string. There is no
1105    * guarantee that the Chimera session has not changed since it was saved.
1106    */
1107   @Override
1108   public String getStateInfo()
1109   {
1110     return this.chimeraSessionFile;
1111   }
1112 }