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.structures.models.AAStructureBindingModel.ColourBy;
41 import jalview.util.MessageManager;
43 import java.awt.Color;
44 import java.awt.Component;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.ItemEvent;
48 import java.awt.event.ItemListener;
49 import java.io.BufferedReader;
51 import java.io.FileOutputStream;
52 import java.io.FileReader;
53 import java.io.IOException;
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.Enumeration;
57 import java.util.List;
58 import java.util.Vector;
60 import javax.swing.AbstractButton;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JCheckBoxMenuItem;
63 import javax.swing.JColorChooser;
64 import javax.swing.JMenu;
65 import javax.swing.JMenuItem;
66 import javax.swing.JRadioButtonMenuItem;
67 import javax.swing.event.MenuEvent;
68 import javax.swing.event.MenuListener;
71 * Base class with common functionality for JMol, Chimera or other structure
77 public abstract class StructureViewerBase extends GStructureViewer
78 implements Runnable, ViewSetProvider
81 * list of sequenceSet ids associated with the view
83 protected List<String> _aps = new ArrayList<>();
86 * list of alignment panels to use for superposition
88 protected Vector<AlignmentPanel> _alignwith = new Vector<>();
91 * list of alignment panels that are used for colouring structures by aligned
94 protected Vector<AlignmentPanel> _colourwith = new Vector<>();
96 private String viewId = null;
98 private AlignmentPanel ap;
100 protected boolean alignAddedStructures = false;
102 protected volatile boolean _started = false;
104 protected volatile boolean addingStructures = false;
106 protected Thread worker = null;
108 protected boolean allChainsSelected = false;
110 protected JMenu viewSelectionMenu;
113 * set after sequence colouring has been applied for this structure viewer.
114 * used to determine if the final sequence/structure mapping has been
117 protected volatile boolean seqColoursApplied = false;
119 private JCheckBoxMenuItem showFeatures;
122 * Default constructor
124 public StructureViewerBase()
130 * @return true if added structures should be aligned to existing one(s)
133 public boolean isAlignAddedStructures()
135 return alignAddedStructures;
141 * if added structures should be aligned to existing one(s)
144 public void setAlignAddedStructures(boolean alignAdded)
146 alignAddedStructures = alignAdded;
152 * @return true if this Jmol instance is linked with the given alignPanel
154 public boolean isLinkedWith(AlignmentPanel ap2)
156 return _aps.contains(ap2.av.getSequenceSetId());
159 public boolean isUsedForAligment(AlignmentPanel ap2)
162 return (_alignwith != null) && _alignwith.contains(ap2);
166 public boolean isUsedForColourBy(Object o)
168 return (_colourwith != null) && _colourwith.contains(o);
173 * @return TRUE if the view is NOT being coloured by the alignment colours.
175 public boolean isColouredByViewer()
177 return !getBinding().isColourBySequence();
180 public String getViewId()
184 viewId = System.currentTimeMillis() + "." + this.hashCode();
189 protected void setViewId(String viewId)
191 this.viewId = viewId;
194 public abstract String getStateInfo();
196 protected void buildActionMenu()
198 if (_alignwith == null)
200 _alignwith = new Vector<>();
202 if (_alignwith.size() == 0 && ap != null)
207 for (Component c : viewerActionMenu.getMenuComponents())
209 if (c != alignStructs)
211 viewerActionMenu.remove((JMenuItem) c);
216 public AlignmentPanel getAlignmentPanel()
221 protected void setAlignmentPanel(AlignmentPanel alp)
227 public AlignmentPanel[] getAllAlignmentPanels()
229 AlignmentPanel[] t, list = new AlignmentPanel[0];
230 for (String setid : _aps)
232 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
235 t = new AlignmentPanel[list.length + panels.length];
236 System.arraycopy(list, 0, t, 0, list.length);
237 System.arraycopy(panels, 0, t, list.length, panels.length);
246 * set the primary alignmentPanel reference and add another alignPanel to the
247 * list of ones to use for colouring and aligning
251 public void addAlignmentPanel(AlignmentPanel nap)
253 if (getAlignmentPanel() == null)
255 setAlignmentPanel(nap);
257 if (!_aps.contains(nap.av.getSequenceSetId()))
259 _aps.add(nap.av.getSequenceSetId());
264 * remove any references held to the given alignment panel
268 public void removeAlignmentPanel(AlignmentPanel nap)
272 _alignwith.remove(nap);
273 _colourwith.remove(nap);
274 if (getAlignmentPanel() == nap)
276 setAlignmentPanel(null);
277 for (AlignmentPanel aps : getAllAlignmentPanels())
281 setAlignmentPanel(aps);
286 } catch (Exception ex)
289 if (getAlignmentPanel() != null)
295 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
297 addAlignmentPanel(nap);
298 if (!_alignwith.contains(nap))
304 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
306 if (_alignwith.contains(nap))
308 _alignwith.remove(nap);
312 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
313 boolean enableColourBySeq)
315 useAlignmentPanelForColourbyseq(nap);
316 seqColour.setSelected(enableColourBySeq);
317 viewerColour.setSelected(!enableColourBySeq);
319 getBinding().setColourBy(enableColourBySeq ? ColourBy.Sequence : ColourBy.Viewer);
322 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
324 addAlignmentPanel(nap);
325 if (!_colourwith.contains(nap))
327 _colourwith.add(nap);
331 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
333 if (_colourwith.contains(nap))
335 _colourwith.remove(nap);
339 public abstract ViewerType getViewerType();
341 protected abstract IProgressIndicator getIProgressIndicator();
344 * add a new structure (with associated sequences and chains) to this viewer,
345 * retrieving it if necessary first.
351 * if true, new structure(s) will be aligned using associated
355 protected void addStructure(final PDBEntry pdbentry,
356 final SequenceI[] seqs, final String[] chains,
357 final IProgressIndicator alignFrame)
359 if (pdbentry.getFile() == null)
361 if (worker != null && worker.isAlive())
363 // a retrieval is in progress, wait around and add ourselves to the
365 new Thread(new Runnable()
370 while (worker != null && worker.isAlive() && _started)
374 Thread.sleep(100 + ((int) Math.random() * 100));
376 } catch (Exception e)
380 // and call ourselves again.
381 addStructure(pdbentry, seqs, chains, alignFrame);
387 // otherwise, start adding the structure.
388 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
390 { seqs }, new String[][] { chains });
391 addingStructures = true;
393 worker = new Thread(this);
398 protected boolean hasPdbId(String pdbId)
400 return getBinding().hasPdbId(pdbId);
404 * Returns a list of any viewer of the instantiated type. The list is
405 * restricted to those linked to the given alignment panel if it is not null.
407 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
409 return Desktop.instance.getStructureViewers(alp, this.getClass());
413 public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
414 String[] chains, final AlignmentViewPanel apanel, String pdbId)
417 * JAL-1742 exclude view with this structure already mapped (don't offer
418 * to align chain B to chain A of the same structure); code may defend
419 * against this possibility before we reach here
425 AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
427 useAlignmentPanelForSuperposition(alignPanel);
428 addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
432 * Adds mappings for the given sequences to an already opened PDB structure,
433 * and updates any viewers that have the PDB file
440 public void addSequenceMappingsToStructure(SequenceI[] seq,
441 String[] chains, final AlignmentViewPanel alpanel,
444 AlignmentPanel apanel = (AlignmentPanel) alpanel;
446 // TODO : Fix multiple seq to one chain issue here.
448 * create the mappings
450 apanel.getStructureSelectionManager().setMapping(seq, chains,
451 pdbFilename, DataSourceType.FILE, getIProgressIndicator());
454 * alert the FeatureRenderer to show new (PDB RESNUM) features
456 if (apanel.getSeqPanel().seqCanvas.fr != null)
458 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
459 // note - we don't do a refresh for structure here because we do it
460 // explicitly for all panels later on
461 apanel.paintAlignment(true, false);
465 * add the sequences to any other viewers (of the same type) for this pdb
468 // JBPNOTE: this looks like a binding routine, rather than a gui routine
469 for (StructureViewerBase viewer : getViewersFor(null))
471 AAStructureBindingModel bindingModel = viewer.getBinding();
472 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
474 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
476 bindingModel.addSequence(pe, seq);
477 viewer.addAlignmentPanel(apanel);
479 * add it to the set of alignments used for colouring structure by
482 viewer.useAlignmentPanelForColourbyseq(apanel);
483 viewer.buildActionMenu();
484 apanel.getStructureSelectionManager()
485 .sequenceColoursChanged(apanel);
493 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
494 final AlignmentViewPanel apanel, String pdbId)
496 String alreadyMapped = apanel.getStructureSelectionManager()
497 .alreadyMappedToFile(pdbId);
499 if (alreadyMapped == null)
504 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
508 void setChainMenuItems(List<String> chainNames)
510 chainMenu.removeAll();
511 if (chainNames == null || chainNames.isEmpty())
515 JMenuItem menuItem = new JMenuItem(
516 MessageManager.getString("label.all"));
517 menuItem.addActionListener(new ActionListener()
520 public void actionPerformed(ActionEvent evt)
522 allChainsSelected = true;
523 for (int i = 0; i < chainMenu.getItemCount(); i++)
525 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
527 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
530 showSelectedChains();
531 allChainsSelected = false;
535 chainMenu.add(menuItem);
537 for (String chain : chainNames)
539 menuItem = new JCheckBoxMenuItem(chain, true);
540 menuItem.addItemListener(new ItemListener()
543 public void itemStateChanged(ItemEvent evt)
545 if (!allChainsSelected)
547 showSelectedChains();
552 chainMenu.add(menuItem);
556 abstract void showSelectedChains();
559 * Action on selecting one of Jalview's registered colour schemes
562 public void changeColour_actionPerformed(String colourSchemeName)
564 showFeatures.setEnabled(true);
565 AlignmentI al = getAlignmentPanel().av.getAlignment();
566 ColourSchemeI cs = ColourSchemes.getInstance()
567 .getColourScheme(colourSchemeName, al, null);
568 getBinding().setJalviewColourScheme(cs, getAlignmentPanel(), showFeatures.isSelected());
572 * Builds the colour menu
574 protected void buildColourMenu()
576 colourMenu.removeAll();
577 AlignmentI al = getAlignmentPanel().av.getAlignment();
579 showFeatures = new JCheckBoxMenuItem(MessageManager.getString(
580 "label.show_sequence_features"));
581 colourMenu.add(showFeatures);
582 colourMenu.addSeparator();
585 * add colour by sequence, by chain, by charge and cysteine
587 colourMenu.add(seqColour);
588 colourMenu.add(chainColour);
589 colourMenu.add(chargeColour);
590 chargeColour.setEnabled(!al.isNucleotide());
593 * add all colour schemes registered to Jalview
595 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
599 * add 'colour by viewer' (menu item text is set in subclasses)
601 viewerColour.setSelected(false);
602 viewerColour.addActionListener(new ActionListener()
605 public void actionPerformed(ActionEvent actionEvent)
607 viewerColour_actionPerformed(actionEvent);
610 colourMenu.add(viewerColour);
613 * add 'set background colour'
615 JMenuItem backGround = new JMenuItem();
617 .setText(MessageManager.getString("action.background_colour"));
618 backGround.addActionListener(new ActionListener()
621 public void actionPerformed(ActionEvent actionEvent)
623 background_actionPerformed(actionEvent);
626 colourMenu.add(backGround);
629 * add colour buttons to a group so their selection is
630 * mutually exclusive (background colour is a separate option)
632 itemGroup.add(seqColour);
633 itemGroup.add(chainColour);
634 itemGroup.add(chargeColour);
635 itemGroup.add(viewerColour);
638 * action on show/hide features is to 'click' the currently
639 * selected colour in order to update the display
641 showFeatures.addActionListener(new ActionListener()
644 public void actionPerformed(ActionEvent e)
646 Enumeration<AbstractButton> items = itemGroup.getElements();
647 while (items.hasMoreElements())
649 AbstractButton item = items.nextElement();
650 if (item.isSelected())
660 * Construct menu items
662 protected void initMenus()
664 AAStructureBindingModel binding = getBinding();
666 seqColour = new JRadioButtonMenuItem();
667 seqColour.setText(MessageManager.getString("action.by_sequence"));
668 seqColour.setSelected(binding.isColourBySequence());
669 seqColour.addActionListener(new ActionListener()
672 public void actionPerformed(ActionEvent actionEvent)
674 seqColour_actionPerformed(actionEvent);
678 chainColour = new JRadioButtonMenuItem();
679 chainColour.setText(MessageManager.getString("action.by_chain"));
680 chainColour.addActionListener(new ActionListener()
683 public void actionPerformed(ActionEvent actionEvent)
685 chainColour_actionPerformed(actionEvent);
689 chargeColour = new JRadioButtonMenuItem();
690 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
691 chargeColour.addActionListener(new ActionListener()
694 public void actionPerformed(ActionEvent actionEvent)
696 chargeColour_actionPerformed(actionEvent);
700 viewerColour = new JRadioButtonMenuItem();
701 // text is set in overrides of this method
702 viewerColour.setSelected(!binding.isColourBySequence());
704 if (_colourwith == null)
706 _colourwith = new Vector<>();
708 if (_alignwith == null)
710 _alignwith = new Vector<>();
713 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
714 MessageManager.getString("label.colour_by"), this, _colourwith,
718 public void itemStateChanged(ItemEvent e)
720 if (!seqColour.isSelected())
726 // update the Chimera display now.
727 seqColour_actionPerformed(null);
731 viewMenu.add(seqColourBy);
733 final ItemListener handler = new ItemListener()
736 public void itemStateChanged(ItemEvent e)
738 alignStructs.setEnabled(!_alignwith.isEmpty());
739 alignStructs.setToolTipText(MessageManager.formatMessage(
740 "label.align_structures_using_linked_alignment_views",
744 viewSelectionMenu = new ViewSelectionMenu(
745 MessageManager.getString("label.superpose_with"), this,
746 _alignwith, handler);
747 handler.itemStateChanged(null);
748 viewerActionMenu.add(viewSelectionMenu, 0);
749 viewerActionMenu.addMenuListener(new MenuListener()
752 public void menuSelected(MenuEvent e)
754 handler.itemStateChanged(null);
758 public void menuDeselected(MenuEvent e)
763 public void menuCanceled(MenuEvent e)
772 * Sends commands to the structure viewer to superimpose structures based on
773 * currently associated alignments. May optionally return an error message for
777 protected String alignStructs_actionPerformed(ActionEvent actionEvent)
779 return alignStructs_withAllAlignPanels();
782 protected String alignStructs_withAllAlignPanels()
784 if (getAlignmentPanel() == null)
789 if (_alignwith.size() == 0)
791 _alignwith.add(getAlignmentPanel());
797 AlignmentI[] als = new Alignment[_alignwith.size()];
798 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
799 int[] alm = new int[_alignwith.size()];
802 for (AlignmentPanel alignPanel : _alignwith)
804 als[a] = alignPanel.av.getAlignment();
806 alc[a++] = alignPanel.av.getAlignment().getHiddenColumns();
808 reply = getBinding().superposeStructures(als, alm, alc);
811 String text = MessageManager
812 .formatMessage("error.superposition_failed", reply);
813 statusBar.setText(text);
815 } catch (Exception e)
817 StringBuffer sp = new StringBuffer();
818 for (AlignmentPanel alignPanel : _alignwith)
820 sp.append("'" + alignPanel.alignFrame.getTitle() + "' ");
822 Cache.log.info("Couldn't align structures with the " + sp.toString()
823 + "associated alignment panels.", e);
829 public void background_actionPerformed(ActionEvent actionEvent)
831 Color col = JColorChooser.showDialog(this,
832 MessageManager.getString("label.select_background_colour"),
836 getBinding().setBackgroundColour(col);
841 public void viewerColour_actionPerformed(ActionEvent actionEvent)
843 showFeatures.setEnabled(false);
844 getBinding().setColourBy(ColourBy.Viewer);
848 public void chainColour_actionPerformed(ActionEvent actionEvent)
850 showFeatures.setEnabled(false);
851 getBinding().colourByChain();
855 public void chargeColour_actionPerformed(ActionEvent actionEvent)
857 showFeatures.setEnabled(false);
858 getBinding().colourByCharge();
862 public void seqColour_actionPerformed(ActionEvent actionEvent)
864 showFeatures.setEnabled(false);
865 AAStructureBindingModel binding = getBinding();
866 if (_colourwith == null)
868 _colourwith = new Vector<>();
871 if (!binding.isLoadingFromArchive())
873 if (_colourwith.isEmpty() && ap != null)
875 // Make the currently displayed alignment panel the associated view
876 _colourwith.add(ap);//.alignFrame.alignPanel); ?!?
880 showFeatures.setSelected(ap == null ? false : ap.av.isShowSequenceFeatures());
882 // Set the colour using the current view for the associated alignframe
883 for (AlignmentPanel alignPanel : _colourwith)
885 binding.colourBySequence(alignPanel, showFeatures.isSelected());
887 seqColoursApplied = true;
891 public void pdbFile_actionPerformed(ActionEvent actionEvent)
893 JalviewFileChooser chooser = new JalviewFileChooser(
894 Cache.getProperty("LAST_DIRECTORY"));
896 chooser.setFileView(new JalviewFileView());
897 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
898 chooser.setToolTipText(MessageManager.getString("action.save"));
900 int value = chooser.showSaveDialog(this);
902 if (value == JalviewFileChooser.APPROVE_OPTION)
904 BufferedReader in = null;
907 // TODO: cope with multiple PDB files in view
908 in = new BufferedReader(
909 new FileReader(getBinding().getStructureFiles()[0]));
910 File outFile = chooser.getSelectedFile();
912 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
914 while ((data = in.readLine()) != null)
916 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
922 } catch (Exception ex)
924 ex.printStackTrace();
932 } catch (IOException e)
942 public void viewMapping_actionPerformed(ActionEvent actionEvent)
944 CutAndPasteTransfer cap = new CutAndPasteTransfer();
947 cap.appendText(getBinding().printMappings());
948 } catch (OutOfMemoryError e)
951 "composing sequence-structure alignments for display in text box.",
956 Desktop.addInternalFrame(cap,
957 MessageManager.getString("label.pdb_sequence_mapping"), 550,
961 protected abstract String getViewerName();
964 * Configures the title and menu items of the viewer panel.
967 public void updateTitleAndMenus()
969 AAStructureBindingModel binding = getBinding();
970 if (binding.hasFileLoadingError())
975 setChainMenuItems(binding.getChainNames());
977 this.setTitle(binding.getViewerTitle(getViewerName(), true));
980 * enable 'Superpose with' if more than one mapped structure
982 viewSelectionMenu.setEnabled(false);
983 if (getBinding().getStructureFiles().length > 1
984 && getBinding().getSequence().length > 1)
986 viewSelectionMenu.setEnabled(true);
990 * Show action menu if it has any enabled items
992 viewerActionMenu.setVisible(false);
993 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
995 if (viewerActionMenu.getItem(i).isEnabled())
997 viewerActionMenu.setVisible(true);
1002 if (!binding.isLoadingFromArchive())
1004 seqColour_actionPerformed(null);
1009 public String toString()
1015 public boolean hasMapping()
1017 if (worker != null && (addingStructures || _started))
1021 if (getBinding() == null)
1023 if (_aps == null || _aps.size() == 0)
1025 // viewer has been closed, but we did at some point run.
1030 String[] pdbids = getBinding().getStructureFiles();
1036 for (String pdbid:pdbids) {
1037 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1038 if (sm!=null && sm.length>0 && sm[0]!=null) {
1042 // only return true if there is a mapping for every structure file we have loaded
1043 if (p == 0 || p != pdbids.length)
1047 // and that coloring has been applied
1048 return seqColoursApplied;
1052 public void raiseViewer()