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 java.awt.Color;
24 import java.awt.Component;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.awt.event.ItemEvent;
28 import java.awt.event.ItemListener;
29 import java.beans.PropertyVetoException;
30 import java.io.BufferedReader;
32 import java.io.FileOutputStream;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.util.ArrayList;
37 import java.util.List;
39 import java.util.Random;
40 import java.util.Vector;
42 import javax.swing.ButtonGroup;
43 import javax.swing.JCheckBoxMenuItem;
44 import javax.swing.JMenu;
45 import javax.swing.JMenuItem;
46 import javax.swing.JRadioButtonMenuItem;
47 import javax.swing.event.MenuEvent;
48 import javax.swing.event.MenuListener;
50 import jalview.api.AlignmentViewPanel;
51 import jalview.api.structures.JalviewStructureDisplayI;
52 import jalview.bin.Cache;
53 import jalview.bin.Console;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.PDBEntry;
56 import jalview.datamodel.SequenceI;
57 import jalview.gui.JalviewColourChooser.ColourChooserListener;
58 import jalview.gui.StructureViewer.ViewerType;
59 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
60 import jalview.io.DataSourceType;
61 import jalview.io.JalviewFileChooser;
62 import jalview.io.JalviewFileView;
63 import jalview.jbgui.GStructureViewer;
64 import jalview.schemes.ColourSchemeI;
65 import jalview.schemes.ColourSchemes;
66 import jalview.structure.StructureMapping;
67 import jalview.structures.models.AAStructureBindingModel;
68 import jalview.util.BrowserLauncher;
69 import jalview.util.MessageManager;
70 import jalview.ws.dbsources.EBIAlfaFold;
71 import jalview.ws.dbsources.Pdb;
72 import jalview.ws.utils.UrlDownloadClient;
75 * Base class with common functionality for JMol, Chimera or other structure
81 public abstract class StructureViewerBase extends GStructureViewer
82 implements Runnable, ViewSetProvider
85 * names for colour options (additional to Jalview colour schemes)
89 BySequence, ByChain, ChargeCysteine, ByViewer
93 * Singleton list of all (open) instances of structureViewerBase TODO:
94 * JAL-3362 - review and adopt the swingJS-safe singleton pattern so each
95 * structure viewer base instance is kept to its own JalviewJS parent
97 private static List<JalviewStructureDisplayI> svbs = new ArrayList<>();
101 * @return list with all existing StructureViewers instance
103 public static List<JalviewStructureDisplayI> getAllStructureViewerBases()
105 List<JalviewStructureDisplayI> goodSvbs = new ArrayList<>();
106 for (JalviewStructureDisplayI s : svbs)
108 if (s != null && !goodSvbs.contains(s))
117 * list of sequenceSet ids associated with the view
119 protected List<String> _aps = new ArrayList<>();
122 * list of alignment panels to use for superposition
124 protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
127 * list of alignment panels that are used for colouring structures by aligned
130 protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
132 private String viewId = null;
134 private AlignmentPanel ap;
136 protected boolean alignAddedStructures = false;
138 protected volatile boolean _started = false;
140 protected volatile boolean addingStructures = false;
142 protected Thread worker = null;
144 protected boolean allChainsSelected = false;
146 protected boolean allHetatmBeingSelected = false;
148 protected JMenu viewSelectionMenu;
151 * set after sequence colouring has been applied for this structure viewer.
152 * used to determine if the final sequence/structure mapping has been
155 protected volatile boolean seqColoursApplied = false;
157 private IProgressIndicator progressBar = null;
159 private Random random = new Random();
162 * Default constructor
164 public StructureViewerBase()
172 * @return true if added structures should be aligned to existing one(s)
175 public boolean isAlignAddedStructures()
177 return alignAddedStructures;
183 * if added structures should be aligned to existing one(s)
186 public void setAlignAddedStructures(boolean alignAdded)
188 alignAddedStructures = alignAdded;
192 * called by the binding model to indicate when adding structures is happening
193 * or has been completed
195 * @param addingStructures
197 public synchronized void setAddingStructures(boolean addingStructures)
199 this.addingStructures = addingStructures;
205 * @return true if this Jmol instance is linked with the given alignPanel
207 public boolean isLinkedWith(AlignmentPanel ap2)
209 return _aps.contains(ap2.av.getSequenceSetId());
213 public boolean isUsedforaligment(AlignmentViewPanel ap2)
216 return (_alignwith != null) && _alignwith.contains(ap2);
220 public boolean isUsedForColourBy(AlignmentViewPanel ap2)
222 return (_colourwith != null) && _colourwith.contains(ap2);
227 * @return TRUE if the view is NOT being coloured by the alignment colours.
229 public boolean isColouredByViewer()
231 return !getBinding().isColourBySequence();
234 public String getViewId()
238 viewId = System.currentTimeMillis() + "." + this.hashCode();
243 protected void setViewId(String viewId)
245 this.viewId = viewId;
248 protected void buildActionMenu()
250 if (_alignwith == null)
252 _alignwith = new Vector<>();
254 if (_alignwith.size() == 0 && ap != null)
259 // TODO: refactor to allow concrete classes to register buttons for adding
261 // currently have to override to add buttons back in after they are cleared
263 for (Component c : viewerActionMenu.getMenuComponents())
265 if (c != alignStructs)
267 viewerActionMenu.remove((JMenuItem) c);
273 public AlignmentPanel getAlignmentPanel()
278 protected void setAlignmentPanel(AlignmentPanel alp)
284 public AlignmentPanel[] getAllAlignmentPanels()
286 AlignmentPanel[] t, list = new AlignmentPanel[0];
287 for (String setid : _aps)
289 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
292 t = new AlignmentPanel[list.length + panels.length];
293 System.arraycopy(list, 0, t, 0, list.length);
294 System.arraycopy(panels, 0, t, list.length, panels.length);
303 * set the primary alignmentPanel reference and add another alignPanel to the
304 * list of ones to use for colouring and aligning
308 public void addAlignmentPanel(AlignmentPanel nap)
310 if (getAlignmentPanel() == null)
312 setAlignmentPanel(nap);
314 if (!_aps.contains(nap.av.getSequenceSetId()))
316 _aps.add(nap.av.getSequenceSetId());
321 * remove any references held to the given alignment panel
326 public void removeAlignmentPanel(AlignmentViewPanel nap)
330 _alignwith.remove(nap);
331 _colourwith.remove(nap);
332 if (getAlignmentPanel() == nap)
334 setAlignmentPanel(null);
335 for (AlignmentPanel aps : getAllAlignmentPanels())
339 setAlignmentPanel(aps);
344 } catch (Exception ex)
347 if (getAlignmentPanel() != null)
353 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
355 addAlignmentPanel(nap);
356 if (!_alignwith.contains(nap))
362 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
364 if (_alignwith.contains(nap))
366 _alignwith.remove(nap);
370 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
371 boolean enableColourBySeq)
373 useAlignmentPanelForColourbyseq(nap);
374 getBinding().setColourBySequence(enableColourBySeq);
375 seqColour.setSelected(enableColourBySeq);
376 viewerColour.setSelected(!enableColourBySeq);
379 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
381 addAlignmentPanel(nap);
382 if (!_colourwith.contains(nap))
384 _colourwith.add(nap);
388 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
390 if (_colourwith.contains(nap))
392 _colourwith.remove(nap);
396 public abstract ViewerType getViewerType();
399 * add a new structure (with associated sequences and chains) to this viewer,
400 * retrieving it if necessary first.
406 * if true, new structure(s) will be aligned using associated
410 protected void addStructure(final PDBEntry pdbentry,
411 final SequenceI[] seqs, final String[] chains,
412 final IProgressIndicator alignFrame)
414 if (pdbentry.getFile() == null)
416 if (worker != null && worker.isAlive())
418 // a retrieval is in progress, wait around and add ourselves to the
420 new Thread(new Runnable()
425 while (worker != null && worker.isAlive() && _started)
429 Thread.sleep(100 + ((int) Math.random() * 100));
431 } catch (Exception e)
435 // and call ourselves again.
436 addStructure(pdbentry, seqs, chains, alignFrame);
442 // otherwise, start adding the structure.
443 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
445 { seqs }, new String[][] { chains });
446 addingStructures = true;
448 worker = new Thread(this);
453 protected boolean hasPdbId(String pdbId)
455 return getBinding().hasPdbId(pdbId);
459 * Returns a list of any viewer of the instantiated type. The list is
460 * restricted to those linked to the given alignment panel if it is not null.
462 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
464 return Desktop.instance.getStructureViewers(alp, this.getClass());
468 public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
469 String[] chains, final AlignmentViewPanel apanel, String pdbId)
472 * JAL-1742 exclude view with this structure already mapped (don't offer
473 * to align chain B to chain A of the same structure); code may defend
474 * against this possibility before we reach here
480 AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error
483 useAlignmentPanelForSuperposition(alignPanel);
484 addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
488 * Adds mappings for the given sequences to an already opened PDB structure,
489 * and updates any viewers that have the PDB file
496 public void addSequenceMappingsToStructure(SequenceI[] seq,
497 String[] chains, final AlignmentViewPanel alpanel,
500 AlignmentPanel apanel = (AlignmentPanel) alpanel;
502 // TODO : Fix multiple seq to one chain issue here.
504 * create the mappings
506 apanel.getStructureSelectionManager().setMapping(seq, chains,
507 pdbFilename, DataSourceType.FILE, getProgressIndicator());
510 * alert the FeatureRenderer to show new (PDB RESNUM) features
512 if (apanel.getSeqPanel().seqCanvas.fr != null)
514 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
515 // note - we don't do a refresh for structure here because we do it
516 // explicitly for all panels later on
517 apanel.paintAlignment(true, false);
521 * add the sequences to any other viewers (of the same type) for this pdb
524 // JBPNOTE: this looks like a binding routine, rather than a gui routine
525 for (StructureViewerBase viewer : getViewersFor(null))
527 AAStructureBindingModel bindingModel = viewer.getBinding();
528 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
530 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
532 bindingModel.addSequence(pe, seq);
533 viewer.addAlignmentPanel(apanel);
535 * add it to the set of alignments used for colouring structure by
538 viewer.useAlignmentPanelForColourbyseq(apanel);
539 viewer.buildActionMenu();
540 apanel.getStructureSelectionManager()
541 .sequenceColoursChanged(apanel);
549 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
550 final AlignmentViewPanel apanel, String pdbId)
552 String alreadyMapped = apanel.getStructureSelectionManager()
553 .alreadyMappedToFile(pdbId);
555 if (alreadyMapped == null)
560 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
564 void setChainMenuItems(List<String> chainNames)
566 chainMenu.removeAll();
567 if (chainNames == null || chainNames.isEmpty())
571 JMenuItem menuItem = new JMenuItem(
572 MessageManager.getString("label.all"));
573 menuItem.addActionListener(new ActionListener()
576 public void actionPerformed(ActionEvent evt)
578 allChainsSelected = true;
579 for (int i = 0; i < chainMenu.getItemCount(); i++)
581 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
583 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
586 showSelectedChains();
587 allChainsSelected = false;
591 chainMenu.add(menuItem);
593 for (String chain : chainNames)
595 menuItem = new JCheckBoxMenuItem(chain, true);
596 menuItem.addItemListener(new ItemListener()
599 public void itemStateChanged(ItemEvent evt)
601 if (!allChainsSelected)
603 showSelectedChains();
608 chainMenu.add(menuItem);
612 void setHetatmMenuItems(Map<String, String> hetatmNames)
614 hetatmMenu.removeAll();
615 if (hetatmNames == null || hetatmNames.isEmpty())
617 hetatmMenu.setVisible(false);
620 hetatmMenu.setVisible(true);
621 allHetatmBeingSelected = false;
622 JMenuItem allMenuItem = new JMenuItem(
623 MessageManager.getString("label.all"));
624 JMenuItem noneMenuItem = new JMenuItem(
625 MessageManager.getString("label.none"));
626 allMenuItem.addActionListener(new ActionListener()
629 public void actionPerformed(ActionEvent e)
632 allHetatmBeingSelected = true;
633 // Toggle state of everything - on
634 for (int i = 0; i < hetatmMenu.getItemCount(); i++)
636 if (hetatmMenu.getItem(i) instanceof JCheckBoxMenuItem)
638 ((JCheckBoxMenuItem) hetatmMenu.getItem(i)).setSelected(true);
641 allHetatmBeingSelected = false;
642 showSelectedHetatms();
647 noneMenuItem.addActionListener(new ActionListener()
650 public void actionPerformed(ActionEvent e)
653 allHetatmBeingSelected = true;
654 // Toggle state of everything off
655 for (int i = 0; i < hetatmMenu.getItemCount(); i++)
657 if (hetatmMenu.getItem(i) instanceof JCheckBoxMenuItem)
659 ((JCheckBoxMenuItem) hetatmMenu.getItem(i))
663 allHetatmBeingSelected = false;
664 showSelectedHetatms();
668 hetatmMenu.add(noneMenuItem);
669 hetatmMenu.add(allMenuItem);
671 for (Map.Entry<String, String> chain : hetatmNames.entrySet())
673 JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(chain.getKey(),
675 menuItem.setToolTipText(chain.getValue());
676 menuItem.addItemListener(new ItemListener()
679 public void itemStateChanged(ItemEvent evt)
681 if (!allHetatmBeingSelected)
683 // update viewer only when we were clicked, not programmatically
685 showSelectedHetatms();
690 hetatmMenu.add(menuItem);
695 * Action on selecting one of Jalview's registered colour schemes
698 public void changeColour_actionPerformed(String colourSchemeName)
700 AlignmentI al = getAlignmentPanel().av.getAlignment();
701 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(
702 colourSchemeName, getAlignmentPanel().av, al, null);
703 getBinding().colourByJalviewColourScheme(cs);
707 * Builds the colour menu
709 protected void buildColourMenu()
711 colourMenu.removeAll();
712 AlignmentI al = getAlignmentPanel().av.getAlignment();
715 * add colour by sequence, by chain, by charge and cysteine
717 colourMenu.add(seqColour);
718 colourMenu.add(chainColour);
719 colourMenu.add(chargeColour);
720 chargeColour.setEnabled(!al.isNucleotide());
723 * add all 'simple' (per-residue) colour schemes registered to Jalview
725 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
729 * add 'colour by viewer' (menu item text is set in subclasses)
731 viewerColour.setSelected(false);
732 viewerColour.addActionListener(new ActionListener()
735 public void actionPerformed(ActionEvent actionEvent)
737 viewerColour_actionPerformed();
740 colourMenu.add(viewerColour);
743 * add 'set background colour'
745 JMenuItem backGround = new JMenuItem();
747 .setText(MessageManager.getString("action.background_colour"));
748 backGround.addActionListener(new ActionListener()
751 public void actionPerformed(ActionEvent actionEvent)
753 background_actionPerformed();
756 colourMenu.add(backGround);
759 * add colour buttons to a group so their selection is
760 * mutually exclusive (background colour is a separate option)
762 itemGroup.add(seqColour);
763 itemGroup.add(chainColour);
764 itemGroup.add(chargeColour);
765 itemGroup.add(viewerColour);
769 * Construct menu items
771 protected void initMenus()
773 AAStructureBindingModel binding = getBinding();
775 seqColour = new JRadioButtonMenuItem();
776 seqColour.setText(MessageManager.getString("action.by_sequence"));
777 seqColour.setName(ViewerColour.BySequence.name());
778 seqColour.setSelected(binding.isColourBySequence());
779 seqColour.addActionListener(new ActionListener()
782 public void actionPerformed(ActionEvent actionEvent)
784 seqColour_actionPerformed();
788 chainColour = new JRadioButtonMenuItem();
789 chainColour.setText(MessageManager.getString("action.by_chain"));
790 chainColour.setName(ViewerColour.ByChain.name());
791 chainColour.addActionListener(new ActionListener()
794 public void actionPerformed(ActionEvent actionEvent)
796 chainColour_actionPerformed();
800 chargeColour = new JRadioButtonMenuItem();
801 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
802 chargeColour.setName(ViewerColour.ChargeCysteine.name());
803 chargeColour.addActionListener(new ActionListener()
806 public void actionPerformed(ActionEvent actionEvent)
808 chargeColour_actionPerformed();
812 viewerColour = new JRadioButtonMenuItem();
814 .setText(MessageManager.getString("label.colour_with_viewer"));
815 viewerColour.setToolTipText(MessageManager
816 .getString("label.let_viewer_manage_structure_colours"));
817 viewerColour.setName(ViewerColour.ByViewer.name());
818 viewerColour.setSelected(!binding.isColourBySequence());
820 if (_colourwith == null)
822 _colourwith = new Vector<>();
824 if (_alignwith == null)
826 _alignwith = new Vector<>();
829 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
830 MessageManager.getString("label.colour_by"), this, _colourwith,
834 public void itemStateChanged(ItemEvent e)
836 if (!seqColour.isSelected())
842 // update the viewer display now.
843 seqColour_actionPerformed();
847 viewMenu.add(seqColourBy);
849 final ItemListener handler = new ItemListener()
852 public void itemStateChanged(ItemEvent e)
854 if (_alignwith.isEmpty())
856 alignStructs.setEnabled(false);
857 alignStructs.setToolTipText(null);
861 alignStructs.setEnabled(true);
862 alignStructs.setToolTipText(MessageManager.formatMessage(
863 "label.align_structures_using_linked_alignment_views",
868 viewSelectionMenu = new ViewSelectionMenu(
869 MessageManager.getString("label.superpose_with"), this,
870 _alignwith, handler);
871 handler.itemStateChanged(null);
872 viewerActionMenu.add(viewSelectionMenu, 0);
873 viewerActionMenu.addMenuListener(new MenuListener()
876 public void menuSelected(MenuEvent e)
878 handler.itemStateChanged(null);
882 public void menuDeselected(MenuEvent e)
887 public void menuCanceled(MenuEvent e)
892 viewerActionMenu.setText(getViewerName());
893 helpItem.setText(MessageManager.formatMessage("label.viewer_help",
900 * Sends commands to the structure viewer to superimpose structures based on
901 * currently associated alignments. May optionally return an error message for
905 protected String alignStructsWithAllAlignPanels()
907 if (getAlignmentPanel() == null)
912 if (_alignwith.size() == 0)
914 _alignwith.add(getAlignmentPanel());
920 reply = getBinding().superposeStructures(_alignwith);
921 if (reply != null && !reply.isEmpty())
923 String text = MessageManager
924 .formatMessage("error.superposition_failed", reply);
925 statusBar.setText(text);
927 } catch (Exception e)
929 StringBuffer sp = new StringBuffer();
930 for (AlignmentViewPanel alignPanel : _alignwith)
932 sp.append("'" + alignPanel.getViewName() + "' ");
934 Console.info("Couldn't align structures with the " + sp.toString()
935 + "associated alignment panels.", e);
941 * Opens a colour chooser dialog, and applies the chosen colour to the
942 * background of the structure viewer
945 public void background_actionPerformed()
947 String ttl = MessageManager.getString("label.select_background_colour");
948 ColourChooserListener listener = new ColourChooserListener()
951 public void colourSelected(Color c)
953 getBinding().setBackgroundColour(c);
956 JalviewColourChooser.showColourChooser(this, ttl, null, listener);
960 public void viewerColour_actionPerformed()
962 if (viewerColour.isSelected())
964 // disable automatic sequence colouring.
965 getBinding().setColourBySequence(false);
970 public void chainColour_actionPerformed()
972 chainColour.setSelected(true);
973 getBinding().colourByChain();
977 public void chargeColour_actionPerformed()
979 chargeColour.setSelected(true);
980 getBinding().colourByCharge();
984 public void seqColour_actionPerformed()
986 AAStructureBindingModel binding = getBinding();
987 binding.setColourBySequence(seqColour.isSelected());
988 if (_colourwith == null)
990 _colourwith = new Vector<>();
992 if (binding.isColourBySequence())
994 if (!binding.isLoadingFromArchive())
996 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
998 // Make the currently displayed alignment panel the associated view
999 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
1002 // Set the colour using the current view for the associated alignframe
1003 for (AlignmentViewPanel alignPanel : _colourwith)
1005 binding.colourBySequence(alignPanel);
1007 seqColoursApplied = true;
1012 public void pdbFile_actionPerformed()
1014 // TODO: JAL-3048 not needed for Jalview-JS - save PDB file
1015 JalviewFileChooser chooser = new JalviewFileChooser(
1016 Cache.getProperty("LAST_DIRECTORY"));
1018 chooser.setFileView(new JalviewFileView());
1019 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
1020 chooser.setToolTipText(MessageManager.getString("action.save"));
1022 int value = chooser.showSaveDialog(this);
1024 if (value == JalviewFileChooser.APPROVE_OPTION)
1026 BufferedReader in = null;
1029 // TODO: cope with multiple PDB files in view
1030 in = new BufferedReader(
1031 new FileReader(getBinding().getStructureFiles()[0]));
1032 File outFile = chooser.getSelectedFile();
1034 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
1036 while ((data = in.readLine()) != null)
1038 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
1044 } catch (Exception ex)
1046 ex.printStackTrace();
1054 } catch (IOException e)
1064 public void viewMapping_actionPerformed()
1066 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1069 cap.appendText(getBinding().printMappings());
1070 } catch (OutOfMemoryError e)
1073 "composing sequence-structure alignments for display in text box.",
1078 Desktop.addInternalFrame(cap,
1079 MessageManager.getString("label.pdb_sequence_mapping"), 550,
1083 protected abstract String getViewerName();
1086 * Configures the title and menu items of the viewer panel.
1089 public void updateTitleAndMenus()
1091 AAStructureBindingModel binding = getBinding();
1092 if (binding.hasFileLoadingError())
1097 setChainMenuItems(binding.getChainNames());
1098 setHetatmMenuItems(binding.getHetatmNames());
1100 this.setTitle(binding.getViewerTitle(getViewerName(), true));
1103 * enable 'Superpose with' if more than one mapped structure
1105 viewSelectionMenu.setEnabled(false);
1106 if (getBinding().getMappedStructureCount() > 1
1107 && getBinding().getSequence().length > 1)
1109 viewSelectionMenu.setEnabled(true);
1113 * Show action menu if it has any enabled items
1115 viewerActionMenu.setVisible(false);
1116 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
1118 if (viewerActionMenu.getItem(i).isEnabled())
1120 viewerActionMenu.setVisible(true);
1125 if (!binding.isLoadingFromArchive())
1127 seqColour_actionPerformed();
1132 public String toString()
1138 public boolean hasMapping()
1140 if (worker != null && (addingStructures || _started))
1144 if (getBinding() == null)
1146 if (_aps == null || _aps.size() == 0)
1148 // viewer has been closed, but we did at some point run.
1153 String[] pdbids = getBinding().getStructureFiles();
1159 for (String pdbid : pdbids)
1161 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1162 if (sm != null && sm.length > 0 && sm[0] != null)
1167 // only return true if there is a mapping for every structure file we have
1169 if (p == 0 || p != pdbids.length)
1173 // and that coloring has been applied
1174 return seqColoursApplied;
1178 public void raiseViewer()
1184 public long startProgressBar(String msg)
1186 // TODO would rather have startProgress/stopProgress as the
1187 // IProgressIndicator interface
1188 long tm = random.nextLong();
1189 if (progressBar != null)
1191 progressBar.setProgressBar(msg, tm);
1197 public void stopProgressBar(String msg, long handle)
1199 if (progressBar != null)
1201 progressBar.setProgressBar(msg, handle);
1205 protected IProgressIndicator getProgressIndicator()
1210 protected void setProgressIndicator(IProgressIndicator pi)
1215 public void setProgressMessage(String message, long id)
1217 if (progressBar != null)
1219 progressBar.setProgressBar(message, id);
1224 public void showConsole(boolean show)
1226 // default does nothing
1230 * Show only the selected chain(s) in the viewer
1232 protected void showSelectedChains()
1234 List<String> toshow = new ArrayList<>();
1235 for (int i = 0; i < chainMenu.getItemCount(); i++)
1237 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
1239 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
1240 if (item.isSelected())
1242 toshow.add(item.getText());
1246 getBinding().showChains(toshow);
1250 * Display selected hetatms in viewer
1252 protected void showSelectedHetatms()
1254 List<String> toshow = new ArrayList<>();
1255 for (int i = 0; i < hetatmMenu.getItemCount(); i++)
1257 if (hetatmMenu.getItem(i) instanceof JCheckBoxMenuItem)
1259 JCheckBoxMenuItem item = (JCheckBoxMenuItem) hetatmMenu.getItem(i);
1260 if (item.isSelected())
1262 toshow.add(item.getText());
1266 getBinding().showHetatms(toshow);
1270 * Tries to fetch a PDB file and save to a temporary local file. Returns the
1271 * saved file path if successful, or null if not.
1273 * @param processingEntry
1276 protected String fetchPdbFile(PDBEntry processingEntry)
1278 String filePath = null;
1279 Pdb pdbclient = new Pdb();
1280 EBIAlfaFold afclient = new EBIAlfaFold();
1281 AlignmentI pdbseq = null;
1282 String pdbid = processingEntry.getId();
1283 long handle = System.currentTimeMillis()
1284 + Thread.currentThread().hashCode();
1287 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
1289 String msg = MessageManager.formatMessage("status.fetching_pdb",
1292 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1293 // long hdl = startProgressBar(MessageManager.formatMessage(
1294 // "status.fetching_pdb", new Object[]
1298 if (afclient.isValidReference(pdbid))
1300 pdbseq = afclient.getSequenceRecords(pdbid,
1301 processingEntry.getRetrievalUrl());
1305 if (processingEntry.hasRetrievalUrl())
1307 String safePDBId = java.net.URLEncoder.encode(pdbid, "UTF-8")
1308 .replace("%", "__");
1310 // retrieve from URL to new local tmpfile
1311 File tmpFile = File.createTempFile(safePDBId,
1312 "." + (PDBEntry.Type.MMCIF.toString().equals(
1313 processingEntry.getType().toString()) ? "cif"
1315 String fromUrl = processingEntry.getRetrievalUrl();
1316 UrlDownloadClient.download(fromUrl, tmpFile);
1318 // may not need this check ?
1319 String file = tmpFile.getAbsolutePath();
1322 pdbseq = EBIAlfaFold.importDownloadedStructureFromUrl(fromUrl,
1323 tmpFile, pdbid, null, null, null);
1328 pdbseq = pdbclient.getSequenceRecords(pdbid);
1331 } catch (Exception e)
1333 jalview.bin.Console.errPrintln(
1334 "Error retrieving PDB id " + pdbid + ": " + e.getMessage());
1337 msg = pdbid + " " + MessageManager.getString("label.state_completed");
1338 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1339 // stopProgressBar(msg, hdl);
1342 * If PDB data were saved and are not invalid (empty alignment), return the
1345 if (pdbseq != null && pdbseq.getHeight() > 0)
1347 // just use the file name from the first sequence's first PDBEntry
1348 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
1349 .elementAt(0).getFile()).getAbsolutePath();
1350 processingEntry.setFile(filePath);
1356 * If supported, saves the state of the structure viewer to a temporary file
1357 * and returns the file, else returns null
1361 public File saveSession()
1363 if (getBinding() == null)
1367 File session = getBinding().saveSession();
1368 long l = session.length();
1375 } catch (InterruptedException e)
1378 long nextl = session.length();
1384 } while (--wait > 0);
1388 private static boolean quitClose = false;
1390 public static void setQuitClose(boolean b)
1396 public boolean stillRunning()
1398 AAStructureBindingModel binding = getBinding();
1399 return binding != null && binding.isViewerRunning();
1403 * Close down this instance of Jalview's Chimera viewer, giving the user the
1404 * option to close the associated Chimera window (process). They may wish to
1405 * keep it open until they have had an opportunity to save any work.
1408 * if true, close any linked Chimera process; if false, prompt first
1411 public void closeViewer(boolean forceClose)
1413 AAStructureBindingModel binding = getBinding();
1418 String viewerName = getViewerName();
1420 int confirm = JvOptionPane.CANCEL_OPTION;
1421 if (QuitHandler.quitting())
1423 // already asked about closing external windows
1424 confirm = quitClose ? JvOptionPane.YES_OPTION
1425 : JvOptionPane.NO_OPTION;
1429 String prompt = MessageManager
1430 .formatMessage("label.confirm_close_viewer", new Object[]
1431 { binding.getViewerTitle(viewerName, false),
1433 prompt = JvSwingUtils.wrapTooltip(true, prompt);
1434 String title = MessageManager.getString("label.close_viewer");
1435 confirm = showCloseDialog(title, prompt);
1439 * abort closure if user hits escape or Cancel
1441 if (confirm == JvOptionPane.CANCEL_OPTION
1442 || confirm == JvOptionPane.CLOSED_OPTION)
1444 // abort possible quit handling if CANCEL chosen
1445 if (confirm == JvOptionPane.CANCEL_OPTION)
1449 // this is a bit futile
1450 this.setClosed(false);
1451 } catch (PropertyVetoException e)
1454 QuitHandler.abortQuit();
1458 forceClose = confirm == JvOptionPane.YES_OPTION;
1461 if (binding != null)
1463 binding.closeViewer(forceClose);
1465 setAlignmentPanel(null);
1468 _colourwith.clear();
1469 // TODO: check for memory leaks where instance isn't finalised because jmb
1470 // holds a reference to the window
1476 } catch (Throwable t)
1479 "Unexpected exception when deregistering structure viewer",
1485 private int showCloseDialog(final String title, final String prompt)
1487 int confirmResponse = JvOptionPane.CANCEL_OPTION;
1488 confirmResponse = JvOptionPane.showConfirmDialog(this, prompt,
1489 MessageManager.getString("label.close_viewer"),
1490 JvOptionPane.YES_NO_CANCEL_OPTION,
1491 JvOptionPane.WARNING_MESSAGE);
1492 return confirmResponse;
1496 public void showHelp_actionPerformed()
1502 String url = getBinding().getHelpURL();
1505 BrowserLauncher.openURL(url);
1509 catch (IOException ex)
1512 .println("Show " + getViewerName() + " failed with: "
1519 public boolean hasViewerActionsMenu()
1521 return viewerActionMenu != null && viewerActionMenu.isEnabled()
1522 && viewerActionMenu.getItemCount() > 0
1523 && viewerActionMenu.isVisible();