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.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.HiddenColumns;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.StructureViewer.ViewerType;
31 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
32 import jalview.io.DataSourceType;
33 import jalview.io.JalviewFileChooser;
34 import jalview.io.JalviewFileView;
35 import jalview.jbgui.GStructureViewer;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ColourSchemes;
38 import jalview.structure.StructureMapping;
39 import jalview.structures.models.AAStructureBindingModel;
40 import jalview.util.MessageManager;
42 import java.awt.Color;
43 import java.awt.Component;
44 import java.awt.event.ActionEvent;
45 import java.awt.event.ActionListener;
46 import java.awt.event.ItemEvent;
47 import java.awt.event.ItemListener;
48 import java.io.BufferedReader;
50 import java.io.FileOutputStream;
51 import java.io.FileReader;
52 import java.io.IOException;
53 import java.io.PrintWriter;
54 import java.util.ArrayList;
55 import java.util.List;
56 import java.util.Vector;
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;
68 * Base class with common functionality for JMol, Chimera or other structure
74 public abstract class StructureViewerBase extends GStructureViewer
75 implements Runnable, ViewSetProvider
78 * names for colour options (additional to Jalview colour schemes)
82 BySequence, ByChain, ChargeCysteine, ByViewer
86 * list of sequenceSet ids associated with the view
88 protected List<String> _aps = new ArrayList<>();
91 * list of alignment panels to use for superposition
93 protected Vector<AlignmentPanel> _alignwith = new Vector<>();
96 * list of alignment panels that are used for colouring structures by aligned
99 protected Vector<AlignmentPanel> _colourwith = new Vector<>();
101 private String viewId = null;
103 private AlignmentPanel ap;
105 protected boolean alignAddedStructures = false;
107 protected volatile boolean _started = false;
109 protected volatile boolean addingStructures = false;
111 protected Thread worker = null;
113 protected boolean allChainsSelected = false;
115 protected JMenu viewSelectionMenu;
118 * set after sequence colouring has been applied for this structure viewer.
119 * used to determine if the final sequence/structure mapping has been
122 protected volatile boolean seqColoursApplied = false;
125 * Default constructor
127 public StructureViewerBase()
135 * @return true if this Jmol instance is linked with the given alignPanel
137 public boolean isLinkedWith(AlignmentPanel ap2)
139 return _aps.contains(ap2.av.getSequenceSetId());
142 public boolean isUsedforaligment(AlignmentPanel ap2)
145 return (_alignwith != null) && _alignwith.contains(ap2);
148 public boolean isUsedforcolourby(AlignmentPanel ap2)
150 return (_colourwith != null) && _colourwith.contains(ap2);
155 * @return TRUE if the view is NOT being coloured by the alignment colours.
157 public boolean isColouredByViewer()
159 return !getBinding().isColourBySequence();
162 public String getViewId()
166 viewId = System.currentTimeMillis() + "." + this.hashCode();
171 protected void setViewId(String viewId)
173 this.viewId = viewId;
176 public abstract String getStateInfo();
178 protected void buildActionMenu()
180 if (_alignwith == null)
182 _alignwith = new Vector<>();
184 if (_alignwith.size() == 0 && ap != null)
189 for (Component c : viewerActionMenu.getMenuComponents())
191 if (c != alignStructs)
193 viewerActionMenu.remove((JMenuItem) c);
198 public AlignmentPanel getAlignmentPanel()
203 protected void setAlignmentPanel(AlignmentPanel alp)
209 public AlignmentPanel[] getAllAlignmentPanels()
211 AlignmentPanel[] t, list = new AlignmentPanel[0];
212 for (String setid : _aps)
214 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
217 t = new AlignmentPanel[list.length + panels.length];
218 System.arraycopy(list, 0, t, 0, list.length);
219 System.arraycopy(panels, 0, t, list.length, panels.length);
228 * set the primary alignmentPanel reference and add another alignPanel to the
229 * list of ones to use for colouring and aligning
233 public void addAlignmentPanel(AlignmentPanel nap)
235 if (getAlignmentPanel() == null)
237 setAlignmentPanel(nap);
239 if (!_aps.contains(nap.av.getSequenceSetId()))
241 _aps.add(nap.av.getSequenceSetId());
246 * remove any references held to the given alignment panel
250 public void removeAlignmentPanel(AlignmentPanel nap)
254 _alignwith.remove(nap);
255 _colourwith.remove(nap);
256 if (getAlignmentPanel() == nap)
258 setAlignmentPanel(null);
259 for (AlignmentPanel aps : getAllAlignmentPanels())
263 setAlignmentPanel(aps);
268 } catch (Exception ex)
271 if (getAlignmentPanel() != null)
277 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
279 addAlignmentPanel(nap);
280 if (!_alignwith.contains(nap))
286 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
288 if (_alignwith.contains(nap))
290 _alignwith.remove(nap);
294 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
295 boolean enableColourBySeq)
297 useAlignmentPanelForColourbyseq(nap);
298 getBinding().setColourBySequence(enableColourBySeq);
299 seqColour.setSelected(enableColourBySeq);
300 viewerColour.setSelected(!enableColourBySeq);
303 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
305 addAlignmentPanel(nap);
306 if (!_colourwith.contains(nap))
308 _colourwith.add(nap);
312 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
314 if (_colourwith.contains(nap))
316 _colourwith.remove(nap);
320 public abstract ViewerType getViewerType();
322 protected abstract IProgressIndicator getIProgressIndicator();
325 * add a new structure (with associated sequences and chains) to this viewer,
326 * retrieving it if necessary first.
332 * if true, new structure(s) will be aligned using associated
336 protected void addStructure(final PDBEntry pdbentry,
337 final SequenceI[] seqs, final String[] chains,
338 final boolean align, final IProgressIndicator alignFrame)
340 if (pdbentry.getFile() == null)
342 if (worker != null && worker.isAlive())
344 // a retrieval is in progress, wait around and add ourselves to the
346 new Thread(new Runnable()
351 while (worker != null && worker.isAlive() && _started)
355 Thread.sleep(100 + ((int) Math.random() * 100));
357 } catch (Exception e)
361 // and call ourselves again.
362 addStructure(pdbentry, seqs, chains, align, alignFrame);
368 // otherwise, start adding the structure.
369 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
371 { seqs }, new String[][] { chains });
372 addingStructures = true;
374 alignAddedStructures = align;
375 worker = new Thread(this);
381 * Presents a dialog with the option to add an align a structure to an
382 * existing structure view
386 * @return YES, NO or CANCEL JvOptionPane code
388 protected int chooseAlignStructureToViewer(String pdbId,
389 StructureViewerBase view)
391 int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
392 MessageManager.formatMessage("label.add_pdbentry_to_view",
394 { pdbId, view.getTitle() }),
396 .getString("label.align_to_existing_structure_view"),
397 JvOptionPane.YES_NO_CANCEL_OPTION);
401 protected boolean hasPdbId(String pdbId)
403 return getBinding().hasPdbId(pdbId);
407 * Returns a list of any viewer of the instantiated type. The list is
408 * restricted to those linked to the given alignment panel if it is not null.
410 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
412 return Desktop.instance.getStructureViewers(alp, this.getClass());
417 * Check for any existing views involving this alignment and give user the
418 * option to add and align this molecule to one of them
425 * @return true if user adds to a view, or cancels entirely, else false
428 public boolean addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
429 String[] chains, final AlignmentViewPanel apanel, String pdbId)
432 * JAL-1742 exclude view with this structure already mapped (don't offer
433 * to align chain B to chain A of the same structure)
439 AlignmentPanel ap = (AlignmentPanel) apanel; // Implementation error if this
441 useAlignmentPanelForSuperposition(ap);
442 addStructure(pdbentry, seq, chains, true, ap.alignFrame);
447 * Adds mappings for the given sequences to an already opened PDB structure,
448 * and updates any viewers that have the PDB file
455 public void addSequenceMappingsToStructure(SequenceI[] seq,
456 String[] chains, final AlignmentViewPanel alpanel,
459 AlignmentPanel apanel = (AlignmentPanel) alpanel;
461 // TODO : Fix multiple seq to one chain issue here.
463 * create the mappings
465 apanel.getStructureSelectionManager().setMapping(seq, chains,
466 pdbFilename, DataSourceType.FILE, getIProgressIndicator());
469 * alert the FeatureRenderer to show new (PDB RESNUM) features
471 if (apanel.getSeqPanel().seqCanvas.fr != null)
473 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
474 // note - we don't do a refresh for structure here because we do it
475 // explicitly for all panels later on
476 apanel.paintAlignment(true, false);
480 * add the sequences to any other viewers (of the same type) for this pdb
483 // JBPNOTE: this looks like a binding routine, rather than a gui routine
484 for (StructureViewerBase viewer : getViewersFor(null))
486 AAStructureBindingModel bindingModel = viewer.getBinding();
487 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
489 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
491 bindingModel.addSequence(pe, seq);
492 viewer.addAlignmentPanel(apanel);
494 * add it to the set of alignments used for colouring structure by
497 viewer.useAlignmentPanelForColourbyseq(apanel);
498 viewer.buildActionMenu();
499 apanel.getStructureSelectionManager()
500 .sequenceColoursChanged(apanel);
508 * Check if the PDB file is already loaded, if so offer to add it to the
515 * @return true if the user chooses to add to a viewer, or to cancel entirely
518 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
519 final AlignmentViewPanel apanel, String pdbId)
521 boolean finished = false;
522 String alreadyMapped = apanel.getStructureSelectionManager()
523 .alreadyMappedToFile(pdbId);
525 if (alreadyMapped != null)
528 * the PDB file is already loaded
530 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
536 void setChainMenuItems(List<String> chainNames)
538 chainMenu.removeAll();
539 if (chainNames == null || chainNames.isEmpty())
543 JMenuItem menuItem = new JMenuItem(
544 MessageManager.getString("label.all"));
545 menuItem.addActionListener(new ActionListener()
548 public void actionPerformed(ActionEvent evt)
550 allChainsSelected = true;
551 for (int i = 0; i < chainMenu.getItemCount(); i++)
553 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
555 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
558 showSelectedChains();
559 allChainsSelected = false;
563 chainMenu.add(menuItem);
565 for (String chain : chainNames)
567 menuItem = new JCheckBoxMenuItem(chain, true);
568 menuItem.addItemListener(new ItemListener()
571 public void itemStateChanged(ItemEvent evt)
573 if (!allChainsSelected)
575 showSelectedChains();
580 chainMenu.add(menuItem);
584 abstract void showSelectedChains();
587 * Action on selecting one of Jalview's registered colour schemes
590 public void changeColour_actionPerformed(String colourSchemeName)
592 AlignmentI al = getAlignmentPanel().av.getAlignment();
593 ColourSchemeI cs = ColourSchemes.getInstance()
594 .getColourScheme(colourSchemeName, al, null);
595 getBinding().setJalviewColourScheme(cs);
599 * Builds the colour menu
601 protected void buildColourMenu()
603 colourMenu.removeAll();
604 AlignmentI al = getAlignmentPanel().av.getAlignment();
607 * add colour by sequence, by chain, by charge and cysteine
609 colourMenu.add(seqColour);
610 colourMenu.add(chainColour);
611 colourMenu.add(chargeColour);
612 chargeColour.setEnabled(!al.isNucleotide());
615 * add all 'simple' (per-residue) colour schemes registered to Jalview
617 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
621 * add 'colour by viewer' (menu item text is set in subclasses)
623 viewerColour.setSelected(false);
624 viewerColour.addActionListener(new ActionListener()
627 public void actionPerformed(ActionEvent actionEvent)
629 viewerColour_actionPerformed(actionEvent);
632 colourMenu.add(viewerColour);
635 * add 'set background colour'
637 JMenuItem backGround = new JMenuItem();
639 .setText(MessageManager.getString("action.background_colour"));
640 backGround.addActionListener(new ActionListener()
643 public void actionPerformed(ActionEvent actionEvent)
645 background_actionPerformed(actionEvent);
648 colourMenu.add(backGround);
651 * add colour buttons to a group so their selection is
652 * mutually exclusive (background colour is a separate option)
654 itemGroup.add(seqColour);
655 itemGroup.add(chainColour);
656 itemGroup.add(chargeColour);
657 itemGroup.add(viewerColour);
661 * Construct menu items
663 protected void initMenus()
665 AAStructureBindingModel binding = getBinding();
667 seqColour = new JRadioButtonMenuItem();
668 seqColour.setText(MessageManager.getString("action.by_sequence"));
669 seqColour.setName(ViewerColour.BySequence.name());
670 seqColour.setSelected(binding.isColourBySequence());
671 seqColour.addActionListener(new ActionListener()
674 public void actionPerformed(ActionEvent actionEvent)
676 seqColour_actionPerformed(actionEvent);
680 chainColour = new JRadioButtonMenuItem();
681 chainColour.setText(MessageManager.getString("action.by_chain"));
682 chainColour.setName(ViewerColour.ByChain.name());
683 chainColour.addActionListener(new ActionListener()
686 public void actionPerformed(ActionEvent actionEvent)
688 chainColour_actionPerformed(actionEvent);
692 chargeColour = new JRadioButtonMenuItem();
693 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
694 chargeColour.setName(ViewerColour.ChargeCysteine.name());
695 chargeColour.addActionListener(new ActionListener()
698 public void actionPerformed(ActionEvent actionEvent)
700 chargeColour_actionPerformed(actionEvent);
704 viewerColour = new JRadioButtonMenuItem();
705 // text is set in overrides of this method
706 viewerColour.setName(ViewerColour.ByViewer.name());
707 viewerColour.setSelected(!binding.isColourBySequence());
709 if (_colourwith == null)
711 _colourwith = new Vector<>();
713 if (_alignwith == null)
715 _alignwith = new Vector<>();
718 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
719 MessageManager.getString("label.colour_by"), this, _colourwith,
723 public void itemStateChanged(ItemEvent e)
725 if (!seqColour.isSelected())
731 // update the Chimera display now.
732 seqColour_actionPerformed(null);
736 viewMenu.add(seqColourBy);
738 final ItemListener handler = new ItemListener()
741 public void itemStateChanged(ItemEvent e)
743 alignStructs.setEnabled(!_alignwith.isEmpty());
744 alignStructs.setToolTipText(MessageManager.formatMessage(
745 "label.align_structures_using_linked_alignment_views",
749 viewSelectionMenu = new ViewSelectionMenu(
750 MessageManager.getString("label.superpose_with"), this,
751 _alignwith, handler);
752 handler.itemStateChanged(null);
753 viewerActionMenu.add(viewSelectionMenu, 0);
754 viewerActionMenu.addMenuListener(new MenuListener()
757 public void menuSelected(MenuEvent e)
759 handler.itemStateChanged(null);
763 public void menuDeselected(MenuEvent e)
768 public void menuCanceled(MenuEvent e)
777 public void setJalviewColourScheme(ColourSchemeI cs)
779 getBinding().setJalviewColourScheme(cs);
783 * Sends commands to the structure viewer to superimpose structures based on
784 * currently associated alignments. May optionally return an error message for
788 protected String alignStructs_actionPerformed(ActionEvent actionEvent)
790 return alignStructs_withAllAlignPanels();
793 protected String alignStructs_withAllAlignPanels()
795 if (getAlignmentPanel() == null)
800 if (_alignwith.size() == 0)
802 _alignwith.add(getAlignmentPanel());
808 AlignmentI[] als = new Alignment[_alignwith.size()];
809 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
810 int[] alm = new int[_alignwith.size()];
813 for (AlignmentPanel ap : _alignwith)
815 als[a] = ap.av.getAlignment();
817 alc[a++] = ap.av.getAlignment().getHiddenColumns();
819 reply = getBinding().superposeStructures(als, alm, alc);
822 String text = MessageManager
823 .formatMessage("error.superposition_failed", reply);
824 statusBar.setText(text);
826 } catch (Exception e)
828 StringBuffer sp = new StringBuffer();
829 for (AlignmentPanel ap : _alignwith)
831 sp.append("'" + ap.alignFrame.getTitle() + "' ");
833 Cache.log.info("Couldn't align structures with the " + sp.toString()
834 + "associated alignment panels.", e);
840 public void background_actionPerformed(ActionEvent actionEvent)
842 Color col = JColorChooser.showDialog(this,
843 MessageManager.getString("label.select_background_colour"),
847 getBinding().setBackgroundColour(col);
852 public void viewerColour_actionPerformed(ActionEvent actionEvent)
854 if (viewerColour.isSelected())
856 // disable automatic sequence colouring.
857 getBinding().setColourBySequence(false);
862 public void chainColour_actionPerformed(ActionEvent actionEvent)
864 chainColour.setSelected(true);
865 getBinding().colourByChain();
869 public void chargeColour_actionPerformed(ActionEvent actionEvent)
871 chargeColour.setSelected(true);
872 getBinding().colourByCharge();
876 public void seqColour_actionPerformed(ActionEvent actionEvent)
878 AAStructureBindingModel binding = getBinding();
879 binding.setColourBySequence(seqColour.isSelected());
880 if (_colourwith == null)
882 _colourwith = new Vector<>();
884 if (binding.isColourBySequence())
886 if (!binding.isLoadingFromArchive())
888 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
890 // Make the currently displayed alignment panel the associated view
891 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
894 // Set the colour using the current view for the associated alignframe
895 for (AlignmentPanel ap : _colourwith)
897 binding.colourBySequence(ap);
899 seqColoursApplied = true;
904 public void pdbFile_actionPerformed(ActionEvent actionEvent)
906 JalviewFileChooser chooser = new JalviewFileChooser(
907 Cache.getProperty("LAST_DIRECTORY"));
909 chooser.setFileView(new JalviewFileView());
910 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
911 chooser.setToolTipText(MessageManager.getString("action.save"));
913 int value = chooser.showSaveDialog(this);
915 if (value == JalviewFileChooser.APPROVE_OPTION)
917 BufferedReader in = null;
920 // TODO: cope with multiple PDB files in view
921 in = new BufferedReader(
922 new FileReader(getBinding().getStructureFiles()[0]));
923 File outFile = chooser.getSelectedFile();
925 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
927 while ((data = in.readLine()) != null)
929 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
935 } catch (Exception ex)
937 ex.printStackTrace();
945 } catch (IOException e)
955 public void viewMapping_actionPerformed(ActionEvent actionEvent)
957 CutAndPasteTransfer cap = new CutAndPasteTransfer();
960 cap.appendText(getBinding().printMappings());
961 } catch (OutOfMemoryError e)
964 "composing sequence-structure alignments for display in text box.",
969 Desktop.addInternalFrame(cap,
970 MessageManager.getString("label.pdb_sequence_mapping"), 550,
974 protected abstract String getViewerName();
977 * Configures the title and menu items of the viewer panel.
980 public void updateTitleAndMenus()
982 AAStructureBindingModel binding = getBinding();
983 if (binding.hasFileLoadingError())
988 setChainMenuItems(binding.getChainNames());
990 this.setTitle(binding.getViewerTitle(getViewerName(), true));
993 * enable 'Superpose with' if more than one mapped structure
995 viewSelectionMenu.setEnabled(false);
996 if (getBinding().getStructureFiles().length > 1
997 && getBinding().getSequence().length > 1)
999 viewSelectionMenu.setEnabled(true);
1003 * Show action menu if it has any enabled items
1005 viewerActionMenu.setVisible(false);
1006 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
1008 if (viewerActionMenu.getItem(i).isEnabled())
1010 viewerActionMenu.setVisible(true);
1015 if (!binding.isLoadingFromArchive())
1017 seqColour_actionPerformed(null);
1022 public String toString()
1028 public boolean hasMapping()
1030 if (worker != null && (addingStructures || _started))
1034 if (getBinding() == null)
1036 if (_aps == null || _aps.size() == 0)
1038 // viewer has been closed, but we did at some point run.
1043 String[] pdbids = getBinding().getStructureFiles();
1049 for (String pdbid:pdbids) {
1050 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1051 if (sm!=null && sm.length>0 && sm[0]!=null) {
1055 // only return true if there is a mapping for every structure file we have loaded
1056 if (p == 0 || p != pdbids.length)
1060 // and that coloring has been applied
1061 return seqColoursApplied;