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.bin.Cache;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.HiddenColumns;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.StructureViewer.ViewerType;
30 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
31 import jalview.io.DataSourceType;
32 import jalview.io.JalviewFileChooser;
33 import jalview.io.JalviewFileView;
34 import jalview.jbgui.GStructureViewer;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.schemes.ColourSchemes;
37 import jalview.structure.StructureMapping;
38 import jalview.structures.models.AAStructureBindingModel;
39 import jalview.util.MessageManager;
41 import java.awt.Color;
42 import java.awt.Component;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.ItemEvent;
46 import java.awt.event.ItemListener;
47 import java.io.BufferedReader;
49 import java.io.FileOutputStream;
50 import java.io.FileReader;
51 import java.io.IOException;
52 import java.io.PrintWriter;
53 import java.util.ArrayList;
54 import java.util.List;
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<AlignmentPanel> _alignwith = new Vector<>();
95 * list of alignment panels that are used for colouring structures by aligned
98 protected Vector<AlignmentPanel> _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;
124 * Default constructor
126 public StructureViewerBase()
134 * @return true if this Jmol instance is linked with the given alignPanel
136 public boolean isLinkedWith(AlignmentPanel ap2)
138 return _aps.contains(ap2.av.getSequenceSetId());
141 public boolean isUsedforaligment(AlignmentPanel ap2)
144 return (_alignwith != null) && _alignwith.contains(ap2);
147 public boolean isUsedforcolourby(AlignmentPanel ap2)
149 return (_colourwith != null) && _colourwith.contains(ap2);
154 * @return TRUE if the view is NOT being coloured by the alignment colours.
156 public boolean isColouredByViewer()
158 return !getBinding().isColourBySequence();
161 public String getViewId()
165 viewId = System.currentTimeMillis() + "." + this.hashCode();
170 protected void setViewId(String viewId)
172 this.viewId = viewId;
175 public abstract String getStateInfo();
177 protected void buildActionMenu()
179 if (_alignwith == null)
181 _alignwith = new Vector<>();
183 if (_alignwith.size() == 0 && ap != null)
188 for (Component c : viewerActionMenu.getMenuComponents())
190 if (c != alignStructs)
192 viewerActionMenu.remove((JMenuItem) c);
197 public AlignmentPanel getAlignmentPanel()
202 protected void setAlignmentPanel(AlignmentPanel alp)
208 public AlignmentPanel[] getAllAlignmentPanels()
210 AlignmentPanel[] t, list = new AlignmentPanel[0];
211 for (String setid : _aps)
213 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
216 t = new AlignmentPanel[list.length + panels.length];
217 System.arraycopy(list, 0, t, 0, list.length);
218 System.arraycopy(panels, 0, t, list.length, panels.length);
227 * set the primary alignmentPanel reference and add another alignPanel to the
228 * list of ones to use for colouring and aligning
232 public void addAlignmentPanel(AlignmentPanel nap)
234 if (getAlignmentPanel() == null)
236 setAlignmentPanel(nap);
238 if (!_aps.contains(nap.av.getSequenceSetId()))
240 _aps.add(nap.av.getSequenceSetId());
245 * remove any references held to the given alignment panel
249 public void removeAlignmentPanel(AlignmentPanel nap)
253 _alignwith.remove(nap);
254 _colourwith.remove(nap);
255 if (getAlignmentPanel() == nap)
257 setAlignmentPanel(null);
258 for (AlignmentPanel aps : getAllAlignmentPanels())
262 setAlignmentPanel(aps);
267 } catch (Exception ex)
270 if (getAlignmentPanel() != null)
276 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
278 addAlignmentPanel(nap);
279 if (!_alignwith.contains(nap))
285 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
287 if (_alignwith.contains(nap))
289 _alignwith.remove(nap);
293 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
294 boolean enableColourBySeq)
296 useAlignmentPanelForColourbyseq(nap);
297 getBinding().setColourBySequence(enableColourBySeq);
298 seqColour.setSelected(enableColourBySeq);
299 viewerColour.setSelected(!enableColourBySeq);
302 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
304 addAlignmentPanel(nap);
305 if (!_colourwith.contains(nap))
307 _colourwith.add(nap);
311 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
313 if (_colourwith.contains(nap))
315 _colourwith.remove(nap);
319 public abstract ViewerType getViewerType();
321 protected abstract IProgressIndicator getIProgressIndicator();
324 * add a new structure (with associated sequences and chains) to this viewer,
325 * retrieving it if necessary first.
331 * if true, new structure(s) will be aligned using associated
335 protected void addStructure(final PDBEntry pdbentry,
336 final SequenceI[] seqs, final String[] chains,
337 final boolean align, final IProgressIndicator alignFrame)
339 if (pdbentry.getFile() == null)
341 if (worker != null && worker.isAlive())
343 // a retrieval is in progress, wait around and add ourselves to the
345 new Thread(new Runnable()
350 while (worker != null && worker.isAlive() && _started)
354 Thread.sleep(100 + ((int) Math.random() * 100));
356 } catch (Exception e)
360 // and call ourselves again.
361 addStructure(pdbentry, seqs, chains, align, alignFrame);
367 // otherwise, start adding the structure.
368 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
370 { seqs }, new String[][] { chains });
371 addingStructures = true;
373 alignAddedStructures = align;
374 worker = new Thread(this);
380 * Presents a dialog with the option to add an align a structure to an
381 * existing structure view
385 * @return YES, NO or CANCEL JvOptionPane code
387 protected int chooseAlignStructureToViewer(String pdbId,
388 StructureViewerBase view)
390 int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
391 MessageManager.formatMessage("label.add_pdbentry_to_view",
393 { pdbId, view.getTitle() }),
395 .getString("label.align_to_existing_structure_view"),
396 JvOptionPane.YES_NO_CANCEL_OPTION);
400 protected boolean hasPdbId(String pdbId)
402 return getBinding().hasPdbId(pdbId);
405 protected abstract List<StructureViewerBase> getViewersFor(
409 * Check for any existing views involving this alignment and give user the
410 * option to add and align this molecule to one of them
417 * @return true if user adds to a view, or cancels entirely, else false
419 protected boolean addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
420 String[] chains, final AlignmentPanel apanel, String pdbId)
422 for (StructureViewerBase view : getViewersFor(apanel))
424 // TODO: highlight the view somehow
426 * JAL-1742 exclude view with this structure already mapped (don't offer
427 * to align chain B to chain A of the same structure)
429 if (view.hasPdbId(pdbId))
433 int option = chooseAlignStructureToViewer(pdbId, view);
434 if (option == JvOptionPane.CANCEL_OPTION)
438 else if (option == JvOptionPane.YES_OPTION)
440 view.useAlignmentPanelForSuperposition(apanel);
441 view.addStructure(pdbentry, seq, chains, true, apanel.alignFrame);
446 // NO_OPTION - offer the next viewer if any
451 * nothing offered and selected
457 * Adds mappings for the given sequences to an already opened PDB structure,
458 * and updates any viewers that have the PDB file
465 protected void addSequenceMappingsToStructure(SequenceI[] seq,
466 String[] chains, final AlignmentPanel apanel, String pdbFilename)
468 // TODO : Fix multiple seq to one chain issue here.
470 * create the mappings
472 apanel.getStructureSelectionManager().setMapping(seq, chains,
473 pdbFilename, DataSourceType.FILE, getIProgressIndicator());
476 * alert the FeatureRenderer to show new (PDB RESNUM) features
478 if (apanel.getSeqPanel().seqCanvas.fr != null)
480 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
481 // note - we don't do a refresh for structure here because we do it
482 // explicitly for all panels later on
483 apanel.paintAlignment(true, false);
487 * add the sequences to any other viewers (of the same type) for this pdb
490 // JBPNOTE: this looks like a binding routine, rather than a gui routine
491 for (StructureViewerBase viewer : getViewersFor(null))
493 AAStructureBindingModel bindingModel = viewer.getBinding();
494 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
496 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
498 bindingModel.addSequence(pe, seq);
499 viewer.addAlignmentPanel(apanel);
501 * add it to the set of alignments used for colouring structure by
504 viewer.useAlignmentPanelForColourbyseq(apanel);
505 viewer.buildActionMenu();
506 apanel.getStructureSelectionManager()
507 .sequenceColoursChanged(apanel);
515 * Check if the PDB file is already loaded, if so offer to add it to the
522 * @return true if the user chooses to add to a viewer, or to cancel entirely
524 protected boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
525 final AlignmentPanel apanel, String pdbId)
527 boolean finished = false;
528 String alreadyMapped = apanel.getStructureSelectionManager()
529 .alreadyMappedToFile(pdbId);
531 if (alreadyMapped != null)
534 * the PDB file is already loaded
536 int option = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
537 MessageManager.formatMessage(
538 "label.pdb_entry_is_already_displayed", new Object[]
540 MessageManager.formatMessage(
541 "label.map_sequences_to_visible_window", new Object[]
543 JvOptionPane.YES_NO_CANCEL_OPTION);
544 if (option == JvOptionPane.CANCEL_OPTION)
548 else if (option == JvOptionPane.YES_OPTION)
550 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
557 void setChainMenuItems(List<String> chainNames)
559 chainMenu.removeAll();
560 if (chainNames == null || chainNames.isEmpty())
564 JMenuItem menuItem = new JMenuItem(
565 MessageManager.getString("label.all"));
566 menuItem.addActionListener(new ActionListener()
569 public void actionPerformed(ActionEvent evt)
571 allChainsSelected = true;
572 for (int i = 0; i < chainMenu.getItemCount(); i++)
574 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
576 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
579 showSelectedChains();
580 allChainsSelected = false;
584 chainMenu.add(menuItem);
586 for (String chain : chainNames)
588 menuItem = new JCheckBoxMenuItem(chain, true);
589 menuItem.addItemListener(new ItemListener()
592 public void itemStateChanged(ItemEvent evt)
594 if (!allChainsSelected)
596 showSelectedChains();
601 chainMenu.add(menuItem);
605 abstract void showSelectedChains();
608 * Action on selecting one of Jalview's registered colour schemes
611 public void changeColour_actionPerformed(String colourSchemeName)
613 AlignmentI al = getAlignmentPanel().av.getAlignment();
614 ColourSchemeI cs = ColourSchemes.getInstance()
615 .getColourScheme(colourSchemeName, al, null);
616 getBinding().setJalviewColourScheme(cs);
620 * Builds the colour menu
622 protected void buildColourMenu()
624 colourMenu.removeAll();
625 AlignmentI al = getAlignmentPanel().av.getAlignment();
628 * add colour by sequence, by chain, by charge and cysteine
630 colourMenu.add(seqColour);
631 colourMenu.add(chainColour);
632 colourMenu.add(chargeColour);
633 chargeColour.setEnabled(!al.isNucleotide());
636 * add all 'simple' (per-residue) colour schemes registered to Jalview
638 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
642 * add 'colour by viewer' (menu item text is set in subclasses)
644 viewerColour.setSelected(false);
645 viewerColour.addActionListener(new ActionListener()
648 public void actionPerformed(ActionEvent actionEvent)
650 viewerColour_actionPerformed(actionEvent);
653 colourMenu.add(viewerColour);
656 * add 'set background colour'
658 JMenuItem backGround = new JMenuItem();
660 .setText(MessageManager.getString("action.background_colour"));
661 backGround.addActionListener(new ActionListener()
664 public void actionPerformed(ActionEvent actionEvent)
666 background_actionPerformed(actionEvent);
669 colourMenu.add(backGround);
672 * add colour buttons to a group so their selection is
673 * mutually exclusive (background colour is a separate option)
675 itemGroup.add(seqColour);
676 itemGroup.add(chainColour);
677 itemGroup.add(chargeColour);
678 itemGroup.add(viewerColour);
682 * Construct menu items
684 protected void initMenus()
686 AAStructureBindingModel binding = getBinding();
688 seqColour = new JRadioButtonMenuItem();
689 seqColour.setText(MessageManager.getString("action.by_sequence"));
690 seqColour.setName(ViewerColour.BySequence.name());
691 seqColour.setSelected(binding.isColourBySequence());
692 seqColour.addActionListener(new ActionListener()
695 public void actionPerformed(ActionEvent actionEvent)
697 seqColour_actionPerformed(actionEvent);
701 chainColour = new JRadioButtonMenuItem();
702 chainColour.setText(MessageManager.getString("action.by_chain"));
703 chainColour.setName(ViewerColour.ByChain.name());
704 chainColour.addActionListener(new ActionListener()
707 public void actionPerformed(ActionEvent actionEvent)
709 chainColour_actionPerformed(actionEvent);
713 chargeColour = new JRadioButtonMenuItem();
714 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
715 chargeColour.setName(ViewerColour.ChargeCysteine.name());
716 chargeColour.addActionListener(new ActionListener()
719 public void actionPerformed(ActionEvent actionEvent)
721 chargeColour_actionPerformed(actionEvent);
725 viewerColour = new JRadioButtonMenuItem();
726 // text is set in overrides of this method
727 viewerColour.setName(ViewerColour.ByViewer.name());
728 viewerColour.setSelected(!binding.isColourBySequence());
730 if (_colourwith == null)
732 _colourwith = new Vector<>();
734 if (_alignwith == null)
736 _alignwith = new Vector<>();
739 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
740 MessageManager.getString("label.colour_by"), this, _colourwith,
744 public void itemStateChanged(ItemEvent e)
746 if (!seqColour.isSelected())
752 // update the Chimera display now.
753 seqColour_actionPerformed(null);
757 viewMenu.add(seqColourBy);
759 final ItemListener handler = new ItemListener()
762 public void itemStateChanged(ItemEvent e)
764 alignStructs.setEnabled(!_alignwith.isEmpty());
765 alignStructs.setToolTipText(MessageManager.formatMessage(
766 "label.align_structures_using_linked_alignment_views",
770 viewSelectionMenu = new ViewSelectionMenu(
771 MessageManager.getString("label.superpose_with"), this,
772 _alignwith, handler);
773 handler.itemStateChanged(null);
774 viewerActionMenu.add(viewSelectionMenu, 0);
775 viewerActionMenu.addMenuListener(new MenuListener()
778 public void menuSelected(MenuEvent e)
780 handler.itemStateChanged(null);
784 public void menuDeselected(MenuEvent e)
789 public void menuCanceled(MenuEvent e)
798 public void setJalviewColourScheme(ColourSchemeI cs)
800 getBinding().setJalviewColourScheme(cs);
804 * Sends commands to the structure viewer to superimpose structures based on
805 * currently associated alignments. May optionally return an error message for
809 protected String alignStructs_actionPerformed(ActionEvent actionEvent)
811 return alignStructs_withAllAlignPanels();
814 protected String alignStructs_withAllAlignPanels()
816 if (getAlignmentPanel() == null)
821 if (_alignwith.size() == 0)
823 _alignwith.add(getAlignmentPanel());
829 AlignmentI[] als = new Alignment[_alignwith.size()];
830 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
831 int[] alm = new int[_alignwith.size()];
834 for (AlignmentPanel ap : _alignwith)
836 als[a] = ap.av.getAlignment();
838 alc[a++] = ap.av.getAlignment().getHiddenColumns();
840 reply = getBinding().superposeStructures(als, alm, alc);
843 String text = MessageManager
844 .formatMessage("error.superposition_failed", reply);
845 statusBar.setText(text);
847 } catch (Exception e)
849 StringBuffer sp = new StringBuffer();
850 for (AlignmentPanel ap : _alignwith)
852 sp.append("'" + ap.alignFrame.getTitle() + "' ");
854 Cache.log.info("Couldn't align structures with the " + sp.toString()
855 + "associated alignment panels.", e);
861 public void background_actionPerformed(ActionEvent actionEvent)
863 Color col = JColorChooser.showDialog(this,
864 MessageManager.getString("label.select_background_colour"),
868 getBinding().setBackgroundColour(col);
873 public void viewerColour_actionPerformed(ActionEvent actionEvent)
875 if (viewerColour.isSelected())
877 // disable automatic sequence colouring.
878 getBinding().setColourBySequence(false);
883 public void chainColour_actionPerformed(ActionEvent actionEvent)
885 chainColour.setSelected(true);
886 getBinding().colourByChain();
890 public void chargeColour_actionPerformed(ActionEvent actionEvent)
892 chargeColour.setSelected(true);
893 getBinding().colourByCharge();
897 public void seqColour_actionPerformed(ActionEvent actionEvent)
899 AAStructureBindingModel binding = getBinding();
900 binding.setColourBySequence(seqColour.isSelected());
901 if (_colourwith == null)
903 _colourwith = new Vector<>();
905 if (binding.isColourBySequence())
907 if (!binding.isLoadingFromArchive())
909 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
911 // Make the currently displayed alignment panel the associated view
912 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
915 // Set the colour using the current view for the associated alignframe
916 for (AlignmentPanel ap : _colourwith)
918 binding.colourBySequence(ap);
920 seqColoursApplied = true;
925 public void pdbFile_actionPerformed(ActionEvent actionEvent)
927 JalviewFileChooser chooser = new JalviewFileChooser(
928 Cache.getProperty("LAST_DIRECTORY"));
930 chooser.setFileView(new JalviewFileView());
931 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
932 chooser.setToolTipText(MessageManager.getString("action.save"));
934 int value = chooser.showSaveDialog(this);
936 if (value == JalviewFileChooser.APPROVE_OPTION)
938 BufferedReader in = null;
941 // TODO: cope with multiple PDB files in view
942 in = new BufferedReader(
943 new FileReader(getBinding().getStructureFiles()[0]));
944 File outFile = chooser.getSelectedFile();
946 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
948 while ((data = in.readLine()) != null)
950 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
956 } catch (Exception ex)
958 ex.printStackTrace();
966 } catch (IOException e)
976 public void viewMapping_actionPerformed(ActionEvent actionEvent)
978 CutAndPasteTransfer cap = new CutAndPasteTransfer();
981 cap.appendText(getBinding().printMappings());
982 } catch (OutOfMemoryError e)
985 "composing sequence-structure alignments for display in text box.",
990 Desktop.addInternalFrame(cap,
991 MessageManager.getString("label.pdb_sequence_mapping"), 550,
995 protected abstract String getViewerName();
998 * Configures the title and menu items of the viewer panel.
1000 public void updateTitleAndMenus()
1002 AAStructureBindingModel binding = getBinding();
1003 if (binding.hasFileLoadingError())
1008 setChainMenuItems(binding.getChainNames());
1010 this.setTitle(binding.getViewerTitle(getViewerName(), true));
1013 * enable 'Superpose with' if more than one mapped structure
1015 viewSelectionMenu.setEnabled(false);
1016 if (getBinding().getStructureFiles().length > 1
1017 && getBinding().getSequence().length > 1)
1019 viewSelectionMenu.setEnabled(true);
1023 * Show action menu if it has any enabled items
1025 viewerActionMenu.setVisible(false);
1026 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
1028 if (viewerActionMenu.getItem(i).isEnabled())
1030 viewerActionMenu.setVisible(true);
1035 if (!binding.isLoadingFromArchive())
1037 seqColour_actionPerformed(null);
1042 public boolean hasMapping()
1044 if (worker != null && (addingStructures || _started))
1048 if (getBinding() == null)
1050 if (_aps == null || _aps.size() == 0)
1052 // viewer has been closed, but we did at some point run.
1057 String[] pdbids = getBinding().getStructureFiles();
1063 for (String pdbid:pdbids) {
1064 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1065 if (sm!=null && sm.length>0 && sm[0]!=null) {
1069 // only return true if there is a mapping for every structure file we have loaded
1070 if (p == 0 || p != pdbids.length)
1074 // and that coloring has been applied
1075 return seqColoursApplied;