JAL-1807 merge from JAL-1759jmolUpdate
[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).getPDBId()
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             alignStructs_withAllAlignPanels();
752             // jmb.superposeStructures(ap.av.getAlignment(), -1, null);
753           }
754         });
755         alignAddedStructures = false;
756       }
757       addingStructures = false;
758
759     }
760     _started = false;
761     worker = null;
762   }
763
764   @Override
765   public void pdbFile_actionPerformed(ActionEvent actionEvent)
766   {
767     JalviewFileChooser chooser = new JalviewFileChooser(
768             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
769
770     chooser.setFileView(new JalviewFileView());
771     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
772     chooser.setToolTipText(MessageManager.getString("action.save"));
773
774     int value = chooser.showSaveDialog(this);
775
776     if (value == JalviewFileChooser.APPROVE_OPTION)
777     {
778       BufferedReader in = null;
779       try
780       {
781         // TODO: cope with multiple PDB files in view
782         in = new BufferedReader(new FileReader(
783                 jmb.getPdbFile()[0]));
784         File outFile = chooser.getSelectedFile();
785
786         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
787         String data;
788         while ((data = in.readLine()) != null)
789         {
790           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
791           {
792             out.println(data);
793           }
794         }
795         out.close();
796       } catch (Exception ex)
797       {
798         ex.printStackTrace();
799       } finally
800       {
801         if (in != null)
802         {
803           try
804           {
805             in.close();
806           } catch (IOException e)
807           {
808             // ignore
809           }
810         }
811       }
812     }
813   }
814
815   @Override
816   public void viewMapping_actionPerformed(ActionEvent actionEvent)
817   {
818     jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
819     try
820     {
821       cap.appendText(jmb.printMappings());
822     } catch (OutOfMemoryError e)
823     {
824       new OOMWarning(
825               "composing sequence-structure alignments for display in text box.",
826               e);
827       cap.dispose();
828       return;
829     }
830     jalview.gui.Desktop.addInternalFrame(cap,
831             MessageManager.getString("label.pdb_sequence_mapping"), 550,
832             600);
833   }
834
835   @Override
836   public void eps_actionPerformed(ActionEvent e)
837   {
838     makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
839   }
840
841   @Override
842   public void png_actionPerformed(ActionEvent e)
843   {
844     makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
845   }
846
847   void makePDBImage(jalview.util.ImageMaker.TYPE type)
848   {
849     int width = getWidth();
850     int height = getHeight();
851
852     jalview.util.ImageMaker im;
853
854     if (type == jalview.util.ImageMaker.TYPE.PNG)
855     {
856       im = new jalview.util.ImageMaker(this,
857               jalview.util.ImageMaker.TYPE.PNG,
858               "Make PNG image from view", width, height, null, null);
859     }
860     else if (type == jalview.util.ImageMaker.TYPE.EPS)
861     {
862       im = new jalview.util.ImageMaker(this,
863               jalview.util.ImageMaker.TYPE.EPS,
864               "Make EPS file from view", width, height, null,
865               this.getTitle());
866     }
867     else
868     {
869
870       im = new jalview.util.ImageMaker(this,
871               jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
872               width, height, null, this.getTitle());
873     }
874
875     if (im.getGraphics() != null)
876     {
877       jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
878       im.writeImage();
879     }
880   }
881
882   @Override
883   public void viewerColour_actionPerformed(ActionEvent actionEvent)
884   {
885     if (viewerColour.isSelected())
886     {
887       // disable automatic sequence colouring.
888       jmb.setColourBySequence(false);
889     }
890   }
891
892   @Override
893   public void seqColour_actionPerformed(ActionEvent actionEvent)
894   {
895     jmb.setColourBySequence(seqColour.isSelected());
896     if (_colourwith == null)
897     {
898       _colourwith = new Vector<AlignmentPanel>();
899     }
900     if (jmb.isColourBySequence())
901     {
902       if (!jmb.isLoadingFromArchive())
903       {
904         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
905         {
906           // Make the currently displayed alignment panel the associated view
907           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
908         }
909       }
910       // Set the colour using the current view for the associated alignframe
911       for (AlignmentPanel ap : _colourwith)
912       {
913         jmb.colourBySequence(ap);
914       }
915     }
916   }
917
918   @Override
919   public void chainColour_actionPerformed(ActionEvent actionEvent)
920   {
921     chainColour.setSelected(true);
922     jmb.colourByChain();
923   }
924
925   @Override
926   public void chargeColour_actionPerformed(ActionEvent actionEvent)
927   {
928     chargeColour.setSelected(true);
929     jmb.colourByCharge();
930   }
931
932   @Override
933   public void zappoColour_actionPerformed(ActionEvent actionEvent)
934   {
935     zappoColour.setSelected(true);
936     jmb.setJalviewColourScheme(new ZappoColourScheme());
937   }
938
939   @Override
940   public void taylorColour_actionPerformed(ActionEvent actionEvent)
941   {
942     taylorColour.setSelected(true);
943     jmb.setJalviewColourScheme(new TaylorColourScheme());
944   }
945
946   @Override
947   public void hydroColour_actionPerformed(ActionEvent actionEvent)
948   {
949     hydroColour.setSelected(true);
950     jmb.setJalviewColourScheme(new HydrophobicColourScheme());
951   }
952
953   @Override
954   public void helixColour_actionPerformed(ActionEvent actionEvent)
955   {
956     helixColour.setSelected(true);
957     jmb.setJalviewColourScheme(new HelixColourScheme());
958   }
959
960   @Override
961   public void strandColour_actionPerformed(ActionEvent actionEvent)
962   {
963     strandColour.setSelected(true);
964     jmb.setJalviewColourScheme(new StrandColourScheme());
965   }
966
967   @Override
968   public void turnColour_actionPerformed(ActionEvent actionEvent)
969   {
970     turnColour.setSelected(true);
971     jmb.setJalviewColourScheme(new TurnColourScheme());
972   }
973
974   @Override
975   public void buriedColour_actionPerformed(ActionEvent actionEvent)
976   {
977     buriedColour.setSelected(true);
978     jmb.setJalviewColourScheme(new BuriedColourScheme());
979   }
980
981   @Override
982   public void purinePyrimidineColour_actionPerformed(ActionEvent actionEvent)
983   {
984     setJalviewColourScheme(new PurinePyrimidineColourScheme());
985   }
986
987   @Override
988   public void userColour_actionPerformed(ActionEvent actionEvent)
989   {
990     userColour.setSelected(true);
991     new UserDefinedColours(this, null);
992   }
993
994   @Override
995   public void backGround_actionPerformed(ActionEvent actionEvent)
996   {
997     java.awt.Color col = JColorChooser.showDialog(this,
998             MessageManager.getString("label.select_backgroud_colour"), null);
999     if (col != null)
1000     {
1001       jmb.setBackgroundColour(col);
1002     }
1003   }
1004
1005   @Override
1006   public void showHelp_actionPerformed(ActionEvent actionEvent)
1007   {
1008     try
1009     {
1010       jalview.util.BrowserLauncher
1011               .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
1012     } catch (Exception ex)
1013     {
1014     }
1015   }
1016
1017   public void showConsole(boolean showConsole)
1018   {
1019
1020     if (showConsole)
1021     {
1022       if (splitPane == null)
1023       {
1024         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
1025         splitPane.setTopComponent(renderPanel);
1026         splitPane.setBottomComponent(scriptWindow);
1027         this.getContentPane().add(splitPane, BorderLayout.CENTER);
1028         splitPane.setDividerLocation(getHeight() - 200);
1029         scriptWindow.setVisible(true);
1030         scriptWindow.validate();
1031         splitPane.validate();
1032       }
1033
1034     }
1035     else
1036     {
1037       if (splitPane != null)
1038       {
1039         splitPane.setVisible(false);
1040       }
1041
1042       splitPane = null;
1043
1044       this.getContentPane().add(renderPanel, BorderLayout.CENTER);
1045     }
1046
1047     validate();
1048   }
1049
1050   class RenderPanel extends JPanel
1051   {
1052     final Dimension currentSize = new Dimension();
1053
1054     @Override
1055     public void paintComponent(Graphics g)
1056     {
1057       getSize(currentSize);
1058
1059       if (jmb != null && jmb.fileLoadingError != null)
1060       {
1061         g.setColor(Color.black);
1062         g.fillRect(0, 0, currentSize.width, currentSize.height);
1063         g.setColor(Color.white);
1064         g.setFont(new Font("Verdana", Font.BOLD, 14));
1065         g.drawString(MessageManager.getString("label.error_loading_file")
1066                 + "...", 20, currentSize.height / 2);
1067         StringBuffer sb = new StringBuffer();
1068         int lines = 0;
1069         for (int e = 0; e < jmb.getPdbCount(); e++)
1070         {
1071           sb.append(jmb.getPdbEntry(e).getId());
1072           if (e < jmb.getPdbCount() - 1)
1073           {
1074             sb.append(",");
1075           }
1076
1077           if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
1078           {
1079             lines++;
1080             g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
1081                     * g.getFontMetrics().getHeight());
1082           }
1083         }
1084       }
1085       else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
1086       {
1087         g.setColor(Color.black);
1088         g.fillRect(0, 0, currentSize.width, currentSize.height);
1089         g.setColor(Color.white);
1090         g.setFont(new Font("Verdana", Font.BOLD, 14));
1091         g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
1092                 20, currentSize.height / 2);
1093       }
1094       else
1095       {
1096         jmb.viewer.renderScreenImage(g, currentSize.width,
1097                 currentSize.height);
1098       }
1099     }
1100   }
1101
1102   public void updateTitleAndMenus()
1103   {
1104     if (jmb.fileLoadingError != null && jmb.fileLoadingError.length() > 0)
1105     {
1106       repaint();
1107       return;
1108     }
1109     setChainMenuItems(jmb.chainNames);
1110
1111     this.setTitle(jmb.getViewerTitle());
1112     if (jmb.getPdbFile().length > 1 && jmb.getSequence().length > 1)
1113     {
1114       viewerActionMenu.setVisible(true);
1115     }
1116     if (!jmb.isLoadingFromArchive())
1117     {
1118       seqColour_actionPerformed(null);
1119     }
1120   }
1121
1122   /*
1123    * (non-Javadoc)
1124    * 
1125    * @see
1126    * jalview.jbgui.GStructureViewer#alignStructs_actionPerformed(java.awt.event
1127    * .ActionEvent)
1128    */
1129   @Override
1130   protected void alignStructs_actionPerformed(ActionEvent actionEvent)
1131   {
1132     alignStructs_withAllAlignPanels();
1133   }
1134
1135   private void alignStructs_withAllAlignPanels()
1136   {
1137     if (getAlignmentPanel() == null)
1138     {
1139       return;
1140     }
1141     ;
1142     if (_alignwith.size() == 0)
1143     {
1144       _alignwith.add(getAlignmentPanel());
1145     }
1146     ;
1147     try
1148     {
1149       AlignmentI[] als = new Alignment[_alignwith.size()];
1150       ColumnSelection[] alc = new ColumnSelection[_alignwith.size()];
1151       int[] alm = new int[_alignwith.size()];
1152       int a = 0;
1153
1154       for (AlignmentPanel ap : _alignwith)
1155       {
1156         als[a] = ap.av.getAlignment();
1157         alm[a] = -1;
1158         alc[a++] = ap.av.getColumnSelection();
1159       }
1160       jmb.superposeStructures(als, alm, alc);
1161     } catch (Exception e)
1162     {
1163       StringBuffer sp = new StringBuffer();
1164       for (AlignmentPanel ap : _alignwith)
1165       {
1166         sp.append("'" + ap.alignFrame.getTitle() + "' ");
1167       }
1168       Cache.log.info("Couldn't align structures with the " + sp.toString()
1169               + "associated alignment panels.", e);
1170
1171     }
1172
1173   }
1174
1175   public void setJalviewColourScheme(ColourSchemeI ucs)
1176   {
1177     jmb.setJalviewColourScheme(ucs);
1178
1179   }
1180
1181   /**
1182    * 
1183    * @param alignment
1184    * @return first alignment panel displaying given alignment, or the default
1185    *         alignment panel
1186    */
1187   public AlignmentPanel getAlignmentPanelFor(AlignmentI alignment)
1188   {
1189     for (AlignmentPanel ap : getAllAlignmentPanels())
1190     {
1191       if (ap.av.getAlignment() == alignment)
1192       {
1193         return ap;
1194       }
1195     }
1196     return getAlignmentPanel();
1197   }
1198
1199   @Override
1200   public AAStructureBindingModel getBinding()
1201   {
1202     return this.jmb;
1203   }
1204
1205   @Override
1206   public String getStateInfo()
1207   {
1208     return jmb == null ? null : jmb.viewer.getStateInfo();
1209   }
1210
1211   @Override
1212   public ViewerType getViewerType()
1213   {
1214     return ViewerType.JMOL;
1215   }
1216
1217 }