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.Random;
57 import java.util.Vector;
59 import javax.swing.ButtonGroup;
60 import javax.swing.JCheckBoxMenuItem;
61 import javax.swing.JColorChooser;
62 import javax.swing.JMenu;
63 import javax.swing.JMenuItem;
64 import javax.swing.JRadioButtonMenuItem;
65 import javax.swing.event.MenuEvent;
66 import javax.swing.event.MenuListener;
69 * Base class with common functionality for JMol, Chimera or other structure
75 public abstract class StructureViewerBase extends GStructureViewer
76 implements Runnable, ViewSetProvider
79 * names for colour options (additional to Jalview colour schemes)
83 BySequence, ByChain, ChargeCysteine, ByViewer
87 * list of sequenceSet ids associated with the view
89 protected List<String> _aps = new ArrayList<>();
92 * list of alignment panels to use for superposition
94 protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
97 * list of alignment panels that are used for colouring structures by aligned
100 protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
102 private String viewId = null;
104 private AlignmentPanel ap;
106 protected boolean alignAddedStructures = false;
108 protected volatile boolean _started = false;
110 protected volatile boolean addingStructures = false;
112 protected Thread worker = null;
114 protected boolean allChainsSelected = false;
116 protected JMenu viewSelectionMenu;
119 * set after sequence colouring has been applied for this structure viewer.
120 * used to determine if the final sequence/structure mapping has been
123 protected volatile boolean seqColoursApplied = false;
125 private IProgressIndicator progressBar = null;
127 private Random random = new Random();
130 * Default constructor
132 public StructureViewerBase()
138 * @return true if added structures should be aligned to existing one(s)
141 public boolean isAlignAddedStructures()
143 return alignAddedStructures;
149 * if added structures should be aligned to existing one(s)
152 public void setAlignAddedStructures(boolean alignAdded)
154 alignAddedStructures = alignAdded;
160 * @return true if this Jmol instance is linked with the given alignPanel
162 public boolean isLinkedWith(AlignmentPanel ap2)
164 return _aps.contains(ap2.av.getSequenceSetId());
167 public boolean isUsedforaligment(AlignmentViewPanel ap2)
170 return (_alignwith != null) && _alignwith.contains(ap2);
174 public boolean isUsedForColourBy(AlignmentViewPanel ap2)
176 return (_colourwith != null) && _colourwith.contains(ap2);
181 * @return TRUE if the view is NOT being coloured by the alignment colours.
183 public boolean isColouredByViewer()
185 return !getBinding().isColourBySequence();
188 public String getViewId()
192 viewId = System.currentTimeMillis() + "." + this.hashCode();
197 protected void setViewId(String viewId)
199 this.viewId = viewId;
202 public abstract String getStateInfo();
204 protected void buildActionMenu()
206 if (_alignwith == null)
208 _alignwith = new Vector<>();
210 if (_alignwith.size() == 0 && ap != null)
215 for (Component c : viewerActionMenu.getMenuComponents())
217 if (c != alignStructs)
219 viewerActionMenu.remove((JMenuItem) c);
225 public AlignmentPanel getAlignmentPanel()
230 protected void setAlignmentPanel(AlignmentPanel alp)
236 public AlignmentPanel[] getAllAlignmentPanels()
238 AlignmentPanel[] t, list = new AlignmentPanel[0];
239 for (String setid : _aps)
241 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
244 t = new AlignmentPanel[list.length + panels.length];
245 System.arraycopy(list, 0, t, 0, list.length);
246 System.arraycopy(panels, 0, t, list.length, panels.length);
255 * set the primary alignmentPanel reference and add another alignPanel to the
256 * list of ones to use for colouring and aligning
260 public void addAlignmentPanel(AlignmentPanel nap)
262 if (getAlignmentPanel() == null)
264 setAlignmentPanel(nap);
266 if (!_aps.contains(nap.av.getSequenceSetId()))
268 _aps.add(nap.av.getSequenceSetId());
273 * remove any references held to the given alignment panel
278 public void removeAlignmentPanel(AlignmentViewPanel nap)
282 _alignwith.remove(nap);
283 _colourwith.remove(nap);
284 if (getAlignmentPanel() == nap)
286 setAlignmentPanel(null);
287 for (AlignmentPanel aps : getAllAlignmentPanels())
291 setAlignmentPanel(aps);
296 } catch (Exception ex)
299 if (getAlignmentPanel() != null)
305 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
307 addAlignmentPanel(nap);
308 if (!_alignwith.contains(nap))
314 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
316 if (_alignwith.contains(nap))
318 _alignwith.remove(nap);
322 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
323 boolean enableColourBySeq)
325 useAlignmentPanelForColourbyseq(nap);
326 getBinding().setColourBySequence(enableColourBySeq);
327 seqColour.setSelected(enableColourBySeq);
328 viewerColour.setSelected(!enableColourBySeq);
331 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
333 addAlignmentPanel(nap);
334 if (!_colourwith.contains(nap))
336 _colourwith.add(nap);
340 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
342 if (_colourwith.contains(nap))
344 _colourwith.remove(nap);
348 public abstract ViewerType getViewerType();
351 * add a new structure (with associated sequences and chains) to this viewer,
352 * retrieving it if necessary first.
358 * if true, new structure(s) will be aligned using associated
362 protected void addStructure(final PDBEntry pdbentry,
363 final SequenceI[] seqs, final String[] chains,
364 final IProgressIndicator alignFrame)
366 if (pdbentry.getFile() == null)
368 if (worker != null && worker.isAlive())
370 // a retrieval is in progress, wait around and add ourselves to the
372 new Thread(new Runnable()
377 while (worker != null && worker.isAlive() && _started)
381 Thread.sleep(100 + ((int) Math.random() * 100));
383 } catch (Exception e)
387 // and call ourselves again.
388 addStructure(pdbentry, seqs, chains, alignFrame);
394 // otherwise, start adding the structure.
395 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
397 { seqs }, new String[][] { chains });
398 addingStructures = true;
400 worker = new Thread(this);
405 protected boolean hasPdbId(String pdbId)
407 return getBinding().hasPdbId(pdbId);
411 * Returns a list of any viewer of the instantiated type. The list is
412 * restricted to those linked to the given alignment panel if it is not null.
414 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
416 return Desktop.instance.getStructureViewers(alp, this.getClass());
420 public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
421 String[] chains, final AlignmentViewPanel apanel, String pdbId)
424 * JAL-1742 exclude view with this structure already mapped (don't offer
425 * to align chain B to chain A of the same structure); code may defend
426 * against this possibility before we reach here
432 AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error if this
434 useAlignmentPanelForSuperposition(alignPanel);
435 addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
439 * Adds mappings for the given sequences to an already opened PDB structure,
440 * and updates any viewers that have the PDB file
447 public void addSequenceMappingsToStructure(SequenceI[] seq,
448 String[] chains, final AlignmentViewPanel alpanel,
451 AlignmentPanel apanel = (AlignmentPanel) alpanel;
453 // TODO : Fix multiple seq to one chain issue here.
455 * create the mappings
457 apanel.getStructureSelectionManager().setMapping(seq, chains,
458 pdbFilename, DataSourceType.FILE, getProgressIndicator());
461 * alert the FeatureRenderer to show new (PDB RESNUM) features
463 if (apanel.getSeqPanel().seqCanvas.fr != null)
465 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
466 // note - we don't do a refresh for structure here because we do it
467 // explicitly for all panels later on
468 apanel.paintAlignment(true, false);
472 * add the sequences to any other viewers (of the same type) for this pdb
475 // JBPNOTE: this looks like a binding routine, rather than a gui routine
476 for (StructureViewerBase viewer : getViewersFor(null))
478 AAStructureBindingModel bindingModel = viewer.getBinding();
479 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
481 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
483 bindingModel.addSequence(pe, seq);
484 viewer.addAlignmentPanel(apanel);
486 * add it to the set of alignments used for colouring structure by
489 viewer.useAlignmentPanelForColourbyseq(apanel);
490 viewer.buildActionMenu();
491 apanel.getStructureSelectionManager()
492 .sequenceColoursChanged(apanel);
500 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
501 final AlignmentViewPanel apanel, String pdbId)
503 String alreadyMapped = apanel.getStructureSelectionManager()
504 .alreadyMappedToFile(pdbId);
506 if (alreadyMapped == null)
511 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
515 void setChainMenuItems(List<String> chainNames)
517 chainMenu.removeAll();
518 if (chainNames == null || chainNames.isEmpty())
522 JMenuItem menuItem = new JMenuItem(
523 MessageManager.getString("label.all"));
524 menuItem.addActionListener(new ActionListener()
527 public void actionPerformed(ActionEvent evt)
529 allChainsSelected = true;
530 for (int i = 0; i < chainMenu.getItemCount(); i++)
532 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
534 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
537 showSelectedChains();
538 allChainsSelected = false;
542 chainMenu.add(menuItem);
544 for (String chain : chainNames)
546 menuItem = new JCheckBoxMenuItem(chain, true);
547 menuItem.addItemListener(new ItemListener()
550 public void itemStateChanged(ItemEvent evt)
552 if (!allChainsSelected)
554 showSelectedChains();
559 chainMenu.add(menuItem);
564 * Action on selecting one of Jalview's registered colour schemes
567 public void changeColour_actionPerformed(String colourSchemeName)
569 AlignmentI al = getAlignmentPanel().av.getAlignment();
570 ColourSchemeI cs = ColourSchemes.getInstance()
571 .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
573 getBinding().colourByJalviewColourScheme(cs);
577 * Builds the colour menu
579 protected void buildColourMenu()
581 colourMenu.removeAll();
582 AlignmentI al = getAlignmentPanel().av.getAlignment();
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 'simple' (per-residue) 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();
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();
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);
639 * Construct menu items
641 protected void initMenus()
643 AAStructureBindingModel binding = getBinding();
645 seqColour = new JRadioButtonMenuItem();
646 seqColour.setText(MessageManager.getString("action.by_sequence"));
647 seqColour.setName(ViewerColour.BySequence.name());
648 seqColour.setSelected(binding.isColourBySequence());
649 seqColour.addActionListener(new ActionListener()
652 public void actionPerformed(ActionEvent actionEvent)
654 seqColour_actionPerformed();
658 chainColour = new JRadioButtonMenuItem();
659 chainColour.setText(MessageManager.getString("action.by_chain"));
660 chainColour.setName(ViewerColour.ByChain.name());
661 chainColour.addActionListener(new ActionListener()
664 public void actionPerformed(ActionEvent actionEvent)
666 chainColour_actionPerformed();
670 chargeColour = new JRadioButtonMenuItem();
671 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
672 chargeColour.setName(ViewerColour.ChargeCysteine.name());
673 chargeColour.addActionListener(new ActionListener()
676 public void actionPerformed(ActionEvent actionEvent)
678 chargeColour_actionPerformed();
682 viewerColour = new JRadioButtonMenuItem();
683 // text is set in overrides of this method
684 viewerColour.setName(ViewerColour.ByViewer.name());
685 viewerColour.setSelected(!binding.isColourBySequence());
687 if (_colourwith == null)
689 _colourwith = new Vector<>();
691 if (_alignwith == null)
693 _alignwith = new Vector<>();
696 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
697 MessageManager.getString("label.colour_by"), this, _colourwith,
701 public void itemStateChanged(ItemEvent e)
703 if (!seqColour.isSelected())
709 // update the Chimera display now.
710 seqColour_actionPerformed();
714 viewMenu.add(seqColourBy);
716 final ItemListener handler = new ItemListener()
719 public void itemStateChanged(ItemEvent e)
721 alignStructs.setEnabled(!_alignwith.isEmpty());
722 alignStructs.setToolTipText(MessageManager.formatMessage(
723 "label.align_structures_using_linked_alignment_views",
727 viewSelectionMenu = new ViewSelectionMenu(
728 MessageManager.getString("label.superpose_with"), this,
729 _alignwith, handler);
730 handler.itemStateChanged(null);
731 viewerActionMenu.add(viewSelectionMenu, 0);
732 viewerActionMenu.addMenuListener(new MenuListener()
735 public void menuSelected(MenuEvent e)
737 handler.itemStateChanged(null);
741 public void menuDeselected(MenuEvent e)
746 public void menuCanceled(MenuEvent e)
755 * Sends commands to the structure viewer to superimpose structures based on
756 * currently associated alignments. May optionally return an error message for
760 protected String alignStructsWithAllAlignPanels()
762 if (getAlignmentPanel() == null)
767 if (_alignwith.size() == 0)
769 _alignwith.add(getAlignmentPanel());
775 AlignmentI[] als = new Alignment[_alignwith.size()];
776 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
777 int[] alm = new int[_alignwith.size()];
780 for (AlignmentViewPanel alignPanel : _alignwith)
782 als[a] = alignPanel.getAlignment();
784 alc[a++] = alignPanel.getAlignment().getHiddenColumns();
786 reply = getBinding().superposeStructures(als, alm, alc);
789 String text = MessageManager
790 .formatMessage("error.superposition_failed", reply);
791 statusBar.setText(text);
793 } catch (Exception e)
795 StringBuffer sp = new StringBuffer();
796 for (AlignmentViewPanel alignPanel : _alignwith)
798 sp.append("'" + alignPanel.getViewName() + "' ");
800 Cache.log.info("Couldn't align structures with the " + sp.toString()
801 + "associated alignment panels.", e);
807 public void background_actionPerformed()
809 Color col = JColorChooser.showDialog(this,
810 MessageManager.getString("label.select_background_colour"),
814 getBinding().setBackgroundColour(col);
819 public void viewerColour_actionPerformed()
821 if (viewerColour.isSelected())
823 // disable automatic sequence colouring.
824 getBinding().setColourBySequence(false);
829 public void chainColour_actionPerformed()
831 chainColour.setSelected(true);
832 getBinding().colourByChain();
836 public void chargeColour_actionPerformed()
838 chargeColour.setSelected(true);
839 getBinding().colourByCharge();
843 public void seqColour_actionPerformed()
845 AAStructureBindingModel binding = getBinding();
846 binding.setColourBySequence(seqColour.isSelected());
847 if (_colourwith == null)
849 _colourwith = new Vector<>();
851 if (binding.isColourBySequence())
853 if (!binding.isLoadingFromArchive())
855 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
857 // Make the currently displayed alignment panel the associated view
858 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
861 // Set the colour using the current view for the associated alignframe
862 for (AlignmentViewPanel alignPanel : _colourwith)
864 binding.colourBySequence(alignPanel);
866 seqColoursApplied = true;
871 public void pdbFile_actionPerformed()
873 JalviewFileChooser chooser = new JalviewFileChooser(
874 Cache.getProperty("LAST_DIRECTORY"));
876 chooser.setFileView(new JalviewFileView());
877 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
878 chooser.setToolTipText(MessageManager.getString("action.save"));
880 int value = chooser.showSaveDialog(this);
882 if (value == JalviewFileChooser.APPROVE_OPTION)
884 BufferedReader in = null;
887 // TODO: cope with multiple PDB files in view
888 in = new BufferedReader(
889 new FileReader(getBinding().getStructureFiles()[0]));
890 File outFile = chooser.getSelectedFile();
892 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
894 while ((data = in.readLine()) != null)
896 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
902 } catch (Exception ex)
904 ex.printStackTrace();
912 } catch (IOException e)
922 public void viewMapping_actionPerformed()
924 CutAndPasteTransfer cap = new CutAndPasteTransfer();
927 cap.appendText(getBinding().printMappings());
928 } catch (OutOfMemoryError e)
931 "composing sequence-structure alignments for display in text box.",
936 Desktop.addInternalFrame(cap,
937 MessageManager.getString("label.pdb_sequence_mapping"), 550,
941 protected abstract String getViewerName();
944 * Configures the title and menu items of the viewer panel.
947 public void updateTitleAndMenus()
949 AAStructureBindingModel binding = getBinding();
950 if (binding.hasFileLoadingError())
955 setChainMenuItems(binding.getChainNames());
957 this.setTitle(binding.getViewerTitle(getViewerName(), true));
960 * enable 'Superpose with' if more than one mapped structure
962 viewSelectionMenu.setEnabled(false);
963 if (getBinding().getStructureFiles().length > 1
964 && getBinding().getSequence().length > 1)
966 viewSelectionMenu.setEnabled(true);
970 * Show action menu if it has any enabled items
972 viewerActionMenu.setVisible(false);
973 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
975 if (viewerActionMenu.getItem(i).isEnabled())
977 viewerActionMenu.setVisible(true);
982 if (!binding.isLoadingFromArchive())
984 seqColour_actionPerformed();
989 public String toString()
995 public boolean hasMapping()
997 if (worker != null && (addingStructures || _started))
1001 if (getBinding() == null)
1003 if (_aps == null || _aps.size() == 0)
1005 // viewer has been closed, but we did at some point run.
1010 String[] pdbids = getBinding().getStructureFiles();
1016 for (String pdbid:pdbids) {
1017 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1018 if (sm!=null && sm.length>0 && sm[0]!=null) {
1022 // only return true if there is a mapping for every structure file we have loaded
1023 if (p == 0 || p != pdbids.length)
1027 // and that coloring has been applied
1028 return seqColoursApplied;
1032 public void raiseViewer()
1038 public long startProgressBar(String msg)
1040 // TODO would rather have startProgress/stopProgress as the
1041 // IProgressIndicator interface
1042 long tm = random.nextLong();
1043 if (progressBar != null)
1045 progressBar.setProgressBar(msg, tm);
1051 public void stopProgressBar(String msg, long handle)
1053 if (progressBar != null)
1055 progressBar.setProgressBar(msg, handle);
1059 protected IProgressIndicator getProgressIndicator()
1064 protected void setProgressIndicator(IProgressIndicator pi)
1069 protected void setProgressMessage(String message, long id)
1071 if (progressBar != null)
1073 progressBar.setProgressBar(message, id);
1078 public void showConsole(boolean show)
1080 // default does nothing
1084 * Show only the selected chain(s) in the viewer
1086 protected void showSelectedChains()
1088 List<String> toshow = new ArrayList<>();
1089 for (int i = 0; i < chainMenu.getItemCount(); i++)
1091 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
1093 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
1094 if (item.isSelected())
1096 toshow.add(item.getText());
1100 getBinding().showChains(toshow);