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
427 protected boolean addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
428 String[] chains, final AlignmentPanel apanel, String pdbId)
430 for (StructureViewerBase view : getViewersFor(apanel))
432 // TODO: highlight the view somehow
434 * JAL-1742 exclude view with this structure already mapped (don't offer
435 * to align chain B to chain A of the same structure)
437 if (view.hasPdbId(pdbId))
441 int option = chooseAlignStructureToViewer(pdbId, view);
442 if (option == JvOptionPane.CANCEL_OPTION)
446 else if (option == JvOptionPane.YES_OPTION)
448 view.useAlignmentPanelForSuperposition(apanel);
449 view.addStructure(pdbentry, seq, chains, true, apanel.alignFrame);
454 // NO_OPTION - offer the next viewer if any
459 * nothing offered and selected
465 * Adds mappings for the given sequences to an already opened PDB structure,
466 * and updates any viewers that have the PDB file
473 protected void addSequenceMappingsToStructure(SequenceI[] seq,
474 String[] chains, final AlignmentPanel apanel, String pdbFilename)
476 // TODO : Fix multiple seq to one chain issue here.
478 * create the mappings
480 apanel.getStructureSelectionManager().setMapping(seq, chains,
481 pdbFilename, DataSourceType.FILE, getIProgressIndicator());
484 * alert the FeatureRenderer to show new (PDB RESNUM) features
486 if (apanel.getSeqPanel().seqCanvas.fr != null)
488 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
489 // note - we don't do a refresh for structure here because we do it
490 // explicitly for all panels later on
491 apanel.paintAlignment(true, false);
495 * add the sequences to any other viewers (of the same type) for this pdb
498 // JBPNOTE: this looks like a binding routine, rather than a gui routine
499 for (StructureViewerBase viewer : getViewersFor(null))
501 AAStructureBindingModel bindingModel = viewer.getBinding();
502 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
504 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
506 bindingModel.addSequence(pe, seq);
507 viewer.addAlignmentPanel(apanel);
509 * add it to the set of alignments used for colouring structure by
512 viewer.useAlignmentPanelForColourbyseq(apanel);
513 viewer.buildActionMenu();
514 apanel.getStructureSelectionManager()
515 .sequenceColoursChanged(apanel);
523 * Check if the PDB file is already loaded, if so offer to add it to the
530 * @return true if the user chooses to add to a viewer, or to cancel entirely
532 protected boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
533 final AlignmentPanel apanel, String pdbId)
535 boolean finished = false;
536 String alreadyMapped = apanel.getStructureSelectionManager()
537 .alreadyMappedToFile(pdbId);
539 if (alreadyMapped != null)
542 * the PDB file is already loaded
544 int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
545 MessageManager.formatMessage(
546 "label.pdb_entry_is_already_displayed", new Object[]
548 MessageManager.formatMessage(
549 "label.map_sequences_to_visible_window", new Object[]
551 JvOptionPane.YES_NO_CANCEL_OPTION);
552 if (option == JvOptionPane.CANCEL_OPTION)
556 else if (option == JvOptionPane.YES_OPTION)
558 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
565 void setChainMenuItems(List<String> chainNames)
567 chainMenu.removeAll();
568 if (chainNames == null || chainNames.isEmpty())
572 JMenuItem menuItem = new JMenuItem(
573 MessageManager.getString("label.all"));
574 menuItem.addActionListener(new ActionListener()
577 public void actionPerformed(ActionEvent evt)
579 allChainsSelected = true;
580 for (int i = 0; i < chainMenu.getItemCount(); i++)
582 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
584 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
587 showSelectedChains();
588 allChainsSelected = false;
592 chainMenu.add(menuItem);
594 for (String chain : chainNames)
596 menuItem = new JCheckBoxMenuItem(chain, true);
597 menuItem.addItemListener(new ItemListener()
600 public void itemStateChanged(ItemEvent evt)
602 if (!allChainsSelected)
604 showSelectedChains();
609 chainMenu.add(menuItem);
613 abstract void showSelectedChains();
616 * Action on selecting one of Jalview's registered colour schemes
619 public void changeColour_actionPerformed(String colourSchemeName)
621 AlignmentI al = getAlignmentPanel().av.getAlignment();
622 ColourSchemeI cs = ColourSchemes.getInstance()
623 .getColourScheme(colourSchemeName, al, null);
624 getBinding().setJalviewColourScheme(cs);
628 * Builds the colour menu
630 protected void buildColourMenu()
632 colourMenu.removeAll();
633 AlignmentI al = getAlignmentPanel().av.getAlignment();
636 * add colour by sequence, by chain, by charge and cysteine
638 colourMenu.add(seqColour);
639 colourMenu.add(chainColour);
640 colourMenu.add(chargeColour);
641 chargeColour.setEnabled(!al.isNucleotide());
644 * add all 'simple' (per-residue) colour schemes registered to Jalview
646 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
650 * add 'colour by viewer' (menu item text is set in subclasses)
652 viewerColour.setSelected(false);
653 viewerColour.addActionListener(new ActionListener()
656 public void actionPerformed(ActionEvent actionEvent)
658 viewerColour_actionPerformed(actionEvent);
661 colourMenu.add(viewerColour);
664 * add 'set background colour'
666 JMenuItem backGround = new JMenuItem();
668 .setText(MessageManager.getString("action.background_colour"));
669 backGround.addActionListener(new ActionListener()
672 public void actionPerformed(ActionEvent actionEvent)
674 background_actionPerformed(actionEvent);
677 colourMenu.add(backGround);
680 * add colour buttons to a group so their selection is
681 * mutually exclusive (background colour is a separate option)
683 itemGroup.add(seqColour);
684 itemGroup.add(chainColour);
685 itemGroup.add(chargeColour);
686 itemGroup.add(viewerColour);
690 * Construct menu items
692 protected void initMenus()
694 AAStructureBindingModel binding = getBinding();
696 seqColour = new JRadioButtonMenuItem();
697 seqColour.setText(MessageManager.getString("action.by_sequence"));
698 seqColour.setName(ViewerColour.BySequence.name());
699 seqColour.setSelected(binding.isColourBySequence());
700 seqColour.addActionListener(new ActionListener()
703 public void actionPerformed(ActionEvent actionEvent)
705 seqColour_actionPerformed(actionEvent);
709 chainColour = new JRadioButtonMenuItem();
710 chainColour.setText(MessageManager.getString("action.by_chain"));
711 chainColour.setName(ViewerColour.ByChain.name());
712 chainColour.addActionListener(new ActionListener()
715 public void actionPerformed(ActionEvent actionEvent)
717 chainColour_actionPerformed(actionEvent);
721 chargeColour = new JRadioButtonMenuItem();
722 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
723 chargeColour.setName(ViewerColour.ChargeCysteine.name());
724 chargeColour.addActionListener(new ActionListener()
727 public void actionPerformed(ActionEvent actionEvent)
729 chargeColour_actionPerformed(actionEvent);
733 viewerColour = new JRadioButtonMenuItem();
734 // text is set in overrides of this method
735 viewerColour.setName(ViewerColour.ByViewer.name());
736 viewerColour.setSelected(!binding.isColourBySequence());
738 if (_colourwith == null)
740 _colourwith = new Vector<>();
742 if (_alignwith == null)
744 _alignwith = new Vector<>();
747 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
748 MessageManager.getString("label.colour_by"), this, _colourwith,
752 public void itemStateChanged(ItemEvent e)
754 if (!seqColour.isSelected())
760 // update the Chimera display now.
761 seqColour_actionPerformed(null);
765 viewMenu.add(seqColourBy);
767 final ItemListener handler = new ItemListener()
770 public void itemStateChanged(ItemEvent e)
772 alignStructs.setEnabled(!_alignwith.isEmpty());
773 alignStructs.setToolTipText(MessageManager.formatMessage(
774 "label.align_structures_using_linked_alignment_views",
778 viewSelectionMenu = new ViewSelectionMenu(
779 MessageManager.getString("label.superpose_with"), this,
780 _alignwith, handler);
781 handler.itemStateChanged(null);
782 viewerActionMenu.add(viewSelectionMenu, 0);
783 viewerActionMenu.addMenuListener(new MenuListener()
786 public void menuSelected(MenuEvent e)
788 handler.itemStateChanged(null);
792 public void menuDeselected(MenuEvent e)
797 public void menuCanceled(MenuEvent e)
806 public void setJalviewColourScheme(ColourSchemeI cs)
808 getBinding().setJalviewColourScheme(cs);
812 * Sends commands to the structure viewer to superimpose structures based on
813 * currently associated alignments. May optionally return an error message for
817 protected String alignStructs_actionPerformed(ActionEvent actionEvent)
819 return alignStructs_withAllAlignPanels();
822 protected String alignStructs_withAllAlignPanels()
824 if (getAlignmentPanel() == null)
829 if (_alignwith.size() == 0)
831 _alignwith.add(getAlignmentPanel());
837 AlignmentI[] als = new Alignment[_alignwith.size()];
838 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
839 int[] alm = new int[_alignwith.size()];
842 for (AlignmentPanel ap : _alignwith)
844 als[a] = ap.av.getAlignment();
846 alc[a++] = ap.av.getAlignment().getHiddenColumns();
848 reply = getBinding().superposeStructures(als, alm, alc);
851 String text = MessageManager
852 .formatMessage("error.superposition_failed", reply);
853 statusBar.setText(text);
855 } catch (Exception e)
857 StringBuffer sp = new StringBuffer();
858 for (AlignmentPanel ap : _alignwith)
860 sp.append("'" + ap.alignFrame.getTitle() + "' ");
862 Cache.log.info("Couldn't align structures with the " + sp.toString()
863 + "associated alignment panels.", e);
869 public void background_actionPerformed(ActionEvent actionEvent)
871 Color col = JColorChooser.showDialog(this,
872 MessageManager.getString("label.select_background_colour"),
876 getBinding().setBackgroundColour(col);
881 public void viewerColour_actionPerformed(ActionEvent actionEvent)
883 if (viewerColour.isSelected())
885 // disable automatic sequence colouring.
886 getBinding().setColourBySequence(false);
891 public void chainColour_actionPerformed(ActionEvent actionEvent)
893 chainColour.setSelected(true);
894 getBinding().colourByChain();
898 public void chargeColour_actionPerformed(ActionEvent actionEvent)
900 chargeColour.setSelected(true);
901 getBinding().colourByCharge();
905 public void seqColour_actionPerformed(ActionEvent actionEvent)
907 AAStructureBindingModel binding = getBinding();
908 binding.setColourBySequence(seqColour.isSelected());
909 if (_colourwith == null)
911 _colourwith = new Vector<>();
913 if (binding.isColourBySequence())
915 if (!binding.isLoadingFromArchive())
917 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
919 // Make the currently displayed alignment panel the associated view
920 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
923 // Set the colour using the current view for the associated alignframe
924 for (AlignmentPanel ap : _colourwith)
926 binding.colourBySequence(ap);
928 seqColoursApplied = true;
933 public void pdbFile_actionPerformed(ActionEvent actionEvent)
935 JalviewFileChooser chooser = new JalviewFileChooser(
936 Cache.getProperty("LAST_DIRECTORY"));
938 chooser.setFileView(new JalviewFileView());
939 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
940 chooser.setToolTipText(MessageManager.getString("action.save"));
942 int value = chooser.showSaveDialog(this);
944 if (value == JalviewFileChooser.APPROVE_OPTION)
946 BufferedReader in = null;
949 // TODO: cope with multiple PDB files in view
950 in = new BufferedReader(
951 new FileReader(getBinding().getStructureFiles()[0]));
952 File outFile = chooser.getSelectedFile();
954 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
956 while ((data = in.readLine()) != null)
958 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
964 } catch (Exception ex)
966 ex.printStackTrace();
974 } catch (IOException e)
984 public void viewMapping_actionPerformed(ActionEvent actionEvent)
986 CutAndPasteTransfer cap = new CutAndPasteTransfer();
989 cap.appendText(getBinding().printMappings());
990 } catch (OutOfMemoryError e)
993 "composing sequence-structure alignments for display in text box.",
998 Desktop.addInternalFrame(cap,
999 MessageManager.getString("label.pdb_sequence_mapping"), 550,
1003 protected abstract String getViewerName();
1006 * Configures the title and menu items of the viewer panel.
1008 public void updateTitleAndMenus()
1010 AAStructureBindingModel binding = getBinding();
1011 if (binding.hasFileLoadingError())
1016 setChainMenuItems(binding.getChainNames());
1018 this.setTitle(binding.getViewerTitle(getViewerName(), true));
1021 * enable 'Superpose with' if more than one mapped structure
1023 viewSelectionMenu.setEnabled(false);
1024 if (getBinding().getStructureFiles().length > 1
1025 && getBinding().getSequence().length > 1)
1027 viewSelectionMenu.setEnabled(true);
1031 * Show action menu if it has any enabled items
1033 viewerActionMenu.setVisible(false);
1034 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
1036 if (viewerActionMenu.getItem(i).isEnabled())
1038 viewerActionMenu.setVisible(true);
1043 if (!binding.isLoadingFromArchive())
1045 seqColour_actionPerformed(null);
1050 public boolean hasMapping()
1052 if (worker != null && (addingStructures || _started))
1056 if (getBinding() == null)
1058 if (_aps == null || _aps.size() == 0)
1060 // viewer has been closed, but we did at some point run.
1065 String[] pdbids = getBinding().getStructureFiles();
1071 for (String pdbid:pdbids) {
1072 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1073 if (sm!=null && sm.length>0 && sm[0]!=null) {
1077 // only return true if there is a mapping for every structure file we have loaded
1078 if (p == 0 || p != pdbids.length)
1082 // and that coloring has been applied
1083 return seqColoursApplied;