JAL-1759 unused field / methods removed
[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.PrintWriter;
61 import java.util.Enumeration;
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     // Check if there are other Jmol views involving this alignment
318     // and prompt user about adding this molecule to one of them
319     Vector existingViews = getJmolsFor(ap);
320     if (existingViews.size() > 0)
321     {
322       Enumeration jm = existingViews.elements();
323       while (jm.hasMoreElements())
324       {
325         AppJmol topJmol = (AppJmol) jm.nextElement();
326         // TODO: highlight topJmol in view somehow
327         int option = JOptionPane
328                 .showInternalConfirmDialog(
329                         Desktop.desktop,
330                         MessageManager.formatMessage(
331                                 "label.add_pdbentry_to_view", new String[]
332                                 { pdbentry.getId(), topJmol.getTitle() }),
333                         MessageManager
334                                 .getString("label.align_to_existing_structure_view"),
335                         JOptionPane.YES_NO_CANCEL_OPTION);
336         if (option == JOptionPane.CANCEL_OPTION)
337         {
338           return;
339         }
340         if (option == JOptionPane.YES_OPTION)
341         {
342           topJmol.useAlignmentPanelForSuperposition(ap);
343           topJmol.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
344           return;
345         }
346       }
347     }
348     // /////////////////////////////////
349     openNewJmol(ap, new PDBEntry[]
350     { pdbentry }, new SequenceI[][]
351     { seq });
352   }
353
354   private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
355           SequenceI[][] seqs)
356   {
357     progressBar = ap.alignFrame;
358     jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
359             pdbentrys, seqs, null, null);
360     addAlignmentPanel(ap);
361     useAlignmentPanelForColourbyseq(ap);
362     if (pdbentrys.length > 1)
363     {
364       alignAddedStructures = true;
365       useAlignmentPanelForSuperposition(ap);
366     }
367     jmb.setColourBySequence(true);
368     setSize(400, 400); // probably should be a configurable/dynamic default here
369     initMenus();
370     worker = null;
371     {
372       addingStructures = false;
373       worker = new Thread(this);
374       worker.start();
375     }
376     this.addInternalFrameListener(new InternalFrameAdapter()
377     {
378       @Override
379       public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
380       {
381         closeViewer(false);
382       }
383     });
384
385   }
386
387   /**
388    * create a new Jmol containing several structures superimposed using the
389    * given alignPanel.
390    * 
391    * @param ap
392    * @param pe
393    * @param seqs
394    */
395   public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
396   {
397     openNewJmol(ap, pe, seqs);
398   }
399
400   /**
401    * pdb retrieval thread.
402    */
403   private Thread worker = null;
404
405   /**
406    * add a new structure (with associated sequences and chains) to this viewer,
407    * retrieving it if necessary first.
408    * 
409    * @param pdbentry
410    * @param seq
411    * @param chains
412    * @param alignFrame
413    * @param align
414    *          if true, new structure(s) will be align using associated alignment
415    */
416   private void addStructure(final PDBEntry pdbentry, final SequenceI[] seq,
417           final String[] chains, final boolean b,
418           final IProgressIndicator alignFrame)
419   {
420     if (pdbentry.getFile() == null)
421     {
422       if (worker != null && worker.isAlive())
423       {
424         // a retrieval is in progress, wait around and add ourselves to the
425         // queue.
426         new Thread(new Runnable()
427         {
428           public void run()
429           {
430             while (worker != null && worker.isAlive() && _started)
431             {
432               try
433               {
434                 Thread.sleep(100 + ((int) Math.random() * 100));
435
436               } catch (Exception e)
437               {
438               }
439
440             }
441             // and call ourselves again.
442             addStructure(pdbentry, seq, chains, b, alignFrame);
443           }
444         }).start();
445         return;
446       }
447     }
448     // otherwise, start adding the structure.
449     jmb.addSequenceAndChain(new PDBEntry[]
450     { pdbentry }, new SequenceI[][]
451     { seq }, new String[][]
452     { chains });
453     addingStructures = true;
454     _started = false;
455     alignAddedStructures = b;
456     progressBar = alignFrame; // visual indication happens on caller frame.
457     (worker = new Thread(this)).start();
458     return;
459   }
460
461   private Vector getJmolsFor(AlignmentPanel apanel)
462   {
463     Vector result = new Vector();
464     JInternalFrame[] frames = Desktop.instance.getAllFrames();
465
466     for (JInternalFrame frame : frames)
467     {
468       if (frame instanceof AppJmol)
469       {
470         if (((StructureViewerBase) frame).isLinkedWith(apanel))
471         {
472           result.addElement(frame);
473         }
474       }
475     }
476     return result;
477   }
478
479   void initJmol(String command)
480   {
481     jmb.setFinishedInit(false);
482     renderPanel = new RenderPanel();
483     // TODO: consider waiting until the structure/view is fully loaded before
484     // displaying
485     this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
486     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
487             getBounds().width, getBounds().height);
488     if (scriptWindow == null)
489     {
490       BorderLayout bl = new BorderLayout();
491       bl.setHgap(0);
492       bl.setVgap(0);
493       scriptWindow = new JPanel(bl);
494       scriptWindow.setVisible(false);
495     }
496     ;
497     jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
498             null);
499     jmb.newJmolPopup("Jmol");
500     if (command == null)
501     {
502       command = "";
503     }
504     jmb.evalStateCommand(command);
505     jmb.setFinishedInit(true);
506   }
507
508   void setChainMenuItems(Vector chains)
509   {
510     chainMenu.removeAll();
511     if (chains == null)
512     {
513       return;
514     }
515     JMenuItem menuItem = new JMenuItem(
516             MessageManager.getString("label.all"));
517     menuItem.addActionListener(new ActionListener()
518     {
519       public void actionPerformed(ActionEvent evt)
520       {
521         allChainsSelected = true;
522         for (int i = 0; i < chainMenu.getItemCount(); i++)
523         {
524           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
525           {
526             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
527           }
528         }
529         centerViewer();
530         allChainsSelected = false;
531       }
532     });
533
534     chainMenu.add(menuItem);
535
536     for (int c = 0; c < chains.size(); c++)
537     {
538       menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
539       menuItem.addItemListener(new ItemListener()
540       {
541         public void itemStateChanged(ItemEvent evt)
542         {
543           if (!allChainsSelected)
544           {
545             centerViewer();
546           }
547         }
548       });
549
550       chainMenu.add(menuItem);
551     }
552   }
553
554   boolean allChainsSelected = false;
555
556   private boolean alignAddedStructures = false;
557
558   void centerViewer()
559   {
560     Vector toshow = new Vector();
561     String lbl;
562     int mlength, p, mnum;
563     for (int i = 0; i < chainMenu.getItemCount(); i++)
564     {
565       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
566       {
567         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
568         if (item.isSelected())
569         {
570           toshow.addElement(item.getText());
571         }
572       }
573     }
574     jmb.centerViewer(toshow);
575   }
576
577   public void closeViewer(boolean closeExternalViewer)
578   {
579     // JMol does not use an external viewer
580     jmb.closeViewer();
581     setAlignmentPanel(null);
582     _aps.clear();
583     _alignwith.clear();
584     _colourwith.clear();
585     // TODO: check for memory leaks where instance isn't finalised because jmb
586     // holds a reference to the window
587     jmb = null;
588   }
589
590   /**
591    * state flag for PDB retrieval thread
592    */
593   private boolean _started = false;
594
595   public void run()
596   {
597     _started = true;
598     String pdbid = "";
599     // todo - record which pdbids were successfuly imported.
600     StringBuffer errormsgs = new StringBuffer(), files = new StringBuffer();
601     try
602     {
603       String[] curfiles = jmb.getPdbFile(); // files currently in viewer
604       // TODO: replace with reference fetching/transfer code (validate PDBentry
605       // as a DBRef?)
606       jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
607       for (int pi = 0; pi < jmb.getPdbCount(); pi++)
608       {
609         String file = jmb.getPdbEntry(pi).getFile();
610         if (file == null)
611         {
612           // retrieve the pdb and store it locally
613           AlignmentI pdbseq = null;
614           pdbid = jmb.getPdbEntry(pi).getId();
615           long hdl = pdbid.hashCode() - System.currentTimeMillis();
616           if (progressBar != null)
617           {
618             progressBar.setProgressBar(MessageManager.formatMessage("status.fetching_pdb", new String[]{pdbid}), hdl);
619           }
620           try
621           {
622             pdbseq = pdbclient.getSequenceRecords(pdbid);
623           } catch (OutOfMemoryError oomerror)
624           {
625             new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
626           } catch (Exception ex)
627           {
628             ex.printStackTrace();
629             errormsgs.append("'" + pdbid + "'");
630           }
631           if (progressBar != null)
632           {
633             progressBar.setProgressBar(MessageManager.getString("label.state_completed"), hdl);
634           }
635           if (pdbseq != null)
636           {
637             // just transfer the file name from the first sequence's first
638             // PDBEntry
639             file = new File(pdbseq.getSequenceAt(0).getPDBId()
640                     .elementAt(0).getFile()).getAbsolutePath();
641             jmb.getPdbEntry(pi).setFile(file);
642
643             files.append(" \"" + Platform.escapeString(file) + "\"");
644           }
645           else
646           {
647             errormsgs.append("'" + pdbid + "' ");
648           }
649         }
650         else
651         {
652           if (curfiles != null && curfiles.length > 0)
653           {
654             addingStructures = true; // already files loaded.
655             for (int c = 0; c < curfiles.length; c++)
656             {
657               if (curfiles[c].equals(file))
658               {
659                 file = null;
660                 break;
661               }
662             }
663           }
664           if (file != null)
665           {
666             files.append(" \"" + Platform.escapeString(file) + "\"");
667           }
668         }
669       }
670     } catch (OutOfMemoryError oomerror)
671     {
672       new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
673     } catch (Exception ex)
674     {
675       ex.printStackTrace();
676       errormsgs.append("When retrieving pdbfiles : current was: '" + pdbid
677               + "'");
678     }
679     if (errormsgs.length() > 0)
680     {
681
682       JOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
683               .formatMessage("label.pdb_entries_couldnt_be_retrieved",
684                       new String[]
685                       { errormsgs.toString() }), MessageManager
686               .getString("label.couldnt_load_file"),
687               JOptionPane.ERROR_MESSAGE);
688
689     }
690     long lastnotify = jmb.getLoadNotifiesHandled();
691     if (files.length() > 0)
692     {
693       if (!addingStructures)
694       {
695
696         try
697         {
698           initJmol("load FILES " + files.toString());
699         } catch (OutOfMemoryError oomerror)
700         {
701           new OOMWarning("When trying to open the Jmol viewer!", oomerror);
702           Cache.log.debug("File locations are " + files);
703         } catch (Exception ex)
704         {
705           Cache.log.error("Couldn't open Jmol viewer!", ex);
706         }
707       }
708       else
709       {
710         StringBuffer cmd = new StringBuffer();
711         cmd.append("loadingJalviewdata=true\nload APPEND ");
712         cmd.append(files.toString());
713         cmd.append("\nloadingJalviewdata=null");
714         final String command = cmd.toString();
715         cmd = null;
716         lastnotify = jmb.getLoadNotifiesHandled();
717
718         try
719         {
720           jmb.evalStateCommand(command);
721         } catch (OutOfMemoryError oomerror)
722         {
723           new OOMWarning(
724                   "When trying to add structures to the Jmol viewer!",
725                   oomerror);
726           Cache.log.debug("File locations are " + files);
727         } catch (Exception ex)
728         {
729           Cache.log.error("Couldn't add files to Jmol viewer!", ex);
730         }
731       }
732
733       // need to wait around until script has finished
734       while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
735               : (jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
736                       .getPdbFile().length != jmb.getPdbCount()))
737       {
738         try
739         {
740           Cache.log.debug("Waiting around for jmb notify.");
741           Thread.sleep(35);
742         } catch (Exception e)
743         {
744         }
745       }
746       // refresh the sequence colours for the new structure(s)
747       for (AlignmentPanel ap : _colourwith)
748       {
749         jmb.updateColours(ap);
750       }
751       // do superposition if asked to
752       if (alignAddedStructures)
753       {
754         javax.swing.SwingUtilities.invokeLater(new Runnable()
755         {
756           public void run()
757           {
758             alignStructs_withAllAlignPanels();
759             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
760           }
761         });
762         alignAddedStructures = false;
763       }
764       addingStructures = false;
765
766     }
767     _started = false;
768     worker = null;
769   }
770
771   @Override
772   public void pdbFile_actionPerformed(ActionEvent actionEvent)
773   {
774     JalviewFileChooser chooser = new JalviewFileChooser(
775             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
776
777     chooser.setFileView(new JalviewFileView());
778     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
779     chooser.setToolTipText(MessageManager.getString("action.save"));
780
781     int value = chooser.showSaveDialog(this);
782
783     if (value == JalviewFileChooser.APPROVE_OPTION)
784     {
785       try
786       {
787         // TODO: cope with multiple PDB files in view
788         BufferedReader in = new BufferedReader(new FileReader(
789                 jmb.getPdbFile()[0]));
790         File outFile = chooser.getSelectedFile();
791
792         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
793         String data;
794         while ((data = in.readLine()) != null)
795         {
796           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
797           {
798             out.println(data);
799           }
800         }
801         out.close();
802       } catch (Exception ex)
803       {
804         ex.printStackTrace();
805       }
806     }
807   }
808
809   @Override
810   public void viewMapping_actionPerformed(ActionEvent actionEvent)
811   {
812     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
813     try
814     {
815       cap.appendText(jmb.printMappings());
816     } catch (OutOfMemoryError e)
817     {
818       new OOMWarning(
819               "composing sequence-structure alignments for display in text box.",
820               e);
821       cap.dispose();
822       return;
823     }
824     jalview.gui.Desktop.addInternalFrame(cap,
825             MessageManager.getString("label.pdb_sequence_mapping"), 550,
826             600);
827   }
828
829   @Override
830   public void eps_actionPerformed(ActionEvent e)
831   {
832     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
833   }
834
835   @Override
836   public void png_actionPerformed(ActionEvent e)
837   {
838     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
839   }
840
841   void makePDBImage(jalview.util.ImageMaker.TYPE type)
842   {
843     int width = getWidth();
844     int height = getHeight();
845
846     jalview.util.ImageMaker im;
847
848     if (type == jalview.util.ImageMaker.TYPE.PNG)
849     {
850       im = new jalview.util.ImageMaker(this,
851               jalview.util.ImageMaker.TYPE.PNG,
852               "Make PNG image from view", width, height, null, null);
853     }
854     else if (type == jalview.util.ImageMaker.TYPE.EPS)
855     {
856       im = new jalview.util.ImageMaker(this,
857               jalview.util.ImageMaker.TYPE.EPS,
858               "Make EPS file from view", width, height, null,
859               this.getTitle());
860     }
861     else
862     {
863
864       im = new jalview.util.ImageMaker(this,
865               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
866               width, height, null, this.getTitle());
867     }
868
869     if (im.getGraphics() != null)
870     {
871       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
872       im.writeImage();
873     }
874   }
875
876   @Override
877   public void viewerColour_actionPerformed(ActionEvent actionEvent)
878   {
879     if (viewerColour.isSelected())
880     {
881       // disable automatic sequence colouring.
882       jmb.setColourBySequence(false);
883     }
884   }
885
886   @Override
887   public void seqColour_actionPerformed(ActionEvent actionEvent)
888   {
889     jmb.setColourBySequence(seqColour.isSelected());
890     if (_colourwith == null)
891     {
892       _colourwith = new Vector<AlignmentPanel>();
893     }
894     if (jmb.isColourBySequence())
895     {
896       if (!jmb.isLoadingFromArchive())
897       {
898         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
899         {
900           // Make the currently displayed alignment panel the associated view
901           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
902         }
903       }
904       // Set the colour using the current view for the associated alignframe
905       for (AlignmentPanel ap : _colourwith)
906       {
907         jmb.colourBySequence(ap.av.isShowSequenceFeatures(), ap);
908       }
909     }
910   }
911
912   @Override
913   public void chainColour_actionPerformed(ActionEvent actionEvent)
914   {
915     chainColour.setSelected(true);
916     jmb.colourByChain();
917   }
918
919   @Override
920   public void chargeColour_actionPerformed(ActionEvent actionEvent)
921   {
922     chargeColour.setSelected(true);
923     jmb.colourByCharge();
924   }
925
926   @Override
927   public void zappoColour_actionPerformed(ActionEvent actionEvent)
928   {
929     zappoColour.setSelected(true);
930     jmb.setJalviewColourScheme(new ZappoColourScheme());
931   }
932
933   @Override
934   public void taylorColour_actionPerformed(ActionEvent actionEvent)
935   {
936     taylorColour.setSelected(true);
937     jmb.setJalviewColourScheme(new TaylorColourScheme());
938   }
939
940   @Override
941   public void hydroColour_actionPerformed(ActionEvent actionEvent)
942   {
943     hydroColour.setSelected(true);
944     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
945   }
946
947   @Override
948   public void helixColour_actionPerformed(ActionEvent actionEvent)
949   {
950     helixColour.setSelected(true);
951     jmb.setJalviewColourScheme(new HelixColourScheme());
952   }
953
954   @Override
955   public void strandColour_actionPerformed(ActionEvent actionEvent)
956   {
957     strandColour.setSelected(true);
958     jmb.setJalviewColourScheme(new StrandColourScheme());
959   }
960
961   @Override
962   public void turnColour_actionPerformed(ActionEvent actionEvent)
963   {
964     turnColour.setSelected(true);
965     jmb.setJalviewColourScheme(new TurnColourScheme());
966   }
967
968   @Override
969   public void buriedColour_actionPerformed(ActionEvent actionEvent)
970   {
971     buriedColour.setSelected(true);
972     jmb.setJalviewColourScheme(new BuriedColourScheme());
973   }
974
975   @Override
976   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
977   {
978     setJalviewColourScheme(new PurinePyrimidineColourScheme());
979   }
980
981   @Override
982   public void userColour_actionPerformed(ActionEvent actionEvent)
983   {
984     userColour.setSelected(true);
985     new UserDefinedColours(this, null);
986   }
987
988   @Override
989   public void backGround_actionPerformed(ActionEvent actionEvent)
990   {
991     java.awt.Color col = JColorChooser.showDialog(this,
992             MessageManager.getString("label.select_backgroud_colour"), null);
993     if (col != null)
994     {
995       jmb.setBackgroundColour(col);
996     }
997   }
998
999   @Override
1000   public void showHelp_actionPerformed(ActionEvent actionEvent)
1001   {
1002     try
1003     {
1004       jalview.util.BrowserLauncher
1005               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1006     } catch (Exception ex)
1007     {
1008     }
1009   }
1010
1011   public void showConsole(boolean showConsole)
1012   {
1013
1014     if (showConsole)
1015     {
1016       if (splitPane == null)
1017       {
1018         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1019         splitPane.setTopComponent(renderPanel);
1020         splitPane.setBottomComponent(scriptWindow);
1021         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1022         splitPane.setDividerLocation(getHeight() - 200);
1023         scriptWindow.setVisible(true);
1024         scriptWindow.validate();
1025         splitPane.validate();
1026       }
1027
1028     }
1029     else
1030     {
1031       if (splitPane != null)
1032       {
1033         splitPane.setVisible(false);
1034       }
1035
1036       splitPane = null;
1037
1038       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1039     }
1040
1041     validate();
1042   }
1043
1044   class RenderPanel extends JPanel
1045   {
1046     final Dimension currentSize = new Dimension();
1047
1048     @Override
1049     public void paintComponent(Graphics g)
1050     {
1051       getSize(currentSize);
1052
1053       if (jmb != null && jmb.fileLoadingError != null)
1054       {
1055         g.setColor(Color.black);
1056         g.fillRect(0, 0, currentSize.width, currentSize.height);
1057         g.setColor(Color.white);
1058         g.setFont(new Font("Verdana", Font.BOLD, 14));
1059         g.drawString(MessageManager.getString("label.error_loading_file")
1060                 + "...", 20, currentSize.height / 2);
1061         StringBuffer sb = new StringBuffer();
1062         int lines = 0;
1063         for (int e = 0; e < jmb.getPdbCount(); e++)
1064         {
1065           sb.append(jmb.getPdbEntry(e).getId());
1066           if (e < jmb.getPdbCount() - 1)
1067           {
1068             sb.append(",");
1069           }
1070
1071           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1072           {
1073             lines++;
1074             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1075                     * g.getFontMetrics().getHeight());
1076           }
1077         }
1078       }
1079       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1080       {
1081         g.setColor(Color.black);
1082         g.fillRect(0, 0, currentSize.width, currentSize.height);
1083         g.setColor(Color.white);
1084         g.setFont(new Font("Verdana", Font.BOLD, 14));
1085         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1086                 20, currentSize.height / 2);
1087       }
1088       else
1089       {
1090         jmb.viewer.renderScreenImage(g, currentSize.width,
1091                 currentSize.height);
1092       }
1093     }
1094   }
1095
1096   public void updateTitleAndMenus()
1097   {
1098     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1099     {
1100       repaint();
1101       return;
1102     }
1103     setChainMenuItems(jmb.chainNames);
1104
1105     this.setTitle(jmb.getViewerTitle());
1106     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1107     {
1108       viewerActionMenu.setVisible(true);
1109     }
1110     if (!jmb.isLoadingFromArchive())
1111     {
1112       seqColour_actionPerformed(null);
1113     }
1114   }
1115
1116   /*
1117    * (non-Javadoc)
1118    * 
1119    * @see
1120    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1121    * .ActionEvent)
1122    */
1123   @Override
1124   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1125   {
1126     alignStructs_withAllAlignPanels();
1127   }
1128
1129   private void alignStructs_withAllAlignPanels()
1130   {
1131     if (getAlignmentPanel() == null)
1132     {
1133       return;
1134     }
1135     ;
1136     if (_alignwith.size() == 0)
1137     {
1138       _alignwith.add(getAlignmentPanel());
1139     }
1140     ;
1141     try
1142     {
1143       AlignmentI[] als = new Alignment[_alignwith.size()];
1144       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1145       int[] alm = new int[_alignwith.size()];
1146       int a = 0;
1147
1148       for (AlignmentPanel ap : _alignwith)
1149       {
1150         als[a] = ap.av.getAlignment();
1151         alm[a] = -1;
1152         alc[a++] = ap.av.getColumnSelection();
1153       }
1154       jmb.superposeStructures(als, alm, alc);
1155     } catch (Exception e)
1156     {
1157       StringBuffer sp = new StringBuffer();
1158       for (AlignmentPanel ap : _alignwith)
1159       {
1160         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1161       }
1162       Cache.log.info("Couldn't align structures with the " + sp.toString()
1163               + "associated alignment panels.", e);
1164
1165     }
1166
1167   }
1168
1169   public void setJalviewColourScheme(ColourSchemeI ucs)
1170   {
1171     jmb.setJalviewColourScheme(ucs);
1172
1173   }
1174
1175   /**
1176    * 
1177    * @param alignment
1178    * @return first alignment panel displaying given alignment, or the default
1179    *         alignment panel
1180    */
1181   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1182   {
1183     for (AlignmentPanel ap : getAllAlignmentPanels())
1184     {
1185       if (ap.av.getAlignment() == alignment)
1186       {
1187         return ap;
1188       }
1189     }
1190     return getAlignmentPanel();
1191   }
1192
1193   @Override
1194   public AAStructureBindingModel getBinding()
1195   {
1196     return this.jmb;
1197   }
1198
1199   @Override
1200   public String getStateInfo()
1201   {
1202     return jmb == null ? null : jmb.viewer.getStateInfo();
1203   }
1204
1205   @Override
1206   public ViewerType getViewerType()
1207   {
1208     return ViewerType.JMOL;
1209   }
1210
1211 }