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;
38 import java.util.Random;
39 import java.util.Vector;
40 import java.util.concurrent.Callable;
41 import java.util.concurrent.ExecutorService;
42 import java.util.concurrent.TimeUnit;
44 import javax.swing.ButtonGroup;
45 import javax.swing.JCheckBoxMenuItem;
46 import javax.swing.JMenu;
47 import javax.swing.JMenuItem;
48 import javax.swing.JRadioButtonMenuItem;
49 import javax.swing.event.MenuEvent;
50 import javax.swing.event.MenuListener;
52 import jalview.api.AlignmentViewPanel;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.PDBEntry;
57 import jalview.datamodel.SequenceI;
58 import jalview.gui.JalviewColourChooser.ColourChooserListener;
59 import jalview.gui.StructureViewer.ViewerType;
60 import jalview.gui.ViewSelectionMenu.ViewSetProvider;
61 import jalview.io.DataSourceType;
62 import jalview.io.JalviewFileChooser;
63 import jalview.io.JalviewFileView;
64 import jalview.jbgui.GStructureViewer;
65 import jalview.schemes.ColourSchemeI;
66 import jalview.schemes.ColourSchemes;
67 import jalview.structure.StructureMapping;
68 import jalview.structures.models.AAStructureBindingModel;
69 import jalview.util.BrowserLauncher;
70 import jalview.util.MessageManager;
71 import jalview.ws.dbsources.EBIAlfaFold;
72 import jalview.ws.dbsources.Pdb;
73 import jalview.ws.utils.UrlDownloadClient;
76 * Base class with common functionality for JMol, Chimera or other structure
82 public abstract class StructureViewerBase extends GStructureViewer
83 implements Runnable, ViewSetProvider
86 * names for colour options (additional to Jalview colour schemes)
90 BySequence, ByChain, ChargeCysteine, ByViewer
94 * list of sequenceSet ids associated with the view
96 protected List<String> _aps = new ArrayList<>();
99 * list of alignment panels to use for superposition
101 protected Vector<AlignmentViewPanel> _alignwith = new Vector<>();
104 * list of alignment panels that are used for colouring structures by aligned
107 protected Vector<AlignmentViewPanel> _colourwith = new Vector<>();
109 private String viewId = null;
111 private AlignmentPanel ap;
113 protected boolean alignAddedStructures = false;
115 protected volatile boolean _started = false;
117 protected volatile boolean addingStructures = false;
119 protected Thread worker = null;
121 protected boolean allChainsSelected = false;
123 protected JMenu viewSelectionMenu;
126 * set after sequence colouring has been applied for this structure viewer.
127 * used to determine if the final sequence/structure mapping has been
130 protected volatile boolean seqColoursApplied = false;
132 private IProgressIndicator progressBar = null;
134 private Random random = new Random();
137 * Default constructor
139 public StructureViewerBase()
146 * @return true if added structures should be aligned to existing one(s)
149 public boolean isAlignAddedStructures()
151 return alignAddedStructures;
157 * if added structures should be aligned to existing one(s)
160 public void setAlignAddedStructures(boolean alignAdded)
162 alignAddedStructures = alignAdded;
166 * called by the binding model to indicate when adding structures is happening
167 * or has been completed
169 * @param addingStructures
171 public synchronized void setAddingStructures(boolean addingStructures)
173 this.addingStructures = addingStructures;
179 * @return true if this Jmol instance is linked with the given alignPanel
181 public boolean isLinkedWith(AlignmentPanel ap2)
183 return _aps.contains(ap2.av.getSequenceSetId());
186 public boolean isUsedforaligment(AlignmentViewPanel ap2)
189 return (_alignwith != null) && _alignwith.contains(ap2);
193 public boolean isUsedForColourBy(AlignmentViewPanel ap2)
195 return (_colourwith != null) && _colourwith.contains(ap2);
200 * @return TRUE if the view is NOT being coloured by the alignment colours.
202 public boolean isColouredByViewer()
204 return !getBinding().isColourBySequence();
207 public String getViewId()
211 viewId = System.currentTimeMillis() + "." + this.hashCode();
216 protected void setViewId(String viewId)
218 this.viewId = viewId;
221 protected void buildActionMenu()
223 if (_alignwith == null)
225 _alignwith = new Vector<>();
227 if (_alignwith.size() == 0 && ap != null)
232 // TODO: refactor to allow concrete classes to register buttons for adding
234 // currently have to override to add buttons back in after they are cleared
236 for (Component c : viewerActionMenu.getMenuComponents())
238 if (c != alignStructs)
240 viewerActionMenu.remove((JMenuItem) c);
246 public AlignmentPanel getAlignmentPanel()
251 protected void setAlignmentPanel(AlignmentPanel alp)
257 public AlignmentPanel[] getAllAlignmentPanels()
259 AlignmentPanel[] t, list = new AlignmentPanel[0];
260 for (String setid : _aps)
262 AlignmentPanel[] panels = PaintRefresher.getAssociatedPanels(setid);
265 t = new AlignmentPanel[list.length + panels.length];
266 System.arraycopy(list, 0, t, 0, list.length);
267 System.arraycopy(panels, 0, t, list.length, panels.length);
276 * set the primary alignmentPanel reference and add another alignPanel to the
277 * list of ones to use for colouring and aligning
281 public void addAlignmentPanel(AlignmentPanel nap)
283 if (getAlignmentPanel() == null)
285 setAlignmentPanel(nap);
287 if (!_aps.contains(nap.av.getSequenceSetId()))
289 _aps.add(nap.av.getSequenceSetId());
294 * remove any references held to the given alignment panel
299 public void removeAlignmentPanel(AlignmentViewPanel nap)
303 _alignwith.remove(nap);
304 _colourwith.remove(nap);
305 if (getAlignmentPanel() == nap)
307 setAlignmentPanel(null);
308 for (AlignmentPanel aps : getAllAlignmentPanels())
312 setAlignmentPanel(aps);
317 } catch (Exception ex)
320 if (getAlignmentPanel() != null)
326 public void useAlignmentPanelForSuperposition(AlignmentPanel nap)
328 addAlignmentPanel(nap);
329 if (!_alignwith.contains(nap))
335 public void excludeAlignmentPanelForSuperposition(AlignmentPanel nap)
337 if (_alignwith.contains(nap))
339 _alignwith.remove(nap);
343 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap,
344 boolean enableColourBySeq)
346 useAlignmentPanelForColourbyseq(nap);
347 getBinding().setColourBySequence(enableColourBySeq);
348 seqColour.setSelected(enableColourBySeq);
349 viewerColour.setSelected(!enableColourBySeq);
352 public void useAlignmentPanelForColourbyseq(AlignmentPanel nap)
354 addAlignmentPanel(nap);
355 if (!_colourwith.contains(nap))
357 _colourwith.add(nap);
361 public void excludeAlignmentPanelForColourbyseq(AlignmentPanel nap)
363 if (_colourwith.contains(nap))
365 _colourwith.remove(nap);
369 public abstract ViewerType getViewerType();
372 * add a new structure (with associated sequences and chains) to this viewer,
373 * retrieving it if necessary first.
379 * if true, new structure(s) will be aligned using associated
383 protected void addStructure(final PDBEntry pdbentry,
384 final SequenceI[] seqs, final String[] chains,
385 final IProgressIndicator alignFrame)
387 if (pdbentry.getFile() == null)
389 if (worker != null && worker.isAlive())
391 // a retrieval is in progress, wait around and add ourselves to the
393 new Thread(new Runnable()
398 while (worker != null && worker.isAlive() && _started)
402 Thread.sleep(100 + ((int) Math.random() * 100));
404 } catch (Exception e)
408 // and call ourselves again.
409 addStructure(pdbentry, seqs, chains, alignFrame);
415 // otherwise, start adding the structure.
416 getBinding().addSequenceAndChain(new PDBEntry[] { pdbentry },
418 { seqs }, new String[][] { chains });
419 addingStructures = true;
421 worker = new Thread(this);
426 protected boolean hasPdbId(String pdbId)
428 return getBinding().hasPdbId(pdbId);
432 * Returns a list of any viewer of the instantiated type. The list is
433 * restricted to those linked to the given alignment panel if it is not null.
435 protected List<StructureViewerBase> getViewersFor(AlignmentPanel alp)
437 return Desktop.instance.getStructureViewers(alp, this.getClass());
441 public void addToExistingViewer(PDBEntry pdbentry, SequenceI[] seq,
442 String[] chains, final AlignmentViewPanel apanel, String pdbId)
445 * JAL-1742 exclude view with this structure already mapped (don't offer
446 * to align chain B to chain A of the same structure); code may defend
447 * against this possibility before we reach here
453 AlignmentPanel alignPanel = (AlignmentPanel) apanel; // Implementation error
456 useAlignmentPanelForSuperposition(alignPanel);
457 addStructure(pdbentry, seq, chains, alignPanel.alignFrame);
461 * Adds mappings for the given sequences to an already opened PDB structure,
462 * and updates any viewers that have the PDB file
469 public void addSequenceMappingsToStructure(SequenceI[] seq,
470 String[] chains, final AlignmentViewPanel alpanel,
473 AlignmentPanel apanel = (AlignmentPanel) alpanel;
475 // TODO : Fix multiple seq to one chain issue here.
477 * create the mappings
479 apanel.getStructureSelectionManager().setMapping(seq, chains,
480 pdbFilename, DataSourceType.FILE, getProgressIndicator());
483 * alert the FeatureRenderer to show new (PDB RESNUM) features
485 if (apanel.getSeqPanel().seqCanvas.fr != null)
487 apanel.getSeqPanel().seqCanvas.fr.featuresAdded();
488 // note - we don't do a refresh for structure here because we do it
489 // explicitly for all panels later on
490 apanel.paintAlignment(true, false);
494 * add the sequences to any other viewers (of the same type) for this pdb
497 // JBPNOTE: this looks like a binding routine, rather than a gui routine
498 for (StructureViewerBase viewer : getViewersFor(null))
500 AAStructureBindingModel bindingModel = viewer.getBinding();
501 for (int pe = 0; pe < bindingModel.getPdbCount(); pe++)
503 if (bindingModel.getPdbEntry(pe).getFile().equals(pdbFilename))
505 bindingModel.addSequence(pe, seq);
506 viewer.addAlignmentPanel(apanel);
508 * add it to the set of alignments used for colouring structure by
511 viewer.useAlignmentPanelForColourbyseq(apanel);
512 viewer.buildActionMenu();
513 apanel.getStructureSelectionManager()
514 .sequenceColoursChanged(apanel);
522 public boolean addAlreadyLoadedFile(SequenceI[] seq, String[] chains,
523 final AlignmentViewPanel apanel, String pdbId)
525 String alreadyMapped = apanel.getStructureSelectionManager()
526 .alreadyMappedToFile(pdbId);
528 if (alreadyMapped == null)
533 addSequenceMappingsToStructure(seq, chains, apanel, alreadyMapped);
537 void setChainMenuItems(List<String> chainNames)
539 chainMenu.removeAll();
540 if (chainNames == null || chainNames.isEmpty())
544 JMenuItem menuItem = new JMenuItem(
545 MessageManager.getString("label.all"));
546 menuItem.addActionListener(new ActionListener()
549 public void actionPerformed(ActionEvent evt)
551 allChainsSelected = true;
552 for (int i = 0; i < chainMenu.getItemCount(); i++)
554 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
556 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
559 showSelectedChains();
560 allChainsSelected = false;
564 chainMenu.add(menuItem);
566 for (String chain : chainNames)
568 menuItem = new JCheckBoxMenuItem(chain, true);
569 menuItem.addItemListener(new ItemListener()
572 public void itemStateChanged(ItemEvent evt)
574 if (!allChainsSelected)
576 showSelectedChains();
581 chainMenu.add(menuItem);
586 * Action on selecting one of Jalview's registered colour schemes
589 public void changeColour_actionPerformed(String colourSchemeName)
591 AlignmentI al = getAlignmentPanel().av.getAlignment();
592 ColourSchemeI cs = ColourSchemes.getInstance().getColourScheme(
593 colourSchemeName, getAlignmentPanel().av, al, null);
594 getBinding().colourByJalviewColourScheme(cs);
598 * Builds the colour menu
600 protected void buildColourMenu()
602 colourMenu.removeAll();
603 AlignmentI al = getAlignmentPanel().av.getAlignment();
606 * add colour by sequence, by chain, by charge and cysteine
608 colourMenu.add(seqColour);
609 colourMenu.add(chainColour);
610 colourMenu.add(chargeColour);
611 chargeColour.setEnabled(!al.isNucleotide());
614 * add all 'simple' (per-residue) colour schemes registered to Jalview
616 ButtonGroup itemGroup = ColourMenuHelper.addMenuItems(colourMenu, this,
620 * add 'colour by viewer' (menu item text is set in subclasses)
622 viewerColour.setSelected(false);
623 viewerColour.addActionListener(new ActionListener()
626 public void actionPerformed(ActionEvent actionEvent)
628 viewerColour_actionPerformed();
631 colourMenu.add(viewerColour);
634 * add 'set background colour'
636 JMenuItem backGround = new JMenuItem();
638 .setText(MessageManager.getString("action.background_colour"));
639 backGround.addActionListener(new ActionListener()
642 public void actionPerformed(ActionEvent actionEvent)
644 background_actionPerformed();
647 colourMenu.add(backGround);
650 * add colour buttons to a group so their selection is
651 * mutually exclusive (background colour is a separate option)
653 itemGroup.add(seqColour);
654 itemGroup.add(chainColour);
655 itemGroup.add(chargeColour);
656 itemGroup.add(viewerColour);
660 * Construct menu items
662 protected void initMenus()
664 AAStructureBindingModel binding = getBinding();
666 seqColour = new JRadioButtonMenuItem();
667 seqColour.setText(MessageManager.getString("action.by_sequence"));
668 seqColour.setName(ViewerColour.BySequence.name());
669 seqColour.setSelected(binding.isColourBySequence());
670 seqColour.addActionListener(new ActionListener()
673 public void actionPerformed(ActionEvent actionEvent)
675 seqColour_actionPerformed();
679 chainColour = new JRadioButtonMenuItem();
680 chainColour.setText(MessageManager.getString("action.by_chain"));
681 chainColour.setName(ViewerColour.ByChain.name());
682 chainColour.addActionListener(new ActionListener()
685 public void actionPerformed(ActionEvent actionEvent)
687 chainColour_actionPerformed();
691 chargeColour = new JRadioButtonMenuItem();
692 chargeColour.setText(MessageManager.getString("label.charge_cysteine"));
693 chargeColour.setName(ViewerColour.ChargeCysteine.name());
694 chargeColour.addActionListener(new ActionListener()
697 public void actionPerformed(ActionEvent actionEvent)
699 chargeColour_actionPerformed();
703 viewerColour = new JRadioButtonMenuItem();
705 .setText(MessageManager.getString("label.colour_with_viewer"));
706 viewerColour.setToolTipText(MessageManager
707 .getString("label.let_viewer_manage_structure_colours"));
708 viewerColour.setName(ViewerColour.ByViewer.name());
709 viewerColour.setSelected(!binding.isColourBySequence());
711 if (_colourwith == null)
713 _colourwith = new Vector<>();
715 if (_alignwith == null)
717 _alignwith = new Vector<>();
720 ViewSelectionMenu seqColourBy = new ViewSelectionMenu(
721 MessageManager.getString("label.colour_by"), this, _colourwith,
725 public void itemStateChanged(ItemEvent e)
727 if (!seqColour.isSelected())
733 // update the viewer display now.
734 seqColour_actionPerformed();
738 viewMenu.add(seqColourBy);
740 final ItemListener handler = new ItemListener()
743 public void itemStateChanged(ItemEvent e)
745 if (_alignwith.isEmpty())
747 alignStructs.setEnabled(false);
748 alignStructs.setToolTipText(null);
752 alignStructs.setEnabled(true);
753 alignStructs.setToolTipText(MessageManager.formatMessage(
754 "label.align_structures_using_linked_alignment_views",
759 viewSelectionMenu = new ViewSelectionMenu(
760 MessageManager.getString("label.superpose_with"), this,
761 _alignwith, handler);
762 handler.itemStateChanged(null);
763 viewerActionMenu.add(viewSelectionMenu, 0);
764 viewerActionMenu.addMenuListener(new MenuListener()
767 public void menuSelected(MenuEvent e)
769 handler.itemStateChanged(null);
773 public void menuDeselected(MenuEvent e)
778 public void menuCanceled(MenuEvent e)
783 viewerActionMenu.setText(getViewerName());
784 helpItem.setText(MessageManager.formatMessage("label.viewer_help",
791 * Sends commands to the structure viewer to superimpose structures based on
792 * currently associated alignments. May optionally return an error message for
796 protected String alignStructsWithAllAlignPanels()
798 if (getAlignmentPanel() == null)
803 if (_alignwith.size() == 0)
805 _alignwith.add(getAlignmentPanel());
811 reply = getBinding().superposeStructures(_alignwith);
812 if (reply != null && !reply.isEmpty())
814 String text = MessageManager
815 .formatMessage("error.superposition_failed", reply);
816 statusBar.setText(text);
818 } catch (Exception e)
820 StringBuffer sp = new StringBuffer();
821 for (AlignmentViewPanel alignPanel : _alignwith)
823 sp.append("'" + alignPanel.getViewName() + "' ");
825 Console.info("Couldn't align structures with the " + sp.toString()
826 + "associated alignment panels.", e);
832 * Opens a colour chooser dialog, and applies the chosen colour to the
833 * background of the structure viewer
836 public void background_actionPerformed()
838 String ttl = MessageManager.getString("label.select_background_colour");
839 ColourChooserListener listener = new ColourChooserListener()
842 public void colourSelected(Color c)
844 getBinding().setBackgroundColour(c);
847 JalviewColourChooser.showColourChooser(this, ttl, null, listener);
851 public void viewerColour_actionPerformed()
853 if (viewerColour.isSelected())
855 // disable automatic sequence colouring.
856 getBinding().setColourBySequence(false);
861 public void chainColour_actionPerformed()
863 chainColour.setSelected(true);
864 getBinding().colourByChain();
868 public void chargeColour_actionPerformed()
870 chargeColour.setSelected(true);
871 getBinding().colourByCharge();
875 public void seqColour_actionPerformed()
877 AAStructureBindingModel binding = getBinding();
878 binding.setColourBySequence(seqColour.isSelected());
879 if (_colourwith == null)
881 _colourwith = new Vector<>();
883 if (binding.isColourBySequence())
885 if (!binding.isLoadingFromArchive())
887 if (_colourwith.size() == 0 && getAlignmentPanel() != null)
889 // Make the currently displayed alignment panel the associated view
890 _colourwith.add(getAlignmentPanel().alignFrame.alignPanel);
893 // Set the colour using the current view for the associated alignframe
894 for (AlignmentViewPanel alignPanel : _colourwith)
896 binding.colourBySequence(alignPanel);
898 seqColoursApplied = true;
903 public void pdbFile_actionPerformed()
905 // TODO: JAL-3048 not needed for Jalview-JS - save PDB file
906 JalviewFileChooser chooser = new JalviewFileChooser(
907 Cache.getProperty("LAST_DIRECTORY"));
909 chooser.setFileView(new JalviewFileView());
910 chooser.setDialogTitle(MessageManager.getString("label.save_pdb_file"));
911 chooser.setToolTipText(MessageManager.getString("action.save"));
913 int value = chooser.showSaveDialog(this);
915 if (value == JalviewFileChooser.APPROVE_OPTION)
917 BufferedReader in = null;
920 // TODO: cope with multiple PDB files in view
921 in = new BufferedReader(
922 new FileReader(getBinding().getStructureFiles()[0]));
923 File outFile = chooser.getSelectedFile();
925 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
927 while ((data = in.readLine()) != null)
929 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
935 } catch (Exception ex)
937 ex.printStackTrace();
945 } catch (IOException e)
955 public void viewMapping_actionPerformed()
957 CutAndPasteTransfer cap = new CutAndPasteTransfer();
960 cap.appendText(getBinding().printMappings());
961 } catch (OutOfMemoryError e)
964 "composing sequence-structure alignments for display in text box.",
969 Desktop.addInternalFrame(cap,
970 MessageManager.getString("label.pdb_sequence_mapping"), 550,
974 protected abstract String getViewerName();
977 * Configures the title and menu items of the viewer panel.
980 public void updateTitleAndMenus()
982 AAStructureBindingModel binding = getBinding();
983 if (binding.hasFileLoadingError())
988 setChainMenuItems(binding.getChainNames());
990 this.setTitle(binding.getViewerTitle(getViewerName(), true));
993 * enable 'Superpose with' if more than one mapped structure
995 viewSelectionMenu.setEnabled(false);
996 if (getBinding().getMappedStructureCount() > 1
997 && getBinding().getSequence().length > 1)
999 viewSelectionMenu.setEnabled(true);
1003 * Show action menu if it has any enabled items
1005 viewerActionMenu.setVisible(false);
1006 for (int i = 0; i < viewerActionMenu.getItemCount(); i++)
1008 if (viewerActionMenu.getItem(i).isEnabled())
1010 viewerActionMenu.setVisible(true);
1015 if (!binding.isLoadingFromArchive())
1017 seqColour_actionPerformed();
1022 public String toString()
1028 public boolean hasMapping()
1030 if (worker != null && (addingStructures || _started))
1034 if (getBinding() == null)
1036 if (_aps == null || _aps.size() == 0)
1038 // viewer has been closed, but we did at some point run.
1043 String[] pdbids = getBinding().getStructureFiles();
1049 for (String pdbid : pdbids)
1051 StructureMapping sm[] = getBinding().getSsm().getMapping(pdbid);
1052 if (sm != null && sm.length > 0 && sm[0] != null)
1057 // only return true if there is a mapping for every structure file we have
1059 if (p == 0 || p != pdbids.length)
1063 // and that coloring has been applied
1064 return seqColoursApplied;
1068 public void raiseViewer()
1074 public long startProgressBar(String msg)
1076 // TODO would rather have startProgress/stopProgress as the
1077 // IProgressIndicator interface
1078 long tm = random.nextLong();
1079 if (progressBar != null)
1081 progressBar.setProgressBar(msg, tm);
1087 public void stopProgressBar(String msg, long handle)
1089 if (progressBar != null)
1091 progressBar.setProgressBar(msg, handle);
1095 protected IProgressIndicator getProgressIndicator()
1100 protected void setProgressIndicator(IProgressIndicator pi)
1105 public void setProgressMessage(String message, long id)
1107 if (progressBar != null)
1109 progressBar.setProgressBar(message, id);
1114 public void showConsole(boolean show)
1116 // default does nothing
1120 * Show only the selected chain(s) in the viewer
1122 protected void showSelectedChains()
1124 List<String> toshow = new ArrayList<>();
1125 for (int i = 0; i < chainMenu.getItemCount(); i++)
1127 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
1129 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
1130 if (item.isSelected())
1132 toshow.add(item.getText());
1136 getBinding().showChains(toshow);
1140 * Tries to fetch a PDB file and save to a temporary local file. Returns the
1141 * saved file path if successful, or null if not.
1143 * @param processingEntry
1146 protected String fetchPdbFile(PDBEntry processingEntry)
1148 String filePath = null;
1149 Pdb pdbclient = new Pdb();
1150 EBIAlfaFold afclient = new EBIAlfaFold();
1151 AlignmentI pdbseq = null;
1152 String pdbid = processingEntry.getId();
1153 long handle = System.currentTimeMillis()
1154 + Thread.currentThread().hashCode();
1157 * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
1159 String msg = MessageManager.formatMessage("status.fetching_pdb",
1162 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1163 // long hdl = startProgressBar(MessageManager.formatMessage(
1164 // "status.fetching_pdb", new Object[]
1168 if (afclient.isValidReference(pdbid))
1170 pdbseq = afclient.getSequenceRecords(pdbid,
1171 processingEntry.getRetrievalUrl());
1175 if (processingEntry.hasRetrievalUrl())
1177 String safePDBId = java.net.URLEncoder.encode(pdbid, "UTF-8")
1178 .replace("%", "__");
1180 // retrieve from URL to new local tmpfile
1181 File tmpFile = File.createTempFile(safePDBId,
1182 "." + (PDBEntry.Type.MMCIF.toString().equals(
1183 processingEntry.getType().toString()) ? "cif"
1185 String fromUrl = processingEntry.getRetrievalUrl();
1186 UrlDownloadClient.download(fromUrl, tmpFile);
1188 // may not need this check ?
1189 String file = tmpFile.getAbsolutePath();
1192 pdbseq = EBIAlfaFold.importDownloadedStructureFromUrl(fromUrl,
1193 tmpFile, pdbid, null, null, null);
1198 pdbseq = pdbclient.getSequenceRecords(pdbid);
1201 } catch (Exception e)
1204 "Error retrieving PDB id " + pdbid + ": " + e.getMessage());
1207 msg = pdbid + " " + MessageManager.getString("label.state_completed");
1208 getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
1209 // stopProgressBar(msg, hdl);
1212 * If PDB data were saved and are not invalid (empty alignment), return the
1215 if (pdbseq != null && pdbseq.getHeight() > 0)
1217 // just use the file name from the first sequence's first PDBEntry
1218 filePath = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
1219 .elementAt(0).getFile()).getAbsolutePath();
1220 processingEntry.setFile(filePath);
1226 * If supported, saves the state of the structure viewer to a temporary file
1227 * and returns the file, else returns null
1231 public File saveSession()
1233 if (getBinding() == null)
1237 File session = getBinding().saveSession();
1238 long l = session.length();
1245 } catch (InterruptedException e)
1248 long nextl = session.length();
1254 } while (--wait > 0);
1259 * Close down this instance of Jalview's Chimera viewer, giving the user the
1260 * option to close the associated Chimera window (process). They may wish to
1261 * keep it open until they have had an opportunity to save any work.
1264 * if true, close any linked Chimera process; if false, prompt first
1267 public void closeViewer(boolean forceClose)
1269 AAStructureBindingModel binding = getBinding();
1270 if (binding != null && binding.isViewerRunning())
1274 String viewerName = getViewerName();
1276 int confirm = JvOptionPane.CANCEL_OPTION;
1277 String prompt = MessageManager
1278 .formatMessage("label.confirm_close_viewer", new Object[]
1279 { binding.getViewerTitle(viewerName, false), viewerName });
1280 prompt = JvSwingUtils.wrapTooltip(true, prompt);
1281 String title = MessageManager.getString("label.close_viewer");
1282 confirm = showCloseDialog(title, prompt);
1285 * abort closure if user hits escape or Cancel
1287 if (confirm == JvOptionPane.CANCEL_OPTION
1288 || confirm == JvOptionPane.CLOSED_OPTION)
1290 // abort possible quit handling if CANCEL chosen
1291 if (confirm == JvOptionPane.CANCEL_OPTION)
1295 // this is a bit futile
1296 this.setClosed(false);
1297 } catch (PropertyVetoException e)
1300 QuitHandler.abortQuit();
1304 forceClose = confirm == JvOptionPane.YES_OPTION;
1307 if (binding != null)
1309 binding.closeViewer(forceClose);
1311 setAlignmentPanel(null);
1314 _colourwith.clear();
1315 // TODO: check for memory leaks where instance isn't finalised because jmb
1316 // holds a reference to the window
1321 private int showCloseDialog(final String title, final String prompt)
1323 confirmResponse = JvOptionPane.CANCEL_OPTION;
1325 if (QuitHandler.quitting())
1328 Callable<Void> yesCall = () -> {
1329 Console.debug("YES");
1330 confirmResponse = JvOptionPane.YES_OPTION;
1333 Callable<Void> noCall = () -> {
1334 Console.debug("NO");
1335 confirmResponse = JvOptionPane.NO_OPTION;
1338 Callable<Void> cancelCall = () -> {
1339 Console.debug("CANCEL");
1340 confirmResponse = JvOptionPane.CANCEL_OPTION;
1343 Callable<Void>[] calls = new Callable[] { yesCall, noCall,
1345 String cancelQuit = MessageManager.getString("action.cancel_quit");
1346 String[] buttonsText = { MessageManager.getString("action.yes"),
1347 MessageManager.getString("action.no"), cancelQuit };
1348 JvOptionPane dialog = JvOptionPane.frameDialog(prompt,
1349 MessageManager.getString("label.close_viewer"),
1350 JvOptionPane.WARNING_MESSAGE, buttonsText, cancelQuit, calls,
1352 // wait for response
1353 ExecutorService executor = dialog.getExecutor();
1354 executor.shutdown();
1357 Console.debug("### executor.awaitTermination() starting");
1358 executor.awaitTermination(60, TimeUnit.SECONDS);
1359 Console.debug("### executor.awaitTermination() finished");
1360 } catch (InterruptedException e)
1366 confirmResponse = JvOptionPane.showConfirmDialog(this, prompt,
1367 MessageManager.getString("label.close_viewer"),
1368 JvOptionPane.YES_NO_CANCEL_OPTION,
1369 JvOptionPane.WARNING_MESSAGE);
1371 return confirmResponse;
1375 public void showHelp_actionPerformed()
1381 String url = getBinding().getHelpURL();
1384 BrowserLauncher.openURL(url);
1388 catch (IOException ex)
1391 .println("Show " + getViewerName() + " failed with: "
1398 public boolean hasViewerActionsMenu()
1400 return viewerActionMenu != null && viewerActionMenu.isEnabled()
1401 && viewerActionMenu.getItemCount() > 0
1402 && viewerActionMenu.isVisible();
1405 private static int confirmResponse = 0;