2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
40 import java.awt.Color;
41 import java.awt.Component;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.ItemEvent;
45 import java.awt.event.ItemListener;
46 import java.io.BufferedReader;
48 import java.io.FileOutputStream;
49 import java.io.FileReader;
50 import java.io.IOException;
51 import java.io.PrintWriter;
52 import java.util.ArrayList;
53 import java.util.List;
54 import java.util.Random;
55 import java.util.Vector;
57 import javax.swing.ButtonGroup;
58 import javax.swing.JCheckBoxMenuItem;
59 import javax.swing.JColorChooser;
60 import javax.swing.JMenu;
61 import javax.swing.JMenuItem;
62 import javax.swing.JRadioButtonMenuItem;
63 import javax.swing.event.MenuEvent;
64 import javax.swing.event.MenuListener;
67 * Base class with common functionality for JMol, Chimera or other structure
73 public abstract class StructureViewerBase extends GStructureViewer
74 implements Runnable, ViewSetProvider
77 * names for colour options (additional to Jalview colour schemes)
81 BySequence, ByChain, ChargeCysteine, ByViewer
85 * list of sequenceSet ids associated with the view
87 protected List<String> _aps = new ArrayList<>();
90 * list of alignment panels to use for superposition
92 protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
95 * list of alignment panels that are used for colouring structures by aligned
98 protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
100 private String viewId = null;
102 private AlignmentPanel ap;
104 protected boolean alignAddedStructures = false;
106 protected volatile boolean _started = false;
108 protected volatile boolean addingStructures = false;
110 protected Thread worker = null;
112 protected boolean allChainsSelected = false;
114 protected JMenu viewSelectionMenu;
117 * set after sequence colouring has been applied for this structure viewer.
118 * used to determine if the final sequence/structure mapping has been
121 protected volatile boolean seqColoursApplied = false;
123 private IProgressIndicator progressBar = null;
125 private Random random = new Random();
128 * Default constructor
130 public StructureViewerBase()
136 * @return true if added structures should be aligned to existing one(s)
139 public boolean isAlignAddedStructures()
141 return alignAddedStructures;
147 * if added structures should be aligned to existing one(s)
150 public void setAlignAddedStructures(boolean alignAdded)
152 alignAddedStructures = alignAdded;
158 * @return true if this Jmol instance is linked with the given alignPanel
160 public boolean isLinkedWith(AlignmentPanel ap2)
162 return _aps.contains(ap2.av.getSequenceSetId());
165 public boolean isUsedforaligment(AlignmentViewPanel ap2)
168 return (_alignwith != null) && _alignwith.contains(ap2);
172 public boolean isUsedForColourBy(AlignmentViewPanel ap2)
174 return (_colourwith != null) && _colourwith.contains(ap2);
179 * @return TRUE if the view is NOT being coloured by the alignment colours.
181 public boolean isColouredByViewer()
183 return !getBinding().isColourBySequence();
186 public String getViewId()
190 viewId = System.currentTimeMillis() + "." + this.hashCode();
195 protected void setViewId(String viewId)
197 this.viewId = viewId;
200 public abstract String getStateInfo();
202 protected void buildActionMenu()
204 if (_alignwith == null)
206 _alignwith = new Vector<>();
208 if (_alignwith.size() == 0 && ap != null)
213 for (Component c : viewerActionMenu.getMenuComponents())
215 if (c != alignStructs)
217 viewerActionMenu.remove((JMenuItem) c);
223 public AlignmentPanel getAlignmentPanel()
228 protected void setAlignmentPanel(AlignmentPanel alp)
234 public AlignmentPanel[] getAllAlignmentPanels()
236 AlignmentPanel[] t, list = new AlignmentPanel[0];
237 for (String setid : _aps)
239 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
242 t = new AlignmentPanel[list.length + panels.length];
243 System.arraycopy(list, 0, t, 0, list.length);
244 System.arraycopy(panels, 0, t, list.length, panels.length);
253 * set the primary alignmentPanel reference and add another alignPanel to the
254 * list of ones to use for colouring and aligning
258 public void addAlignmentPanel(AlignmentPanel nap)
260 if (getAlignmentPanel() == null)
262 setAlignmentPanel(nap);
264 if (!_aps.contains(nap.av.getSequenceSetId()))
266 _aps.add(nap.av.getSequenceSetId());
271 * remove any references held to the given alignment panel
276 public void removeAlignmentPanel(AlignmentViewPanel nap)
280 _alignwith.remove(nap);
281 _colourwith.remove(nap);
282 if (getAlignmentPanel() == nap)
284 setAlignmentPanel(null);
285 for (AlignmentPanel aps : getAllAlignmentPanels())
289 setAlignmentPanel(aps);
294 } catch (Exception ex)
297 if (getAlignmentPanel() != null)
303 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
305 addAlignmentPanel(nap);
306 if (!_alignwith.contains(nap))
312 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
314 if (_alignwith.contains(nap))
316 _alignwith.remove(nap);
320 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
321 boolean enableColourBySeq)
323 useAlignmentPanelForColourbyseq(nap);
324 getBinding().setColourBySequence(enableColourBySeq);
325 seqColour.setSelected(enableColourBySeq);
326 viewerColour.setSelected(!enableColourBySeq);
329 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
331 addAlignmentPanel(nap);
332 if (!_colourwith.contains(nap))
334 _colourwith.add(nap);
338 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
340 if (_colourwith.contains(nap))
342 _colourwith.remove(nap);
346 public abstract ViewerType getViewerType();
349 * add a new structure (with associated sequences and chains) to this viewer,
350 * retrieving it if necessary first.
356 * if true, new structure(s) will be aligned using associated
360 protected void addStructure(final PDBEntry pdbentry,
361 final SequenceI[] seqs, final String[] chains,
362 final IProgressIndicator alignFrame)
364 if (pdbentry.getFile() == null)
366 if (worker != null && worker.isAlive())
368 // a retrieval is in progress, wait around and add ourselves to the
370 new Thread(new Runnable()
375 while (worker != null && worker.isAlive() && _started)
379 Thread.sleep(100 + ((int) Math.random() * 100));
381 } catch (Exception e)
385 // and call ourselves again.
386 addStructure(pdbentry, seqs, chains, alignFrame);
392 // otherwise, start adding the structure.
393 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
395 { seqs }, new String[][] { chains });
396 addingStructures = true;
398 worker = new Thread(this);
403 protected boolean hasPdbId(String pdbId)
405 return getBinding().hasPdbId(pdbId);
409 * Returns a list of any viewer of the instantiated type. The list is
410 * restricted to those linked to the given alignment panel if it is not null.
412 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
414 return Desktop.instance.getStructureViewers(alp, this.getClass());
418 public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
419 String[] chains, final AlignmentViewPanel apanel, String pdbId)
422 * JAL-1742 exclude view with this structure already mapped (don't offer
423 * to align chain B to chain A of the same structure); code may defend
424 * against this possibility before we reach here
430 AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
432 useAlignmentPanelForSuperposition(alignPanel);
433 addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
437 * Adds mappings for the given sequences to an already opened PDB structure,
438 * and updates any viewers that have the PDB file
445 public void addSequenceMappingsToStructure(SequenceI[] seq,
446 String[] chains, final AlignmentViewPanel alpanel,
449 AlignmentPanel apanel = (AlignmentPanel) alpanel;
451 // TODO : Fix multiple seq to one chain issue here.
453 * create the mappings
455 apanel.getStructureSelectionManager().setMapping(seq, chains,
456 pdbFilename, DataSourceType.FILE, getProgressIndicator());
459 * alert the FeatureRenderer to show new (PDB RESNUM) features
461 if (apanel.getSeqPanel().seqCanvas.fr != null)
463 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
464 // note - we don't do a refresh for structure here because we do it
465 // explicitly for all panels later on
466 apanel.paintAlignment(true, false);
470 * add the sequences to any other viewers (of the same type) for this pdb
473 // JBPNOTE: this looks like a binding routine, rather than a gui routine
474 for (StructureViewerBase viewer : getViewersFor(null))
476 AAStructureBindingModel bindingModel = viewer.getBinding();
477 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
479 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
481 bindingModel.addSequence(pe, seq);
482 viewer.addAlignmentPanel(apanel);
484 * add it to the set of alignments used for colouring structure by
487 viewer.useAlignmentPanelForColourbyseq(apanel);
488 viewer.buildActionMenu();
489 apanel.getStructureSelectionManager()
490 .sequenceColoursChanged(apanel);
498 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
499 final AlignmentViewPanel apanel, String pdbId)
501 String alreadyMapped = apanel.getStructureSelectionManager()
502 .alreadyMappedToFile(pdbId);
504 if (alreadyMapped == null)
509 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
513 void setChainMenuItems(List<String> chainNames)
515 chainMenu.removeAll();
516 if (chainNames == null || chainNames.isEmpty())
520 JMenuItem menuItem = new JMenuItem(
521 MessageManager.getString("label.all"));
522 menuItem.addActionListener(new ActionListener()
525 public void actionPerformed(ActionEvent evt)
527 allChainsSelected = true;
528 for (int i = 0; i < chainMenu.getItemCount(); i++)
530 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
532 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
535 showSelectedChains();
536 allChainsSelected = false;
540 chainMenu.add(menuItem);
542 for (String chain : chainNames)
544 menuItem = new JCheckBoxMenuItem(chain, true);
545 menuItem.addItemListener(new ItemListener()
548 public void itemStateChanged(ItemEvent evt)
550 if (!allChainsSelected)
552 showSelectedChains();
557 chainMenu.add(menuItem);
562 * Action on selecting one of Jalview's registered colour schemes
565 public void changeColour_actionPerformed(String colourSchemeName)
567 AlignmentI al = getAlignmentPanel().av.getAlignment();
568 ColourSchemeI cs = ColourSchemes.getInstance()
569 .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
571 getBinding().colourByJalviewColourScheme(cs);
575 * Builds the colour menu
577 protected void buildColourMenu()
579 colourMenu.removeAll();
580 AlignmentI al = getAlignmentPanel().av.getAlignment();
583 * add colour by sequence, by chain, by charge and cysteine
585 colourMenu.add(seqColour);
586 colourMenu.add(chainColour);
587 colourMenu.add(chargeColour);
588 chargeColour.setEnabled(!al.isNucleotide());
591 * add all 'simple' (per-residue) colour schemes registered to Jalview
593 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
597 * add 'colour by viewer' (menu item text is set in subclasses)
599 viewerColour.setSelected(false);
600 viewerColour.addActionListener(new ActionListener()
603 public void actionPerformed(ActionEvent actionEvent)
605 viewerColour_actionPerformed();
608 colourMenu.add(viewerColour);
611 * add 'set background colour'
613 JMenuItem backGround = new JMenuItem();
615 .setText(MessageManager.getString("action.background_colour"));
616 backGround.addActionListener(new ActionListener()
619 public void actionPerformed(ActionEvent actionEvent)
621 background_actionPerformed();
624 colourMenu.add(backGround);
627 * add colour buttons to a group so their selection is
628 * mutually exclusive (background colour is a separate option)
630 itemGroup.add(seqColour);
631 itemGroup.add(chainColour);
632 itemGroup.add(chargeColour);
633 itemGroup.add(viewerColour);
637 * Construct menu items
639 protected void initMenus()
641 AAStructureBindingModel binding = getBinding();
643 seqColour = new JRadioButtonMenuItem();
644 seqColour.setText(MessageManager.getString("action.by_sequence"));
645 seqColour.setName(ViewerColour.BySequence.name());
646 seqColour.setSelected(binding.isColourBySequence());
647 seqColour.addActionListener(new ActionListener()
650 public void actionPerformed(ActionEvent actionEvent)
652 seqColour_actionPerformed();
656 chainColour = new JRadioButtonMenuItem();
657 chainColour.setText(MessageManager.getString("action.by_chain"));
658 chainColour.setName(ViewerColour.ByChain.name());
659 chainColour.addActionListener(new ActionListener()
662 public void actionPerformed(ActionEvent actionEvent)
664 chainColour_actionPerformed();
668 chargeColour = new JRadioButtonMenuItem();
669 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
670 chargeColour.setName(ViewerColour.ChargeCysteine.name());
671 chargeColour.addActionListener(new ActionListener()
674 public void actionPerformed(ActionEvent actionEvent)
676 chargeColour_actionPerformed();
680 viewerColour = new JRadioButtonMenuItem();
681 // text is set in overrides of this method
682 viewerColour.setName(ViewerColour.ByViewer.name());
683 viewerColour.setSelected(!binding.isColourBySequence());
685 if (_colourwith == null)
687 _colourwith = new Vector<>();
689 if (_alignwith == null)
691 _alignwith = new Vector<>();
694 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
695 MessageManager.getString("label.colour_by"), this, _colourwith,
699 public void itemStateChanged(ItemEvent e)
701 if (!seqColour.isSelected())
707 // update the Chimera display now.
708 seqColour_actionPerformed();
712 viewMenu.add(seqColourBy);
714 final ItemListener handler = new ItemListener()
717 public void itemStateChanged(ItemEvent e)
719 alignStructs.setEnabled(!_alignwith.isEmpty());
720 alignStructs.setToolTipText(MessageManager.formatMessage(
721 "label.align_structures_using_linked_alignment_views",
725 viewSelectionMenu = new ViewSelectionMenu(
726 MessageManager.getString("label.superpose_with"), this,
727 _alignwith, handler);
728 handler.itemStateChanged(null);
729 viewerActionMenu.add(viewSelectionMenu, 0);
730 viewerActionMenu.addMenuListener(new MenuListener()
733 public void menuSelected(MenuEvent e)
735 handler.itemStateChanged(null);
739 public void menuDeselected(MenuEvent e)
744 public void menuCanceled(MenuEvent e)
753 * Sends commands to the structure viewer to superimpose structures based on
754 * currently associated alignments. May optionally return an error message for
758 protected String alignStructsWithAllAlignPanels()
760 if (getAlignmentPanel() == null)
765 if (_alignwith.size() == 0)
767 _alignwith.add(getAlignmentPanel());
773 reply = getBinding().superposeStructures(_alignwith);
774 if (reply != null && !reply.isEmpty())
776 String text = MessageManager
777 .formatMessage("error.superposition_failed", reply);
778 statusBar.setText(text);
780 } catch (Exception e)
782 StringBuffer sp = new StringBuffer();
783 for (AlignmentViewPanel alignPanel : _alignwith)
785 sp.append("'" + alignPanel.getViewName() + "' ");
787 Cache.log.info("Couldn't align structures with the " + sp.toString()
788 + "associated alignment panels.", e);
794 public void background_actionPerformed()
796 Color col = JColorChooser.showDialog(this,
797 MessageManager.getString("label.select_background_colour"),
801 getBinding().setBackgroundColour(col);
806 public void viewerColour_actionPerformed()
808 if (viewerColour.isSelected())
810 // disable automatic sequence colouring.
811 getBinding().setColourBySequence(false);
816 public void chainColour_actionPerformed()
818 chainColour.setSelected(true);
819 getBinding().colourByChain();
823 public void chargeColour_actionPerformed()
825 chargeColour.setSelected(true);
826 getBinding().colourByCharge();
830 public void seqColour_actionPerformed()
832 AAStructureBindingModel binding = getBinding();
833 binding.setColourBySequence(seqColour.isSelected());
834 if (_colourwith == null)
836 _colourwith = new Vector<>();
838 if (binding.isColourBySequence())
840 if (!binding.isLoadingFromArchive())
842 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
844 // Make the currently displayed alignment panel the associated view
845 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
848 // Set the colour using the current view for the associated alignframe
849 for (AlignmentViewPanel alignPanel : _colourwith)
851 binding.colourBySequence(alignPanel);
853 seqColoursApplied = true;
858 public void pdbFile_actionPerformed()
860 JalviewFileChooser chooser = new JalviewFileChooser(
861 Cache.getProperty("LAST_DIRECTORY"));
863 chooser.setFileView(new JalviewFileView());
864 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
865 chooser.setToolTipText(MessageManager.getString("action.save"));
867 int value = chooser.showSaveDialog(this);
869 if (value == JalviewFileChooser.APPROVE_OPTION)
871 BufferedReader in = null;
874 // TODO: cope with multiple PDB files in view
875 in = new BufferedReader(
876 new FileReader(getBinding().getStructureFiles()[0]));
877 File outFile = chooser.getSelectedFile();
879 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
881 while ((data = in.readLine()) != null)
883 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
889 } catch (Exception ex)
891 ex.printStackTrace();
899 } catch (IOException e)
909 public void viewMapping_actionPerformed()
911 CutAndPasteTransfer cap = new CutAndPasteTransfer();
914 cap.appendText(getBinding().printMappings());
915 } catch (OutOfMemoryError e)
918 "composing sequence-structure alignments for display in text box.",
923 Desktop.addInternalFrame(cap,
924 MessageManager.getString("label.pdb_sequence_mapping"), 550,
928 protected abstract String getViewerName();
931 * Configures the title and menu items of the viewer panel.
934 public void updateTitleAndMenus()
936 AAStructureBindingModel binding = getBinding();
937 if (binding.hasFileLoadingError())
942 setChainMenuItems(binding.getChainNames());
944 this.setTitle(binding.getViewerTitle(getViewerName(), true));
947 * enable 'Superpose with' if more than one mapped structure
949 viewSelectionMenu.setEnabled(false);
950 if (getBinding().getStructureFiles().length > 1
951 && getBinding().getSequence().length > 1)
953 viewSelectionMenu.setEnabled(true);
957 * Show action menu if it has any enabled items
959 viewerActionMenu.setVisible(false);
960 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
962 if (viewerActionMenu.getItem(i).isEnabled())
964 viewerActionMenu.setVisible(true);
969 if (!binding.isLoadingFromArchive())
971 seqColour_actionPerformed();
976 public String toString()
982 public boolean hasMapping()
984 if (worker != null && (addingStructures || _started))
988 if (getBinding() == null)
990 if (_aps == null || _aps.size() == 0)
992 // viewer has been closed, but we did at some point run.
997 String[] pdbids = getBinding().getStructureFiles();
1003 for (String pdbid:pdbids) {
1004 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1005 if (sm!=null && sm.length>0 && sm[0]!=null) {
1009 // only return true if there is a mapping for every structure file we have loaded
1010 if (p == 0 || p != pdbids.length)
1014 // and that coloring has been applied
1015 return seqColoursApplied;
1019 public void raiseViewer()
1025 public long startProgressBar(String msg)
1027 // TODO would rather have startProgress/stopProgress as the
1028 // IProgressIndicator interface
1029 long tm = random.nextLong();
1030 if (progressBar != null)
1032 progressBar.setProgressBar(msg, tm);
1038 public void stopProgressBar(String msg, long handle)
1040 if (progressBar != null)
1042 progressBar.setProgressBar(msg, handle);
1046 protected IProgressIndicator getProgressIndicator()
1051 protected void setProgressIndicator(IProgressIndicator pi)
1056 protected void setProgressMessage(String message, long id)
1058 if (progressBar != null)
1060 progressBar.setProgressBar(message, id);
1065 public void showConsole(boolean show)
1067 // default does nothing
1071 * Show only the selected chain(s) in the viewer
1073 protected void showSelectedChains()
1075 List<String> toshow = new ArrayList<>();
1076 for (int i = 0; i < chainMenu.getItemCount(); i++)
1078 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
1080 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
1081 if (item.isSelected())
1083 toshow.add(item.getText());
1087 getBinding().showChains(toshow);