JAL-3551 working proof of concept of Jalview driving PyMOL
[jalview.git] / src / jalview / gui / StructureViewerBase.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.api.AlignmentViewPanel;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.StructureViewer.ViewerType;
29 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
30 import jalview.io.DataSourceType;
31 import jalview.io.JalviewFileChooser;
32 import jalview.io.JalviewFileView;
33 import jalview.jbgui.GStructureViewer;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.schemes.ColourSchemes;
36 import jalview.structure.StructureMapping;
37 import jalview.structures.models.AAStructureBindingModel;
38 import jalview.util.MessageManager;
39 import jalview.ws.dbsources.Pdb;
40
41 import java.awt.Color;
42 import java.awt.Component;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.ItemEvent;
46 import java.awt.event.ItemListener;
47 import java.io.BufferedReader;
48 import java.io.File;
49 import java.io.FileOutputStream;
50 import java.io.FileReader;
51 import java.io.IOException;
52 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.List;
55 import java.util.Random;
56 import java.util.Vector;
57
58 import javax.swing.ButtonGroup;
59 import javax.swing.JCheckBoxMenuItem;
60 import javax.swing.JColorChooser;
61 import javax.swing.JMenu;
62 import javax.swing.JMenuItem;
63 import javax.swing.JRadioButtonMenuItem;
64 import javax.swing.event.MenuEvent;
65 import javax.swing.event.MenuListener;
66
67 /**
68  * Base class with common functionality for JMol, Chimera or other structure
69  * viewers.
70  * 
71  * @author gmcarstairs
72  *
73  */
74 public abstract class StructureViewerBase extends GStructureViewer
75         implements Runnable, ViewSetProvider
76 {
77   /*
78    * names for colour options (additional to Jalview colour schemes)
79    */
80   enum ViewerColour
81   {
82     BySequence, ByChain, ChargeCysteine, ByViewer
83   }
84
85   /**
86    * list of sequenceSet ids associated with the view
87    */
88   protected List<String> _aps = new ArrayList<>();
89
90   /**
91    * list of alignment panels to use for superposition
92    */
93   protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
94
95   /**
96    * list of alignment panels that are used for colouring structures by aligned
97    * sequences
98    */
99   protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
100
101   private String viewId = null;
102
103   private AlignmentPanel ap;
104
105   protected boolean alignAddedStructures = false;
106
107   protected volatile boolean _started = false;
108
109   protected volatile boolean addingStructures = false;
110
111   protected Thread worker = null;
112
113   protected boolean allChainsSelected = false;
114
115   protected JMenu viewSelectionMenu;
116
117   /**
118    * set after sequence colouring has been applied for this structure viewer.
119    * used to determine if the final sequence/structure mapping has been
120    * determined
121    */
122   protected volatile boolean seqColoursApplied = false;
123
124   private IProgressIndicator progressBar = null;
125
126   private Random random = new Random();
127
128   /**
129    * Default constructor
130    */
131   public StructureViewerBase()
132   {
133     super();
134   }
135
136   /**
137    * @return true if added structures should be aligned to existing one(s)
138    */
139   @Override
140   public boolean isAlignAddedStructures()
141   {
142     return alignAddedStructures;
143   }
144
145   /**
146    * 
147    * @param true
148    *          if added structures should be aligned to existing one(s)
149    */
150   @Override
151   public void setAlignAddedStructures(boolean alignAdded)
152   {
153     alignAddedStructures = alignAdded;
154   }
155
156   /**
157    * 
158    * @param ap2
159    * @return true if this Jmol instance is linked with the given alignPanel
160    */
161   public boolean isLinkedWith(AlignmentPanel ap2)
162   {
163     return _aps.contains(ap2.av.getSequenceSetId());
164   }
165
166   public boolean isUsedforaligment(AlignmentViewPanel ap2)
167   {
168
169     return (_alignwith != null) && _alignwith.contains(ap2);
170   }
171
172   @Override
173   public boolean isUsedForColourBy(AlignmentViewPanel ap2)
174   {
175     return (_colourwith != null) && _colourwith.contains(ap2);
176   }
177
178   /**
179    * 
180    * @return TRUE if the view is NOT being coloured by the alignment colours.
181    */
182   public boolean isColouredByViewer()
183   {
184     return !getBinding().isColourBySequence();
185   }
186
187   public String getViewId()
188   {
189     if (viewId == null)
190     {
191       viewId = System.currentTimeMillis() + "." + this.hashCode();
192     }
193     return viewId;
194   }
195
196   protected void setViewId(String viewId)
197   {
198     this.viewId = viewId;
199   }
200
201   public abstract String getStateInfo();
202
203   protected void buildActionMenu()
204   {
205     if (_alignwith == null)
206     {
207       _alignwith = new Vector<>();
208     }
209     if (_alignwith.size() == 0 && ap != null)
210     {
211       _alignwith.add(ap);
212     }
213     ;
214     for (Component c : viewerActionMenu.getMenuComponents())
215     {
216       if (c != alignStructs)
217       {
218         viewerActionMenu.remove((JMenuItem) c);
219       }
220     }
221   }
222
223   @Override
224   public AlignmentPanel getAlignmentPanel()
225   {
226     return ap;
227   }
228
229   protected void setAlignmentPanel(AlignmentPanel alp)
230   {
231     this.ap = alp;
232   }
233
234   @Override
235   public AlignmentPanel[] getAllAlignmentPanels()
236   {
237     AlignmentPanel[] t, list = new AlignmentPanel[0];
238     for (String setid : _aps)
239     {
240       AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
241       if (panels != null)
242       {
243         t = new AlignmentPanel[list.length + panels.length];
244         System.arraycopy(list, 0, t, 0, list.length);
245         System.arraycopy(panels, 0, t, list.length, panels.length);
246         list = t;
247       }
248     }
249
250     return list;
251   }
252
253   /**
254    * set the primary alignmentPanel reference and add another alignPanel to the
255    * list of ones to use for colouring and aligning
256    * 
257    * @param nap
258    */
259   public void addAlignmentPanel(AlignmentPanel nap)
260   {
261     if (getAlignmentPanel() == null)
262     {
263       setAlignmentPanel(nap);
264     }
265     if (!_aps.contains(nap.av.getSequenceSetId()))
266     {
267       _aps.add(nap.av.getSequenceSetId());
268     }
269   }
270
271   /**
272    * remove any references held to the given alignment panel
273    * 
274    * @param nap
275    */
276   @Override
277   public void removeAlignmentPanel(AlignmentViewPanel nap)
278   {
279     try
280     {
281       _alignwith.remove(nap);
282       _colourwith.remove(nap);
283       if (getAlignmentPanel() == nap)
284       {
285         setAlignmentPanel(null);
286         for (AlignmentPanel aps : getAllAlignmentPanels())
287         {
288           if (aps != nap)
289           {
290             setAlignmentPanel(aps);
291             break;
292           }
293         }
294       }
295     } catch (Exception ex)
296     {
297     }
298     if (getAlignmentPanel() != null)
299     {
300       buildActionMenu();
301     }
302   }
303
304   public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
305   {
306     addAlignmentPanel(nap);
307     if (!_alignwith.contains(nap))
308     {
309       _alignwith.add(nap);
310     }
311   }
312
313   public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
314   {
315     if (_alignwith.contains(nap))
316     {
317       _alignwith.remove(nap);
318     }
319   }
320
321   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
322           boolean enableColourBySeq)
323   {
324     useAlignmentPanelForColourbyseq(nap);
325     getBinding().setColourBySequence(enableColourBySeq);
326     seqColour.setSelected(enableColourBySeq);
327     viewerColour.setSelected(!enableColourBySeq);
328   }
329
330   public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
331   {
332     addAlignmentPanel(nap);
333     if (!_colourwith.contains(nap))
334     {
335       _colourwith.add(nap);
336     }
337   }
338
339   public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
340   {
341     if (_colourwith.contains(nap))
342     {
343       _colourwith.remove(nap);
344     }
345   }
346
347   public abstract ViewerType getViewerType();
348
349   /**
350    * add a new structure (with associated sequences and chains) to this viewer,
351    * retrieving it if necessary first.
352    * 
353    * @param pdbentry
354    * @param seqs
355    * @param chains
356    * @param align
357    *          if true, new structure(s) will be aligned using associated
358    *          alignment
359    * @param alignFrame
360    */
361   protected void addStructure(final PDBEntry pdbentry,
362           final SequenceI[] seqs, final String[] chains,
363           final IProgressIndicator alignFrame)
364   {
365     if (pdbentry.getFile() == null)
366     {
367       if (worker != null && worker.isAlive())
368       {
369         // a retrieval is in progress, wait around and add ourselves to the
370         // queue.
371         new Thread(new Runnable()
372         {
373           @Override
374           public void run()
375           {
376             while (worker != null && worker.isAlive() && _started)
377             {
378               try
379               {
380                 Thread.sleep(100 + ((int) Math.random() * 100));
381
382               } catch (Exception e)
383               {
384               }
385             }
386             // and call ourselves again.
387             addStructure(pdbentry, seqs, chains, alignFrame);
388           }
389         }).start();
390         return;
391       }
392     }
393     // otherwise, start adding the structure.
394     getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
395             new SequenceI[][]
396             { seqs }, new String[][] { chains });
397     addingStructures = true;
398     _started = false;
399     worker = new Thread(this);
400     worker.start();
401     return;
402   }
403
404   protected boolean hasPdbId(String pdbId)
405   {
406     return getBinding().hasPdbId(pdbId);
407   }
408
409   /**
410    * Returns a list of any viewer of the instantiated type. The list is
411    * restricted to those linked to the given alignment panel if it is not null.
412    */
413   protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
414   {
415     return Desktop.instance.getStructureViewers(alp, this.getClass());
416   }
417
418   @Override
419   public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
420           String[] chains, final AlignmentViewPanel apanel, String pdbId)
421   {
422     /*
423      * JAL-1742 exclude view with this structure already mapped (don't offer
424      * to align chain B to chain A of the same structure); code may defend
425      * against this possibility before we reach here
426      */
427     if (hasPdbId(pdbId))
428     {
429       return;
430     }
431     AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
432                                                  // cast fails
433     useAlignmentPanelForSuperposition(alignPanel);
434     addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
435   }
436
437   /**
438    * Adds mappings for the given sequences to an already opened PDB structure,
439    * and updates any viewers that have the PDB file
440    * 
441    * @param seq
442    * @param chains
443    * @param apanel
444    * @param pdbFilename
445    */
446   public void addSequenceMappingsToStructure(SequenceI[] seq,
447           String[] chains, final AlignmentViewPanel alpanel,
448           String pdbFilename)
449   {
450     AlignmentPanel apanel = (AlignmentPanel) alpanel;
451
452     // TODO : Fix multiple seq to one chain issue here.
453     /*
454      * create the mappings
455      */
456     apanel.getStructureSelectionManager().setMapping(seq, chains,
457             pdbFilename, DataSourceType.FILE, getProgressIndicator());
458
459     /*
460      * alert the FeatureRenderer to show new (PDB RESNUM) features
461      */
462     if (apanel.getSeqPanel().seqCanvas.fr != null)
463     {
464       apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
465       // note - we don't do a refresh for structure here because we do it
466       // explicitly for all panels later on
467       apanel.paintAlignment(true, false);
468     }
469
470     /*
471      * add the sequences to any other viewers (of the same type) for this pdb
472      * file
473      */
474     // JBPNOTE: this looks like a binding routine, rather than a gui routine
475     for (StructureViewerBase viewer : getViewersFor(null))
476     {
477       AAStructureBindingModel bindingModel = viewer.getBinding();
478       for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
479       {
480         if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
481         {
482           bindingModel.addSequence(pe, seq);
483           viewer.addAlignmentPanel(apanel);
484           /*
485            * add it to the set of alignments used for colouring structure by
486            * sequence
487            */
488           viewer.useAlignmentPanelForColourbyseq(apanel);
489           viewer.buildActionMenu();
490           apanel.getStructureSelectionManager()
491                   .sequenceColoursChanged(apanel);
492           break;
493         }
494       }
495     }
496   }
497
498   @Override
499   public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
500           final AlignmentViewPanel apanel, String pdbId)
501   {
502     String alreadyMapped = apanel.getStructureSelectionManager()
503             .alreadyMappedToFile(pdbId);
504
505     if (alreadyMapped == null)
506     {
507       return false;
508     }
509
510     addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
511     return true;
512   }
513
514   void setChainMenuItems(List<String> chainNames)
515   {
516     chainMenu.removeAll();
517     if (chainNames == null || chainNames.isEmpty())
518     {
519       return;
520     }
521     JMenuItem menuItem = new JMenuItem(
522             MessageManager.getString("label.all"));
523     menuItem.addActionListener(new ActionListener()
524     {
525       @Override
526       public void actionPerformed(ActionEvent evt)
527       {
528         allChainsSelected = true;
529         for (int i = 0; i < chainMenu.getItemCount(); i++)
530         {
531           if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
532           {
533             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
534           }
535         }
536         showSelectedChains();
537         allChainsSelected = false;
538       }
539     });
540
541     chainMenu.add(menuItem);
542
543     for (String chain : chainNames)
544     {
545       menuItem = new JCheckBoxMenuItem(chain, true);
546       menuItem.addItemListener(new ItemListener()
547       {
548         @Override
549         public void itemStateChanged(ItemEvent evt)
550         {
551           if (!allChainsSelected)
552           {
553             showSelectedChains();
554           }
555         }
556       });
557
558       chainMenu.add(menuItem);
559     }
560   }
561
562   /**
563    * Action on selecting one of Jalview's registered colour schemes
564    */
565   @Override
566   public void changeColour_actionPerformed(String colourSchemeName)
567   {
568     AlignmentI al = getAlignmentPanel().av.getAlignment();
569     ColourSchemeI cs = ColourSchemes.getInstance()
570             .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
571                     null);
572     getBinding().colourByJalviewColourScheme(cs);
573   }
574
575   /**
576    * Builds the colour menu
577    */
578   protected void buildColourMenu()
579   {
580     colourMenu.removeAll();
581     AlignmentI al = getAlignmentPanel().av.getAlignment();
582
583     /*
584      * add colour by sequence, by chain, by charge and cysteine
585      */
586     colourMenu.add(seqColour);
587     colourMenu.add(chainColour);
588     colourMenu.add(chargeColour);
589     chargeColour.setEnabled(!al.isNucleotide());
590
591     /*
592      * add all 'simple' (per-residue) colour schemes registered to Jalview
593      */
594     ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
595             al, true);
596
597     /*
598      * add 'colour by viewer' (menu item text is set in subclasses)
599      */
600     viewerColour.setSelected(false);
601     viewerColour.addActionListener(new ActionListener()
602     {
603       @Override
604       public void actionPerformed(ActionEvent actionEvent)
605       {
606         viewerColour_actionPerformed();
607       }
608     });
609     colourMenu.add(viewerColour);
610
611     /*
612      * add 'set background colour'
613      */
614     JMenuItem backGround = new JMenuItem();
615     backGround
616             .setText(MessageManager.getString("action.background_colour"));
617     backGround.addActionListener(new ActionListener()
618     {
619       @Override
620       public void actionPerformed(ActionEvent actionEvent)
621       {
622         background_actionPerformed();
623       }
624     });
625     colourMenu.add(backGround);
626
627     /*
628      * add colour buttons to a group so their selection is
629      * mutually exclusive (background colour is a separate option)
630      */
631     itemGroup.add(seqColour);
632     itemGroup.add(chainColour);
633     itemGroup.add(chargeColour);
634     itemGroup.add(viewerColour);
635   }
636
637   /**
638    * Construct menu items
639    */
640   protected void initMenus()
641   {
642     AAStructureBindingModel binding = getBinding();
643
644     seqColour = new JRadioButtonMenuItem();
645     seqColour.setText(MessageManager.getString("action.by_sequence"));
646     seqColour.setName(ViewerColour.BySequence.name());
647     seqColour.setSelected(binding.isColourBySequence());
648     seqColour.addActionListener(new ActionListener()
649     {
650       @Override
651       public void actionPerformed(ActionEvent actionEvent)
652       {
653         seqColour_actionPerformed();
654       }
655     });
656
657     chainColour = new JRadioButtonMenuItem();
658     chainColour.setText(MessageManager.getString("action.by_chain"));
659     chainColour.setName(ViewerColour.ByChain.name());
660     chainColour.addActionListener(new ActionListener()
661     {
662       @Override
663       public void actionPerformed(ActionEvent actionEvent)
664       {
665         chainColour_actionPerformed();
666       }
667     });
668
669     chargeColour = new JRadioButtonMenuItem();
670     chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
671     chargeColour.setName(ViewerColour.ChargeCysteine.name());
672     chargeColour.addActionListener(new ActionListener()
673     {
674       @Override
675       public void actionPerformed(ActionEvent actionEvent)
676       {
677         chargeColour_actionPerformed();
678       }
679     });
680
681     viewerColour = new JRadioButtonMenuItem();
682     // text is set in overrides of this method
683     viewerColour.setName(ViewerColour.ByViewer.name());
684     viewerColour.setSelected(!binding.isColourBySequence());
685
686     if (_colourwith == null)
687     {
688       _colourwith = new Vector<>();
689     }
690     if (_alignwith == null)
691     {
692       _alignwith = new Vector<>();
693     }
694
695     ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
696             MessageManager.getString("label.colour_by"), this, _colourwith,
697             new ItemListener()
698             {
699               @Override
700               public void itemStateChanged(ItemEvent e)
701               {
702                 if (!seqColour.isSelected())
703                 {
704                   seqColour.doClick();
705                 }
706                 else
707                 {
708                   // update the Chimera display now.
709                   seqColour_actionPerformed();
710                 }
711               }
712             });
713     viewMenu.add(seqColourBy);
714
715     final ItemListener handler = new ItemListener()
716     {
717       @Override
718       public void itemStateChanged(ItemEvent e)
719       {
720         alignStructs.setEnabled(!_alignwith.isEmpty());
721         alignStructs.setToolTipText(MessageManager.formatMessage(
722                 "label.align_structures_using_linked_alignment_views",
723                 _alignwith.size()));
724       }
725     };
726     viewSelectionMenu = new ViewSelectionMenu(
727             MessageManager.getString("label.superpose_with"), this,
728             _alignwith, handler);
729     handler.itemStateChanged(null);
730     viewerActionMenu.add(viewSelectionMenu, 0);
731     viewerActionMenu.addMenuListener(new MenuListener()
732     {
733       @Override
734       public void menuSelected(MenuEvent e)
735       {
736         handler.itemStateChanged(null);
737       }
738
739       @Override
740       public void menuDeselected(MenuEvent e)
741       {
742       }
743
744       @Override
745       public void menuCanceled(MenuEvent e)
746       {
747       }
748     });
749
750     buildColourMenu();
751   }
752
753   /**
754    * Sends commands to the structure viewer to superimpose structures based on
755    * currently associated alignments. May optionally return an error message for
756    * the operation.
757    */
758   @Override
759   protected String alignStructsWithAllAlignPanels()
760   {
761     if (getAlignmentPanel() == null)
762     {
763       return null;
764     }
765
766     if (_alignwith.size() == 0)
767     {
768       _alignwith.add(getAlignmentPanel());
769     }
770
771     String reply = null;
772     try
773     {
774       reply = getBinding().superposeStructures(_alignwith);
775       if (reply != null && !reply.isEmpty())
776       {
777         String text = MessageManager
778                 .formatMessage("error.superposition_failed", reply);
779         statusBar.setText(text);
780       }
781     } catch (Exception e)
782     {
783       StringBuffer sp = new StringBuffer();
784       for (AlignmentViewPanel alignPanel : _alignwith)
785       {
786         sp.append("'" + alignPanel.getViewName() + "' ");
787       }
788       Cache.log.info("Couldn't align structures with the " + sp.toString()
789               + "associated alignment panels.", e);
790     }
791     return reply;
792   }
793
794   @Override
795   public void background_actionPerformed()
796   {
797     Color col = JColorChooser.showDialog(this,
798             MessageManager.getString("label.select_background_colour"),
799             null);
800     if (col != null)
801     {
802       getBinding().setBackgroundColour(col);
803     }
804   }
805
806   @Override
807   public void viewerColour_actionPerformed()
808   {
809     if (viewerColour.isSelected())
810     {
811       // disable automatic sequence colouring.
812       getBinding().setColourBySequence(false);
813     }
814   }
815
816   @Override
817   public void chainColour_actionPerformed()
818   {
819     chainColour.setSelected(true);
820     getBinding().colourByChain();
821   }
822
823   @Override
824   public void chargeColour_actionPerformed()
825   {
826     chargeColour.setSelected(true);
827     getBinding().colourByCharge();
828   }
829
830   @Override
831   public void seqColour_actionPerformed()
832   {
833     AAStructureBindingModel binding = getBinding();
834     binding.setColourBySequence(seqColour.isSelected());
835     if (_colourwith == null)
836     {
837       _colourwith = new Vector<>();
838     }
839     if (binding.isColourBySequence())
840     {
841       if (!binding.isLoadingFromArchive())
842       {
843         if (_colourwith.size() == 0 && getAlignmentPanel() != null)
844         {
845           // Make the currently displayed alignment panel the associated view
846           _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
847         }
848       }
849       // Set the colour using the current view for the associated alignframe
850       for (AlignmentViewPanel alignPanel : _colourwith)
851       {
852         binding.colourBySequence(alignPanel);
853       }
854       seqColoursApplied = true;
855     }
856   }
857
858   @Override
859   public void pdbFile_actionPerformed()
860   {
861     JalviewFileChooser chooser = new JalviewFileChooser(
862             Cache.getProperty("LAST_DIRECTORY"));
863
864     chooser.setFileView(new JalviewFileView());
865     chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
866     chooser.setToolTipText(MessageManager.getString("action.save"));
867
868     int value = chooser.showSaveDialog(this);
869
870     if (value == JalviewFileChooser.APPROVE_OPTION)
871     {
872       BufferedReader in = null;
873       try
874       {
875         // TODO: cope with multiple PDB files in view
876         in = new BufferedReader(
877                 new FileReader(getBinding().getStructureFiles()[0]));
878         File outFile = chooser.getSelectedFile();
879
880         PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
881         String data;
882         while ((data = in.readLine()) != null)
883         {
884           if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
885           {
886             out.println(data);
887           }
888         }
889         out.close();
890       } catch (Exception ex)
891       {
892         ex.printStackTrace();
893       } finally
894       {
895         if (in != null)
896         {
897           try
898           {
899             in.close();
900           } catch (IOException e)
901           {
902             // ignore
903           }
904         }
905       }
906     }
907   }
908
909   @Override
910   public void viewMapping_actionPerformed()
911   {
912     CutAndPasteTransfer cap = new CutAndPasteTransfer();
913     try
914     {
915       cap.appendText(getBinding().printMappings());
916     } catch (OutOfMemoryError e)
917     {
918       new OOMWarning(
919               "composing sequence-structure alignments for display in text box.",
920               e);
921       cap.dispose();
922       return;
923     }
924     Desktop.addInternalFrame(cap,
925             MessageManager.getString("label.pdb_sequence_mapping"), 550,
926             600);
927   }
928
929   protected abstract String getViewerName();
930
931   /**
932    * Configures the title and menu items of the viewer panel.
933    */
934   @Override
935   public void updateTitleAndMenus()
936   {
937     AAStructureBindingModel binding = getBinding();
938     if (binding.hasFileLoadingError())
939     {
940       repaint();
941       return;
942     }
943     setChainMenuItems(binding.getChainNames());
944
945     this.setTitle(binding.getViewerTitle(getViewerName(), true));
946
947     /*
948      * enable 'Superpose with' if more than one mapped structure
949      */
950     viewSelectionMenu.setEnabled(false);
951     if (getBinding().getStructureFiles().length > 1
952             && getBinding().getSequence().length > 1)
953     {
954       viewSelectionMenu.setEnabled(true);
955     }
956
957     /*
958      * Show action menu if it has any enabled items
959      */
960     viewerActionMenu.setVisible(false);
961     for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
962     {
963       if (viewerActionMenu.getItem(i).isEnabled())
964       {
965         viewerActionMenu.setVisible(true);
966         break;
967       }
968     }
969
970     if (!binding.isLoadingFromArchive())
971     {
972       seqColour_actionPerformed();
973     }
974   }
975
976   @Override
977   public String toString()
978   {
979     return getTitle();
980   }
981
982   @Override
983   public boolean hasMapping()
984   {
985     if (worker != null && (addingStructures || _started))
986     {
987       return false;
988     }
989     if (getBinding() == null)
990     {
991       if (_aps == null || _aps.size() == 0)
992       {
993         // viewer has been closed, but we did at some point run.
994         return true;
995       }
996       return false;
997     }
998     String[] pdbids = getBinding().getStructureFiles();
999     if (pdbids == null)
1000     {
1001       return false;
1002     }
1003     int p=0;
1004     for (String pdbid:pdbids) {
1005       StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1006       if (sm!=null && sm.length>0 && sm[0]!=null) {
1007         p++;
1008       }
1009     }
1010     // only return true if there is a mapping for every structure file we have loaded
1011     if (p == 0 || p != pdbids.length)
1012     {
1013       return false;
1014     }
1015     // and that coloring has been applied
1016     return seqColoursApplied;
1017   }
1018
1019   @Override
1020   public void raiseViewer()
1021   {
1022     toFront();
1023   }
1024
1025   @Override
1026   public long startProgressBar(String msg)
1027   {
1028     // TODO would rather have startProgress/stopProgress as the
1029     // IProgressIndicator interface
1030     long tm = random.nextLong();
1031     if (progressBar != null)
1032     {
1033       progressBar.setProgressBar(msg, tm);
1034     }
1035     return tm;
1036   }
1037
1038   @Override
1039   public void stopProgressBar(String msg, long handle)
1040   {
1041     if (progressBar != null)
1042     {
1043       progressBar.setProgressBar(msg, handle);
1044     }
1045   }
1046
1047   protected IProgressIndicator getProgressIndicator()
1048   {
1049     return progressBar;
1050   }
1051
1052   protected void setProgressIndicator(IProgressIndicator pi)
1053   {
1054     progressBar = pi;
1055   }
1056
1057   protected void setProgressMessage(String message, long id)
1058   {
1059     if (progressBar != null)
1060     {
1061       progressBar.setProgressBar(message, id);
1062     }
1063   }
1064
1065   @Override
1066   public void showConsole(boolean show)
1067   {
1068     // default does nothing
1069   }
1070
1071   /**
1072    * Show only the selected chain(s) in the viewer
1073    */
1074   protected void showSelectedChains()
1075   {
1076     List<String> toshow = new ArrayList<>();
1077     for (int i = 0; i < chainMenu.getItemCount(); i++)
1078     {
1079       if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
1080       {
1081         JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
1082         if (item.isSelected())
1083         {
1084           toshow.add(item.getText());
1085         }
1086       }
1087     }
1088     getBinding().showChains(toshow);
1089   }
1090
1091   /**
1092    * Tries to fetch a PDB file and save to a temporary local file. Returns the
1093    * saved file path if successful, or null if not.
1094    * 
1095    * @param processingEntry
1096    * @return
1097    */
1098   protected String fetchPdbFile(PDBEntry processingEntry)
1099   {
1100     String filePath = null;
1101     Pdb pdbclient = new Pdb();
1102     AlignmentI pdbseq = null;
1103     String pdbid = processingEntry.getId();
1104     long handle = System.currentTimeMillis()
1105             + Thread.currentThread().hashCode();
1106   
1107     /*
1108      * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
1109      */
1110     String msg = MessageManager.formatMessage("status.fetching_pdb",
1111             new Object[]
1112             { pdbid });
1113     getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1114     // long hdl = startProgressBar(MessageManager.formatMessage(
1115     // "status.fetching_pdb", new Object[]
1116     // { pdbid }));
1117     try
1118     {
1119       pdbseq = pdbclient.getSequenceRecords(pdbid);
1120     } catch (Exception e)
1121     {
1122       System.err.println(
1123               "Error retrieving PDB id " + pdbid + ": " + e.getMessage());
1124     } finally
1125     {
1126       msg = pdbid + " " + MessageManager.getString("label.state_completed");
1127       getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1128       // stopProgressBar(msg, hdl);
1129     }
1130     /*
1131      * If PDB data were saved and are not invalid (empty alignment), return the
1132      * file path.
1133      */
1134     if (pdbseq != null && pdbseq.getHeight() > 0)
1135     {
1136       // just use the file name from the first sequence's first PDBEntry
1137       filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
1138               .elementAt(0).getFile()).getAbsolutePath();
1139       processingEntry.setFile(filePath);
1140     }
1141     return filePath;
1142   }
1143
1144 }