JAL-1824 updated caching procedure for pdb entries. Also refactored getPDBEntry metho...
[jalview.git] / src / jalview / gui / AppJmol.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.gui.StructureViewer.ViewerType;
30 import jalview.io.AppletFormatAdapter;
31 import jalview.io.JalviewFileChooser;
32 import jalview.io.JalviewFileView;
33 import jalview.schemes.BuriedColourScheme;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.schemes.HelixColourScheme;
36 import jalview.schemes.HydrophobicColourScheme;
37 import jalview.schemes.PurinePyrimidineColourScheme;
38 import jalview.schemes.StrandColourScheme;
39 import jalview.schemes.TaylorColourScheme;
40 import jalview.schemes.TurnColourScheme;
41 import jalview.schemes.ZappoColourScheme;
42 import jalview.structures.models.AAStructureBindingModel;
43 import jalview.util.MessageManager;
44 import jalview.util.Platform;
45
46 import java.awt.BorderLayout;
47 import java.awt.Color;
48 import java.awt.Dimension;
49 import java.awt.Font;
50 import java.awt.Graphics;
51 import java.awt.Rectangle;
52 import java.awt.event.ActionEvent;
53 import java.awt.event.ActionListener;
54 import java.awt.event.ItemEvent;
55 import java.awt.event.ItemListener;
56 import java.io.BufferedReader;
57 import java.io.File;
58 import java.io.FileOutputStream;
59 import java.io.FileReader;
60 import java.io.IOException;
61 import java.io.PrintWriter;
62 import java.util.Vector;
63
64 import javax.swing.JCheckBoxMenuItem;
65 import javax.swing.JColorChooser;
66 import javax.swing.JInternalFrame;
67 import javax.swing.JMenu;
68 import javax.swing.JMenuItem;
69 import javax.swing.JOptionPane;
70 import javax.swing.JPanel;
71 import javax.swing.JSplitPane;
72 import javax.swing.event.InternalFrameAdapter;
73 import javax.swing.event.InternalFrameEvent;
74 import javax.swing.event.MenuEvent;
75 import javax.swing.event.MenuListener;
76
77 public class AppJmol extends StructureViewerBase
78 {
79   AppJmolBinding jmb;
80
81   JPanel scriptWindow;
82
83   JSplitPane splitPane;
84
85   RenderPanel renderPanel;
86
87   private boolean addingStructures = false;
88
89   ViewSelectionMenu seqColourBy;
90
91   /**
92    * 
93    * @param files
94    * @param ids
95    * @param seqs
96    * @param ap
97    * @param usetoColour
98    *          - add the alignment panel to the list used for colouring these
99    *          structures
100    * @param useToAlign
101    *          - add the alignment panel to the list used for aligning these
102    *          structures
103    * @param leaveColouringToJmol
104    *          - do not update the colours from any other source. Jmol is
105    *          handling them
106    * @param loadStatus
107    * @param bounds
108    * @param viewid
109    */
110   public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
111           AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
112           boolean leaveColouringToJmol, String loadStatus,
113           Rectangle bounds, String viewid)
114   {
115     PDBEntry[] pdbentrys = new PDBEntry[files.length];
116     for (int i = 0; i < pdbentrys.length; i++)
117     {
118       // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
119       PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
120               files[i]);
121       pdbentrys[i] = pdbentry;
122     }
123     // / TODO: check if protocol is needed to be set, and if chains are
124     // autodiscovered.
125     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
126             pdbentrys, seqs, null, null);
127
128     jmb.setLoadingFromArchive(true);
129     addAlignmentPanel(ap);
130     if (useToAlign)
131     {
132       useAlignmentPanelForSuperposition(ap);
133     }
134     if (leaveColouringToJmol || !usetoColour)
135     {
136       jmb.setColourBySequence(false);
137       seqColour.setSelected(false);
138       viewerColour.setSelected(true);
139     }
140     else if (usetoColour)
141     {
142       useAlignmentPanelForColourbyseq(ap);
143       jmb.setColourBySequence(true);
144       seqColour.setSelected(true);
145       viewerColour.setSelected(false);
146     }
147     this.setBounds(bounds);
148     initMenus();
149     setViewId(viewid);
150     // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
151     // bounds.width,bounds.height);
152
153     this.addInternalFrameListener(new InternalFrameAdapter()
154     {
155       @Override
156       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
157       {
158         closeViewer(false);
159       }
160     });
161     initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
162
163   }
164
165   private void initMenus()
166   {
167     seqColour.setSelected(jmb.isColourBySequence());
168     viewerColour.setSelected(!jmb.isColourBySequence());
169     if (_colourwith == null)
170     {
171       _colourwith = new Vector<AlignmentPanel>();
172     }
173     if (_alignwith == null)
174     {
175       _alignwith = new Vector<AlignmentPanel>();
176     }
177
178     seqColourBy = new ViewSelectionMenu(MessageManager.getString("label.colour_by"), this, _colourwith,
179             new ItemListener()
180             {
181
182               @Override
183               public void itemStateChanged(ItemEvent e)
184               {
185                 if (!seqColour.isSelected())
186                 {
187                   seqColour.doClick();
188                 }
189                 else
190                 {
191                   // update the jmol display now.
192                   seqColour_actionPerformed(null);
193                 }
194               }
195             });
196     viewMenu.add(seqColourBy);
197     final ItemListener handler;
198     JMenu alpanels = new ViewSelectionMenu(MessageManager.getString("label.superpose_with"), this,
199             _alignwith, handler = new ItemListener()
200             {
201
202               @Override
203               public void itemStateChanged(ItemEvent e)
204               {
205                 alignStructs.setEnabled(_alignwith.size() > 0);
206                 alignStructs.setToolTipText(MessageManager
207                         .formatMessage(
208                                 "label.align_structures_using_linked_alignment_views",
209                                 new String[]
210                                 { new Integer(_alignwith.size()).toString() }));
211               }
212             });
213     handler.itemStateChanged(null);
214     viewerActionMenu.add(alpanels);
215     viewerActionMenu.addMenuListener(new MenuListener()
216     {
217
218       @Override
219       public void menuSelected(MenuEvent e)
220       {
221         handler.itemStateChanged(null);
222       }
223
224       @Override
225       public void menuDeselected(MenuEvent e)
226       {
227         // TODO Auto-generated method stub
228
229       }
230
231       @Override
232       public void menuCanceled(MenuEvent e)
233       {
234         // TODO Auto-generated method stub
235
236       }
237     });
238   }
239
240   IProgressIndicator progressBar = null;
241
242   /**
243    * add a single PDB structure to a new or existing Jmol view
244    * 
245    * @param pdbentry
246    * @param seq
247    * @param chains
248    * @param ap
249    */
250   public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
251           final AlignmentPanel ap)
252   {
253     progressBar = ap.alignFrame;
254     // ////////////////////////////////
255     // Is the pdb file already loaded?
256     String alreadyMapped = ap.getStructureSelectionManager()
257             .alreadyMappedToFile(pdbentry.getId());
258
259     if (alreadyMapped != null)
260     {
261       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
262               MessageManager.formatMessage(
263                       "label.pdb_entry_is_already_displayed", new String[]
264                       { pdbentry.getId() }), MessageManager.formatMessage(
265                       "label.map_sequences_to_visible_window", new String[]
266                       { pdbentry.getId() }),
267               JOptionPane.YES_NO_CANCEL_OPTION);
268
269       if (option == JOptionPane.CANCEL_OPTION)
270       {
271         return;
272       }
273       if (option == JOptionPane.YES_OPTION)
274       {
275         // TODO : Fix multiple seq to one chain issue here.
276         ap.getStructureSelectionManager().setMapping(seq, chains,
277                 alreadyMapped, AppletFormatAdapter.FILE);
278         if (ap.getSeqPanel().seqCanvas.fr != null)
279         {
280           ap.getSeqPanel().seqCanvas.fr.featuresAdded();
281           ap.paintAlignment(true);
282         }
283
284         // Now this AppJmol is mapped to new sequences. We must add them to
285         // the exisiting array
286         JInternalFrame[] frames = Desktop.instance.getAllFrames();
287
288         for (int i = 0; i < frames.length; i++)
289         {
290           if (frames[i] instanceof AppJmol)
291           {
292             final AppJmol topJmol = ((AppJmol) frames[i]);
293             // JBPNOTE: this looks like a binding routine, rather than a gui
294             // routine
295             for (int pe = 0; pe < topJmol.jmb.getPdbCount(); pe++)
296             {
297               if (topJmol.jmb.getPdbEntry(pe).getFile()
298                       .equals(alreadyMapped))
299               {
300                 topJmol.jmb.addSequence(pe, seq);
301                 topJmol.addAlignmentPanel(ap);
302                 // add it to the set used for colouring
303                 topJmol.useAlignmentPanelForColourbyseq(ap);
304                 topJmol.buildActionMenu();
305                 ap.getStructureSelectionManager()
306                         .sequenceColoursChanged(ap);
307                 break;
308               }
309             }
310           }
311         }
312
313         return;
314       }
315     }
316
317     /*
318      * Check if there are other Jmol views involving this alignment and prompt
319      * user about adding this molecule to one of them
320      */
321     for (AppJmol topJmol : getJmolsFor(ap))
322     {
323       // TODO: highlight topJmol in view somehow
324       int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
325               MessageManager.formatMessage("label.add_pdbentry_to_view",
326                       new String[]
327                       { pdbentry.getId(), topJmol.getTitle() }),
328               MessageManager
329                       .getString("label.align_to_existing_structure_view"),
330               JOptionPane.YES_NO_CANCEL_OPTION);
331       if (option == JOptionPane.CANCEL_OPTION)
332       {
333         return;
334       }
335       if (option == JOptionPane.YES_OPTION)
336       {
337         topJmol.useAlignmentPanelForSuperposition(ap);
338         topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
339         return;
340       }
341     }
342     // /////////////////////////////////
343     openNewJmol(ap, new PDBEntry[]
344     { pdbentry }, new SequenceI[][]
345     { seq });
346   }
347
348   private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
349           SequenceI[][] seqs)
350   {
351     progressBar = ap.alignFrame;
352     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
353             pdbentrys, seqs, null, null);
354     addAlignmentPanel(ap);
355     useAlignmentPanelForColourbyseq(ap);
356     if (pdbentrys.length > 1)
357     {
358       alignAddedStructures = true;
359       useAlignmentPanelForSuperposition(ap);
360     }
361     jmb.setColourBySequence(true);
362     setSize(400, 400); // probably should be a configurable/dynamic default here
363     initMenus();
364     worker = null;
365     {
366       addingStructures = false;
367       worker = new Thread(this);
368       worker.start();
369     }
370     this.addInternalFrameListener(new InternalFrameAdapter()
371     {
372       @Override
373       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
374       {
375         closeViewer(false);
376       }
377     });
378
379   }
380
381   /**
382    * create a new Jmol containing several structures superimposed using the
383    * given alignPanel.
384    * 
385    * @param ap
386    * @param pe
387    * @param seqs
388    */
389   public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
390   {
391     openNewJmol(ap, pe, seqs);
392   }
393
394   /**
395    * pdb retrieval thread.
396    */
397   private Thread worker = null;
398
399   /**
400    * add a new structure (with associated sequences and chains) to this viewer,
401    * retrieving it if necessary first.
402    * 
403    * @param pdbentry
404    * @param seq
405    * @param chains
406    * @param alignFrame
407    * @param align
408    *          if true, new structure(s) will be align using associated alignment
409    */
410   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
411           final String[] chains, final boolean b,
412           final IProgressIndicator alignFrame)
413   {
414     if (pdbentry.getFile() == null)
415     {
416       if (worker != null && worker.isAlive())
417       {
418         // a retrieval is in progress, wait around and add ourselves to the
419         // queue.
420         new Thread(new Runnable()
421         {
422           public void run()
423           {
424             while (worker != null && worker.isAlive() && _started)
425             {
426               try
427               {
428                 Thread.sleep(100 + ((int) Math.random() * 100));
429
430               } catch (Exception e)
431               {
432               }
433
434             }
435             // and call ourselves again.
436             addStructure(pdbentry, seq, chains, b, alignFrame);
437           }
438         }).start();
439         return;
440       }
441     }
442     // otherwise, start adding the structure.
443     jmb.addSequenceAndChain(new PDBEntry[]
444     { pdbentry }, new SequenceI[][]
445     { seq }, new String[][]
446     { chains });
447     addingStructures = true;
448     _started = false;
449     alignAddedStructures = b;
450     progressBar = alignFrame; // visual indication happens on caller frame.
451     (worker = new Thread(this)).start();
452     return;
453   }
454
455   private Vector<AppJmol> getJmolsFor(AlignmentPanel apanel)
456   {
457     Vector<AppJmol> result = new Vector<AppJmol>();
458     JInternalFrame[] frames = Desktop.instance.getAllFrames();
459
460     for (JInternalFrame frame : frames)
461     {
462       if (frame instanceof AppJmol)
463       {
464         if (((AppJmol) frame).isLinkedWith(apanel))
465         {
466           result.addElement((AppJmol) frame);
467         }
468       }
469     }
470     return result;
471   }
472
473   void initJmol(String command)
474   {
475     jmb.setFinishedInit(false);
476     renderPanel = new RenderPanel();
477     // TODO: consider waiting until the structure/view is fully loaded before
478     // displaying
479     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
480     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
481             getBounds().width, getBounds().height);
482     if (scriptWindow == null)
483     {
484       BorderLayout bl = new BorderLayout();
485       bl.setHgap(0);
486       bl.setVgap(0);
487       scriptWindow = new JPanel(bl);
488       scriptWindow.setVisible(false);
489     }
490
491     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
492             null);
493     // jmb.newJmolPopup("Jmol");
494     if (command == null)
495     {
496       command = "";
497     }
498     jmb.evalStateCommand(command);
499     jmb.setFinishedInit(true);
500   }
501
502   void setChainMenuItems(Vector<String> chains)
503   {
504     chainMenu.removeAll();
505     if (chains == null)
506     {
507       return;
508     }
509     JMenuItem menuItem = new JMenuItem(
510             MessageManager.getString("label.all"));
511     menuItem.addActionListener(new ActionListener()
512     {
513       public void actionPerformed(ActionEvent evt)
514       {
515         allChainsSelected = true;
516         for (int i = 0; i < chainMenu.getItemCount(); i++)
517         {
518           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
519           {
520             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
521           }
522         }
523         centerViewer();
524         allChainsSelected = false;
525       }
526     });
527
528     chainMenu.add(menuItem);
529
530     for (String chain : chains)
531     {
532       menuItem = new JCheckBoxMenuItem(chain, true);
533       menuItem.addItemListener(new ItemListener()
534       {
535         public void itemStateChanged(ItemEvent evt)
536         {
537           if (!allChainsSelected)
538           {
539             centerViewer();
540           }
541         }
542       });
543
544       chainMenu.add(menuItem);
545     }
546   }
547
548   boolean allChainsSelected = false;
549
550   private boolean alignAddedStructures = false;
551
552   void centerViewer()
553   {
554     Vector<String> toshow = new Vector<String>();
555     for (int i = 0; i < chainMenu.getItemCount(); i++)
556     {
557       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
558       {
559         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
560         if (item.isSelected())
561         {
562           toshow.addElement(item.getText());
563         }
564       }
565     }
566     jmb.centerViewer(toshow);
567   }
568
569   public void closeViewer(boolean closeExternalViewer)
570   {
571     // JMol does not use an external viewer
572     jmb.closeViewer();
573     setAlignmentPanel(null);
574     _aps.clear();
575     _alignwith.clear();
576     _colourwith.clear();
577     // TODO: check for memory leaks where instance isn't finalised because jmb
578     // holds a reference to the window
579     jmb = null;
580   }
581
582   /**
583    * state flag for PDB retrieval thread
584    */
585   private boolean _started = false;
586
587   public void run()
588   {
589     _started = true;
590     String pdbid = "";
591     // todo - record which pdbids were successfuly imported.
592     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
593     try
594     {
595       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
596       // TODO: replace with reference fetching/transfer code (validate PDBentry
597       // as a DBRef?)
598       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
599       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
600       {
601         String file = jmb.getPdbEntry(pi).getFile();
602         if (file == null)
603         {
604           // retrieve the pdb and store it locally
605           AlignmentI pdbseq = null;
606           pdbid = jmb.getPdbEntry(pi).getId();
607           long hdl = pdbid.hashCode() - System.currentTimeMillis();
608           if (progressBar != null)
609           {
610             progressBar.setProgressBar(MessageManager.formatMessage("status.fetching_pdb", new String[]{pdbid}), hdl);
611           }
612           try
613           {
614             pdbseq = pdbclient.getSequenceRecords(pdbid);
615           } catch (OutOfMemoryError oomerror)
616           {
617             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
618           } catch (Exception ex)
619           {
620             ex.printStackTrace();
621             errormsgs.append("'" + pdbid + "'");
622           }
623           if (progressBar != null)
624           {
625             progressBar.setProgressBar(MessageManager.getString("label.state_completed"), hdl);
626           }
627           if (pdbseq != null)
628           {
629             // just transfer the file name from the first sequence's first
630             // PDBEntry
631             file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
632                     .elementAt(0).getFile()).getAbsolutePath();
633             jmb.getPdbEntry(pi).setFile(file);
634
635             files.append(" \"" + Platform.escapeString(file) + "\"");
636           }
637           else
638           {
639             errormsgs.append("'" + pdbid + "' ");
640           }
641         }
642         else
643         {
644           if (curfiles != null && curfiles.length > 0)
645           {
646             addingStructures = true; // already files loaded.
647             for (int c = 0; c < curfiles.length; c++)
648             {
649               if (curfiles[c].equals(file))
650               {
651                 file = null;
652                 break;
653               }
654             }
655           }
656           if (file != null)
657           {
658             files.append(" \"" + Platform.escapeString(file) + "\"");
659           }
660         }
661       }
662     } catch (OutOfMemoryError oomerror)
663     {
664       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
665     } catch (Exception ex)
666     {
667       ex.printStackTrace();
668       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
669               + "'");
670     }
671     if (errormsgs.length() > 0)
672     {
673
674       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
675               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
676                       new String[]
677                       { errormsgs.toString() }), MessageManager
678               .getString("label.couldnt_load_file"),
679               JOptionPane.ERROR_MESSAGE);
680
681     }
682     long lastnotify = jmb.getLoadNotifiesHandled();
683     if (files.length() > 0)
684     {
685       if (!addingStructures)
686       {
687
688         try
689         {
690           initJmol("load FILES " + files.toString());
691         } catch (OutOfMemoryError oomerror)
692         {
693           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
694           Cache.log.debug("File locations are " + files);
695         } catch (Exception ex)
696         {
697           Cache.log.error("Couldn't open Jmol viewer!", ex);
698         }
699       }
700       else
701       {
702         StringBuffer cmd = new StringBuffer();
703         cmd.append("loadingJalviewdata=true\nload APPEND ");
704         cmd.append(files.toString());
705         cmd.append("\nloadingJalviewdata=null");
706         final String command = cmd.toString();
707         cmd = null;
708         lastnotify = jmb.getLoadNotifiesHandled();
709
710         try
711         {
712           jmb.evalStateCommand(command);
713         } catch (OutOfMemoryError oomerror)
714         {
715           new OOMWarning(
716                   "When trying to add structures to the Jmol viewer!",
717                   oomerror);
718           Cache.log.debug("File locations are " + files);
719         } catch (Exception ex)
720         {
721           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
722         }
723       }
724
725       // need to wait around until script has finished
726       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
727               : (!jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
728                       .getPdbFile().length != jmb.getPdbCount()))
729       {
730         try
731         {
732           Cache.log.debug("Waiting around for jmb notify.");
733           Thread.sleep(35);
734         } catch (Exception e)
735         {
736         }
737       }
738
739       // refresh the sequence colours for the new structure(s)
740       for (AlignmentPanel ap : _colourwith)
741       {
742         jmb.updateColours(ap);
743       }
744       // do superposition if asked to
745       if (alignAddedStructures)
746       {
747         javax.swing.SwingUtilities.invokeLater(new Runnable()
748         {
749           public void run()
750           {
751             if (jmb.viewer.isScriptExecuting())
752             {
753               javax.swing.SwingUtilities.invokeLater(this);
754               try
755               {
756                 Thread.sleep(5);
757               } catch (InterruptedException q)
758               {
759               }
760               ;
761               return;
762             }
763             else
764             {
765               alignStructs_withAllAlignPanels();
766             }
767           }
768         });
769         alignAddedStructures = false;
770       }
771       addingStructures = false;
772
773     }
774     _started = false;
775     worker = null;
776   }
777
778   @Override
779   public void pdbFile_actionPerformed(ActionEvent actionEvent)
780   {
781     JalviewFileChooser chooser = new JalviewFileChooser(
782             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
783
784     chooser.setFileView(new JalviewFileView());
785     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
786     chooser.setToolTipText(MessageManager.getString("action.save"));
787
788     int value = chooser.showSaveDialog(this);
789
790     if (value == JalviewFileChooser.APPROVE_OPTION)
791     {
792       BufferedReader in = null;
793       try
794       {
795         // TODO: cope with multiple PDB files in view
796         in = new BufferedReader(new FileReader(
797                 jmb.getPdbFile()[0]));
798         File outFile = chooser.getSelectedFile();
799
800         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
801         String data;
802         while ((data = in.readLine()) != null)
803         {
804           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
805           {
806             out.println(data);
807           }
808         }
809         out.close();
810       } catch (Exception ex)
811       {
812         ex.printStackTrace();
813       } finally
814       {
815         if (in != null)
816         {
817           try
818           {
819             in.close();
820           } catch (IOException e)
821           {
822             // ignore
823           }
824         }
825       }
826     }
827   }
828
829   @Override
830   public void viewMapping_actionPerformed(ActionEvent actionEvent)
831   {
832     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
833     try
834     {
835       cap.appendText(jmb.printMappings());
836     } catch (OutOfMemoryError e)
837     {
838       new OOMWarning(
839               "composing sequence-structure alignments for display in text box.",
840               e);
841       cap.dispose();
842       return;
843     }
844     jalview.gui.Desktop.addInternalFrame(cap,
845             MessageManager.getString("label.pdb_sequence_mapping"), 550,
846             600);
847   }
848
849   @Override
850   public void eps_actionPerformed(ActionEvent e)
851   {
852     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
853   }
854
855   @Override
856   public void png_actionPerformed(ActionEvent e)
857   {
858     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
859   }
860
861   void makePDBImage(jalview.util.ImageMaker.TYPE type)
862   {
863     int width = getWidth();
864     int height = getHeight();
865
866     jalview.util.ImageMaker im;
867
868     if (type == jalview.util.ImageMaker.TYPE.PNG)
869     {
870       im = new jalview.util.ImageMaker(this,
871               jalview.util.ImageMaker.TYPE.PNG,
872               "Make PNG image from view", width, height, null, null);
873     }
874     else if (type == jalview.util.ImageMaker.TYPE.EPS)
875     {
876       im = new jalview.util.ImageMaker(this,
877               jalview.util.ImageMaker.TYPE.EPS,
878               "Make EPS file from view", width, height, null,
879               this.getTitle());
880     }
881     else
882     {
883
884       im = new jalview.util.ImageMaker(this,
885               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
886               width, height, null, this.getTitle());
887     }
888
889     if (im.getGraphics() != null)
890     {
891       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
892       im.writeImage();
893     }
894   }
895
896   @Override
897   public void viewerColour_actionPerformed(ActionEvent actionEvent)
898   {
899     if (viewerColour.isSelected())
900     {
901       // disable automatic sequence colouring.
902       jmb.setColourBySequence(false);
903     }
904   }
905
906   @Override
907   public void seqColour_actionPerformed(ActionEvent actionEvent)
908   {
909     jmb.setColourBySequence(seqColour.isSelected());
910     if (_colourwith == null)
911     {
912       _colourwith = new Vector<AlignmentPanel>();
913     }
914     if (jmb.isColourBySequence())
915     {
916       if (!jmb.isLoadingFromArchive())
917       {
918         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
919         {
920           // Make the currently displayed alignment panel the associated view
921           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
922         }
923       }
924       // Set the colour using the current view for the associated alignframe
925       for (AlignmentPanel ap : _colourwith)
926       {
927         jmb.colourBySequence(ap);
928       }
929     }
930   }
931
932   @Override
933   public void chainColour_actionPerformed(ActionEvent actionEvent)
934   {
935     chainColour.setSelected(true);
936     jmb.colourByChain();
937   }
938
939   @Override
940   public void chargeColour_actionPerformed(ActionEvent actionEvent)
941   {
942     chargeColour.setSelected(true);
943     jmb.colourByCharge();
944   }
945
946   @Override
947   public void zappoColour_actionPerformed(ActionEvent actionEvent)
948   {
949     zappoColour.setSelected(true);
950     jmb.setJalviewColourScheme(new ZappoColourScheme());
951   }
952
953   @Override
954   public void taylorColour_actionPerformed(ActionEvent actionEvent)
955   {
956     taylorColour.setSelected(true);
957     jmb.setJalviewColourScheme(new TaylorColourScheme());
958   }
959
960   @Override
961   public void hydroColour_actionPerformed(ActionEvent actionEvent)
962   {
963     hydroColour.setSelected(true);
964     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
965   }
966
967   @Override
968   public void helixColour_actionPerformed(ActionEvent actionEvent)
969   {
970     helixColour.setSelected(true);
971     jmb.setJalviewColourScheme(new HelixColourScheme());
972   }
973
974   @Override
975   public void strandColour_actionPerformed(ActionEvent actionEvent)
976   {
977     strandColour.setSelected(true);
978     jmb.setJalviewColourScheme(new StrandColourScheme());
979   }
980
981   @Override
982   public void turnColour_actionPerformed(ActionEvent actionEvent)
983   {
984     turnColour.setSelected(true);
985     jmb.setJalviewColourScheme(new TurnColourScheme());
986   }
987
988   @Override
989   public void buriedColour_actionPerformed(ActionEvent actionEvent)
990   {
991     buriedColour.setSelected(true);
992     jmb.setJalviewColourScheme(new BuriedColourScheme());
993   }
994
995   @Override
996   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
997   {
998     setJalviewColourScheme(new PurinePyrimidineColourScheme());
999   }
1000
1001   @Override
1002   public void userColour_actionPerformed(ActionEvent actionEvent)
1003   {
1004     userColour.setSelected(true);
1005     new UserDefinedColours(this, null);
1006   }
1007
1008   @Override
1009   public void backGround_actionPerformed(ActionEvent actionEvent)
1010   {
1011     java.awt.Color col = JColorChooser.showDialog(this,
1012             MessageManager.getString("label.select_backgroud_colour"), null);
1013     if (col != null)
1014     {
1015       jmb.setBackgroundColour(col);
1016     }
1017   }
1018
1019   @Override
1020   public void showHelp_actionPerformed(ActionEvent actionEvent)
1021   {
1022     try
1023     {
1024       jalview.util.BrowserLauncher
1025               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1026     } catch (Exception ex)
1027     {
1028     }
1029   }
1030
1031   public void showConsole(boolean showConsole)
1032   {
1033
1034     if (showConsole)
1035     {
1036       if (splitPane == null)
1037       {
1038         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1039         splitPane.setTopComponent(renderPanel);
1040         splitPane.setBottomComponent(scriptWindow);
1041         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1042         splitPane.setDividerLocation(getHeight() - 200);
1043         scriptWindow.setVisible(true);
1044         scriptWindow.validate();
1045         splitPane.validate();
1046       }
1047
1048     }
1049     else
1050     {
1051       if (splitPane != null)
1052       {
1053         splitPane.setVisible(false);
1054       }
1055
1056       splitPane = null;
1057
1058       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1059     }
1060
1061     validate();
1062   }
1063
1064   class RenderPanel extends JPanel
1065   {
1066     final Dimension currentSize = new Dimension();
1067
1068     @Override
1069     public void paintComponent(Graphics g)
1070     {
1071       getSize(currentSize);
1072
1073       if (jmb != null && jmb.fileLoadingError != null)
1074       {
1075         g.setColor(Color.black);
1076         g.fillRect(0, 0, currentSize.width, currentSize.height);
1077         g.setColor(Color.white);
1078         g.setFont(new Font("Verdana", Font.BOLD, 14));
1079         g.drawString(MessageManager.getString("label.error_loading_file")
1080                 + "...", 20, currentSize.height / 2);
1081         StringBuffer sb = new StringBuffer();
1082         int lines = 0;
1083         for (int e = 0; e < jmb.getPdbCount(); e++)
1084         {
1085           sb.append(jmb.getPdbEntry(e).getId());
1086           if (e < jmb.getPdbCount() - 1)
1087           {
1088             sb.append(",");
1089           }
1090
1091           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1092           {
1093             lines++;
1094             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1095                     * g.getFontMetrics().getHeight());
1096           }
1097         }
1098       }
1099       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1100       {
1101         g.setColor(Color.black);
1102         g.fillRect(0, 0, currentSize.width, currentSize.height);
1103         g.setColor(Color.white);
1104         g.setFont(new Font("Verdana", Font.BOLD, 14));
1105         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1106                 20, currentSize.height / 2);
1107       }
1108       else
1109       {
1110         jmb.viewer.renderScreenImage(g, currentSize.width,
1111                 currentSize.height);
1112       }
1113     }
1114   }
1115
1116   public void updateTitleAndMenus()
1117   {
1118     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1119     {
1120       repaint();
1121       return;
1122     }
1123     setChainMenuItems(jmb.chainNames);
1124
1125     this.setTitle(jmb.getViewerTitle());
1126     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1127     {
1128       viewerActionMenu.setVisible(true);
1129     }
1130     if (!jmb.isLoadingFromArchive())
1131     {
1132       seqColour_actionPerformed(null);
1133     }
1134   }
1135
1136   /*
1137    * (non-Javadoc)
1138    * 
1139    * @see
1140    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1141    * .ActionEvent)
1142    */
1143   @Override
1144   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1145   {
1146     alignStructs_withAllAlignPanels();
1147   }
1148
1149   private void alignStructs_withAllAlignPanels()
1150   {
1151     if (getAlignmentPanel() == null)
1152     {
1153       return;
1154     }
1155     ;
1156     if (_alignwith.size() == 0)
1157     {
1158       _alignwith.add(getAlignmentPanel());
1159     }
1160     ;
1161     try
1162     {
1163       AlignmentI[] als = new Alignment[_alignwith.size()];
1164       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1165       int[] alm = new int[_alignwith.size()];
1166       int a = 0;
1167
1168       for (AlignmentPanel ap : _alignwith)
1169       {
1170         als[a] = ap.av.getAlignment();
1171         alm[a] = -1;
1172         alc[a++] = ap.av.getColumnSelection();
1173       }
1174       jmb.superposeStructures(als, alm, alc);
1175     } catch (Exception e)
1176     {
1177       StringBuffer sp = new StringBuffer();
1178       for (AlignmentPanel ap : _alignwith)
1179       {
1180         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1181       }
1182       Cache.log.info("Couldn't align structures with the " + sp.toString()
1183               + "associated alignment panels.", e);
1184
1185     }
1186
1187   }
1188
1189   public void setJalviewColourScheme(ColourSchemeI ucs)
1190   {
1191     jmb.setJalviewColourScheme(ucs);
1192
1193   }
1194
1195   /**
1196    * 
1197    * @param alignment
1198    * @return first alignment panel displaying given alignment, or the default
1199    *         alignment panel
1200    */
1201   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1202   {
1203     for (AlignmentPanel ap : getAllAlignmentPanels())
1204     {
1205       if (ap.av.getAlignment() == alignment)
1206       {
1207         return ap;
1208       }
1209     }
1210     return getAlignmentPanel();
1211   }
1212
1213   @Override
1214   public AAStructureBindingModel getBinding()
1215   {
1216     return this.jmb;
1217   }
1218
1219   @Override
1220   public String getStateInfo()
1221   {
1222     return jmb == null ? null : jmb.viewer.getStateInfo();
1223   }
1224
1225   @Override
1226   public ViewerType getViewerType()
1227   {
1228     return ViewerType.JMOL;
1229   }
1230
1231 }