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);
563 abstract void showSelectedChains();
566 * Action on selecting one of Jalview's registered colour schemes
569 public void changeColour_actionPerformed(String colourSchemeName)
571 AlignmentI al = getAlignmentPanel().av.getAlignment();
572 ColourSchemeI cs = ColourSchemes.getInstance()
573 .getColourScheme(colourSchemeName, getAlignmentPanel().av, al,
575 getBinding().setJalviewColourScheme(cs);
579 * Builds the colour menu
581 protected void buildColourMenu()
583 colourMenu.removeAll();
584 AlignmentI al = getAlignmentPanel().av.getAlignment();
587 * add colour by sequence, by chain, by charge and cysteine
589 colourMenu.add(seqColour);
590 colourMenu.add(chainColour);
591 colourMenu.add(chargeColour);
592 chargeColour.setEnabled(!al.isNucleotide());
595 * add all 'simple' (per-residue) colour schemes registered to Jalview
597 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
601 * add 'colour by viewer' (menu item text is set in subclasses)
603 viewerColour.setSelected(false);
604 viewerColour.addActionListener(new ActionListener()
607 public void actionPerformed(ActionEvent actionEvent)
609 viewerColour_actionPerformed(actionEvent);
612 colourMenu.add(viewerColour);
615 * add 'set background colour'
617 JMenuItem backGround = new JMenuItem();
619 .setText(MessageManager.getString("action.background_colour"));
620 backGround.addActionListener(new ActionListener()
623 public void actionPerformed(ActionEvent actionEvent)
625 background_actionPerformed(actionEvent);
628 colourMenu.add(backGround);
631 * add colour buttons to a group so their selection is
632 * mutually exclusive (background colour is a separate option)
634 itemGroup.add(seqColour);
635 itemGroup.add(chainColour);
636 itemGroup.add(chargeColour);
637 itemGroup.add(viewerColour);
641 * Construct menu items
643 protected void initMenus()
645 AAStructureBindingModel binding = getBinding();
647 seqColour = new JRadioButtonMenuItem();
648 seqColour.setText(MessageManager.getString("action.by_sequence"));
649 seqColour.setName(ViewerColour.BySequence.name());
650 seqColour.setSelected(binding.isColourBySequence());
651 seqColour.addActionListener(new ActionListener()
654 public void actionPerformed(ActionEvent actionEvent)
656 seqColour_actionPerformed(actionEvent);
660 chainColour = new JRadioButtonMenuItem();
661 chainColour.setText(MessageManager.getString("action.by_chain"));
662 chainColour.setName(ViewerColour.ByChain.name());
663 chainColour.addActionListener(new ActionListener()
666 public void actionPerformed(ActionEvent actionEvent)
668 chainColour_actionPerformed(actionEvent);
672 chargeColour = new JRadioButtonMenuItem();
673 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
674 chargeColour.setName(ViewerColour.ChargeCysteine.name());
675 chargeColour.addActionListener(new ActionListener()
678 public void actionPerformed(ActionEvent actionEvent)
680 chargeColour_actionPerformed(actionEvent);
684 viewerColour = new JRadioButtonMenuItem();
685 // text is set in overrides of this method
686 viewerColour.setName(ViewerColour.ByViewer.name());
687 viewerColour.setSelected(!binding.isColourBySequence());
689 if (_colourwith == null)
691 _colourwith = new Vector<>();
693 if (_alignwith == null)
695 _alignwith = new Vector<>();
698 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
699 MessageManager.getString("label.colour_by"), this, _colourwith,
703 public void itemStateChanged(ItemEvent e)
705 if (!seqColour.isSelected())
711 // update the Chimera display now.
712 seqColour_actionPerformed(null);
716 viewMenu.add(seqColourBy);
718 final ItemListener handler = new ItemListener()
721 public void itemStateChanged(ItemEvent e)
723 alignStructs.setEnabled(!_alignwith.isEmpty());
724 alignStructs.setToolTipText(MessageManager.formatMessage(
725 "label.align_structures_using_linked_alignment_views",
729 viewSelectionMenu = new ViewSelectionMenu(
730 MessageManager.getString("label.superpose_with"), this,
731 _alignwith, handler);
732 handler.itemStateChanged(null);
733 viewerActionMenu.add(viewSelectionMenu, 0);
734 viewerActionMenu.addMenuListener(new MenuListener()
737 public void menuSelected(MenuEvent e)
739 handler.itemStateChanged(null);
743 public void menuDeselected(MenuEvent e)
748 public void menuCanceled(MenuEvent e)
757 public void setJalviewColourScheme(ColourSchemeI cs)
759 getBinding().setJalviewColourScheme(cs);
763 * Sends commands to the structure viewer to superimpose structures based on
764 * currently associated alignments. May optionally return an error message for
768 protected String alignStructs_actionPerformed(ActionEvent actionEvent)
770 return alignStructs_withAllAlignPanels();
773 protected String alignStructs_withAllAlignPanels()
775 if (getAlignmentPanel() == null)
780 if (_alignwith.size() == 0)
782 _alignwith.add(getAlignmentPanel());
788 AlignmentI[] als = new Alignment[_alignwith.size()];
789 HiddenColumns[] alc = new HiddenColumns[_alignwith.size()];
790 int[] alm = new int[_alignwith.size()];
793 for (AlignmentViewPanel alignPanel : _alignwith)
795 als[a] = alignPanel.getAlignment();
797 alc[a++] = alignPanel.getAlignment().getHiddenColumns();
799 reply = getBinding().superposeStructures(als, alm, alc);
802 String text = MessageManager
803 .formatMessage("error.superposition_failed", reply);
804 statusBar.setText(text);
806 } catch (Exception e)
808 StringBuffer sp = new StringBuffer();
809 for (AlignmentViewPanel alignPanel : _alignwith)
811 sp.append("'" + alignPanel.getViewName() + "' ");
813 Cache.log.info("Couldn't align structures with the " + sp.toString()
814 + "associated alignment panels.", e);
820 public void background_actionPerformed(ActionEvent actionEvent)
822 Color col = JColorChooser.showDialog(this,
823 MessageManager.getString("label.select_background_colour"),
827 getBinding().setBackgroundColour(col);
832 public void viewerColour_actionPerformed(ActionEvent actionEvent)
834 if (viewerColour.isSelected())
836 // disable automatic sequence colouring.
837 getBinding().setColourBySequence(false);
842 public void chainColour_actionPerformed(ActionEvent actionEvent)
844 chainColour.setSelected(true);
845 getBinding().colourByChain();
849 public void chargeColour_actionPerformed(ActionEvent actionEvent)
851 chargeColour.setSelected(true);
852 getBinding().colourByCharge();
856 public void seqColour_actionPerformed(ActionEvent actionEvent)
858 AAStructureBindingModel binding = getBinding();
859 binding.setColourBySequence(seqColour.isSelected());
860 if (_colourwith == null)
862 _colourwith = new Vector<>();
864 if (binding.isColourBySequence())
866 if (!binding.isLoadingFromArchive())
868 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
870 // Make the currently displayed alignment panel the associated view
871 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
874 // Set the colour using the current view for the associated alignframe
875 for (AlignmentViewPanel alignPanel : _colourwith)
877 binding.colourBySequence(alignPanel);
879 seqColoursApplied = true;
884 public void pdbFile_actionPerformed(ActionEvent actionEvent)
886 JalviewFileChooser chooser = new JalviewFileChooser(
887 Cache.getProperty("LAST_DIRECTORY"));
889 chooser.setFileView(new JalviewFileView());
890 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
891 chooser.setToolTipText(MessageManager.getString("action.save"));
893 int value = chooser.showSaveDialog(this);
895 if (value == JalviewFileChooser.APPROVE_OPTION)
897 BufferedReader in = null;
900 // TODO: cope with multiple PDB files in view
901 in = new BufferedReader(
902 new FileReader(getBinding().getStructureFiles()[0]));
903 File outFile = chooser.getSelectedFile();
905 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
907 while ((data = in.readLine()) != null)
909 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
915 } catch (Exception ex)
917 ex.printStackTrace();
925 } catch (IOException e)
935 public void viewMapping_actionPerformed(ActionEvent actionEvent)
937 CutAndPasteTransfer cap = new CutAndPasteTransfer();
940 cap.appendText(getBinding().printMappings());
941 } catch (OutOfMemoryError e)
944 "composing sequence-structure alignments for display in text box.",
949 Desktop.addInternalFrame(cap,
950 MessageManager.getString("label.pdb_sequence_mapping"), 550,
954 protected abstract String getViewerName();
957 * Configures the title and menu items of the viewer panel.
960 public void updateTitleAndMenus()
962 AAStructureBindingModel binding = getBinding();
963 if (binding.hasFileLoadingError())
968 setChainMenuItems(binding.getChainNames());
970 this.setTitle(binding.getViewerTitle(getViewerName(), true));
973 * enable 'Superpose with' if more than one mapped structure
975 viewSelectionMenu.setEnabled(false);
976 if (getBinding().getStructureFiles().length > 1
977 && getBinding().getSequence().length > 1)
979 viewSelectionMenu.setEnabled(true);
983 * Show action menu if it has any enabled items
985 viewerActionMenu.setVisible(false);
986 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
988 if (viewerActionMenu.getItem(i).isEnabled())
990 viewerActionMenu.setVisible(true);
995 if (!binding.isLoadingFromArchive())
997 seqColour_actionPerformed(null);
1002 public String toString()
1008 public boolean hasMapping()
1010 if (worker != null && (addingStructures || _started))
1014 if (getBinding() == null)
1016 if (_aps == null || _aps.size() == 0)
1018 // viewer has been closed, but we did at some point run.
1023 String[] pdbids = getBinding().getStructureFiles();
1029 for (String pdbid:pdbids) {
1030 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1031 if (sm!=null && sm.length>0 && sm[0]!=null) {
1035 // only return true if there is a mapping for every structure file we have loaded
1036 if (p == 0 || p != pdbids.length)
1040 // and that coloring has been applied
1041 return seqColoursApplied;
1045 public void raiseViewer()
1051 public long startProgressBar(String msg)
1053 // TODO would rather have startProgress/stopProgress as the
1054 // IProgressIndicator interface
1055 long tm = random.nextLong();
1056 if (progressBar != null)
1058 progressBar.setProgressBar(msg, tm);
1064 * End the progress bar with the specified handle, leaving a message (if not
1065 * null) on the status bar
1070 public void stopProgressBar(String msg, long handle)
1072 if (progressBar != null)
1074 progressBar.setProgressBar(msg, handle);
1079 public void stopProgressBar(Object object, long handle)
1083 protected IProgressIndicator getProgressIndicator()
1088 protected void setProgressIndicator(IProgressIndicator pi)
1093 protected void setProgressMessage(String message, long id)
1095 if (progressBar != null)
1097 progressBar.setProgressBar(message, id);
1102 public void showConsole(boolean show)
1104 // default does nothing