molstar-cli 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- molstar_cli-0.0.1/.gitignore +8 -0
- molstar_cli-0.0.1/LICENSE +21 -0
- molstar_cli-0.0.1/PKG-INFO +134 -0
- molstar_cli-0.0.1/README.md +111 -0
- molstar_cli-0.0.1/molstar_cli/__init__.py +12 -0
- molstar_cli-0.0.1/molstar_cli/__main__.py +5 -0
- molstar_cli-0.0.1/molstar_cli/_version.py +24 -0
- molstar_cli-0.0.1/molstar_cli/cli.py +70 -0
- molstar_cli-0.0.1/molstar_cli/server.py +128 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/LICENSE.molstar +21 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/VERSION +1 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/favicon.ico +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/cells.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_back6.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_bottom4.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_front5.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_left2.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_right1.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/images/nebula_top3.jpg +0 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/molstar.css +3 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/molstar.js +7872 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/blue.css +2 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/blue.js +1 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/dark.css +2 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/dark.js +1 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/light.css +2 -0
- molstar_cli-0.0.1/molstar_cli/static/molstar/theme/light.js +1 -0
- molstar_cli-0.0.1/molstar_cli/static/open.html +38 -0
- molstar_cli-0.0.1/pyproject.toml +49 -0
- molstar_cli-0.0.1/scripts/update_molstar.py +45 -0
- molstar_cli-0.0.1/tests/test_cli.py +127 -0
- molstar_cli-0.0.1/tests/test_server.py +113 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Arthur Zalevsky
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: molstar-cli
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Open local structure and map files (mmCIF, PDB, EMDB maps, ...) in the Mol* viewer from the command line
|
|
5
|
+
Project-URL: Homepage, https://github.com/aozalevsky/molstar_cli
|
|
6
|
+
Project-URL: Issues, https://github.com/aozalevsky/molstar_cli/issues
|
|
7
|
+
Project-URL: Mol*, https://molstar.org
|
|
8
|
+
Author: Arthur Zalevsky
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: molstar_cli/static/molstar/LICENSE.molstar
|
|
12
|
+
Keywords: cryo-em,emdb,mmcif,mol*,molecular visualization,molstar,pdb,viewer
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Environment :: Web Environment
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Chemistry
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# molstar-cli
|
|
25
|
+
|
|
26
|
+
Open local structure and map files in the [Mol*](https://molstar.org) viewer from the terminal.
|
|
27
|
+
|
|
28
|
+
```console
|
|
29
|
+
$ pip install molstar-cli
|
|
30
|
+
$ molstar 5me2.cif emd_3488.map.gz
|
|
31
|
+
Mol* viewer: http://127.0.0.1:34037/MtXDcbb3cYRnGhsxczKvZw/
|
|
32
|
+
Press Ctrl-C to stop.
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
All files open together in one Mol* scene in your default browser — e.g. a model fitted
|
|
36
|
+
into its cryo-EM map. The Mol* viewer is bundled, so it works offline; there are no
|
|
37
|
+
dependencies beyond Python ≥ 3.10.
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
molstar FILE [FILE ...] [-p PORT] [--no-browser]
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```console
|
|
46
|
+
$ molstar *.cif # several structures, one scene
|
|
47
|
+
$ molstar model.cif emd_1234.map.gz # model + EMDB map
|
|
48
|
+
$ molstar PDBDEV_00000001.cif # integrative (IHM) models, incl. coarse-grained beads
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The command keeps serving while you look at the structures; stop it with Ctrl-C.
|
|
52
|
+
Reloading the browser tab re-reads the files from disk.
|
|
53
|
+
|
|
54
|
+
| Option | |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `-p`, `--port PORT` | listen on a fixed port instead of a random free one |
|
|
57
|
+
| `--no-browser` | only print the URL |
|
|
58
|
+
| `-V`, `--version` | print the molstar-cli and bundled Mol* versions |
|
|
59
|
+
|
|
60
|
+
### Supported formats
|
|
61
|
+
|
|
62
|
+
Anything Mol*'s *Open Files* dialog accepts, detected by file extension, optionally
|
|
63
|
+
wrapped in `.gz` or `.zip`:
|
|
64
|
+
|
|
65
|
+
- **Structures:** mmCIF / PDBx (`.cif`, `.mmcif`, `.mcif`) including IHM integrative
|
|
66
|
+
models, BinaryCIF (`.bcif`), PDB (`.pdb`, `.ent`), PDBQT, PQR, GRO, XYZ, SDF / MOL /
|
|
67
|
+
MOL2, LAMMPS data/dump
|
|
68
|
+
- **Volumes:** CCP4 / MRC / MAP (`.map`, `.mrc`, `.ccp4` — EMDB maps), DSN6 / BRIX,
|
|
69
|
+
DX, Cube, density server CIF, MTZ
|
|
70
|
+
- **Trajectories and topologies:** DCD, XTC, TRR, NetCDF, PSF, PRMTOP, TOP
|
|
71
|
+
- **Other:** PLY / OBJ meshes, MolViewSpec (`.mvsj`, `.mvsx`), Mol* sessions (`.molj`, `.molx`)
|
|
72
|
+
|
|
73
|
+
Unsupported files are skipped with a warning in the Mol* log panel.
|
|
74
|
+
|
|
75
|
+
Maps open at Mol*'s default isovalue (2σ) — the EMDB-recommended contour level is not
|
|
76
|
+
stored in the map file. Adjust it in the Volume panel on the right.
|
|
77
|
+
|
|
78
|
+
### Remote machines
|
|
79
|
+
|
|
80
|
+
With `--no-browser`, or on a Linux machine without a display (e.g. over SSH), `molstar`
|
|
81
|
+
doesn't start a browser; it prints an `ssh -L` command instead:
|
|
82
|
+
|
|
83
|
+
```console
|
|
84
|
+
server$ molstar model.cif
|
|
85
|
+
Mol* viewer: http://127.0.0.1:41235/Xy.../
|
|
86
|
+
On a remote machine? Run `ssh -L 41235:127.0.0.1:41235 server` on your computer, then open the URL above there.
|
|
87
|
+
Press Ctrl-C to stop.
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Use `--port` to keep the same forwarded port between runs.
|
|
91
|
+
|
|
92
|
+
### Security
|
|
93
|
+
|
|
94
|
+
The server listens on `127.0.0.1` only, every URL carries a random token, and only the
|
|
95
|
+
files named on the command line can be read — no directory listing, no other paths.
|
|
96
|
+
|
|
97
|
+
## Development
|
|
98
|
+
|
|
99
|
+
```console
|
|
100
|
+
$ python -m venv .venv && .venv/bin/pip install -e . pytest
|
|
101
|
+
$ .venv/bin/pytest
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Updating the bundled Mol*
|
|
105
|
+
|
|
106
|
+
The prebuilt viewer from the [`molstar` npm package](https://www.npmjs.com/package/molstar)
|
|
107
|
+
is vendored in `molstar_cli/static/molstar/` (no Node.js needed):
|
|
108
|
+
|
|
109
|
+
```console
|
|
110
|
+
$ python scripts/update_molstar.py 5.11.0
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Check that it loads, then commit the result.
|
|
114
|
+
|
|
115
|
+
### Releasing
|
|
116
|
+
|
|
117
|
+
Create a GitHub release with a tag like `v0.0.2`. The package version is taken from the
|
|
118
|
+
tag, so there is nothing to bump. The *Publish to PyPI* workflow builds and uploads it
|
|
119
|
+
using [trusted publishing](https://docs.pypi.org/trusted-publishers/) (PyPI publisher:
|
|
120
|
+
owner `aozalevsky`, repository `molstar_cli`, workflow `publish.yml`, environment `pypi`).
|
|
121
|
+
|
|
122
|
+
## Citing Mol*
|
|
123
|
+
|
|
124
|
+
If you use Mol* in your work, please cite:
|
|
125
|
+
|
|
126
|
+
> D. Sehnal, S. Bittrich, M. Deshpande, R. Svobodová, K. Berka, V. Bazgier, S. Velankar,
|
|
127
|
+
> S.K. Burley, J. Koča, A.S. Rose. Mol* Viewer: modern web app for 3D visualization and
|
|
128
|
+
> analysis of large biomolecular structures. *Nucleic Acids Research* 49(W1), W431–W437
|
|
129
|
+
> (2021). [doi:10.1093/nar/gkab314](https://doi.org/10.1093/nar/gkab314)
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT. The bundled Mol* viewer is © Mol* contributors, also MIT —
|
|
134
|
+
see [`LICENSE.molstar`](molstar_cli/static/molstar/LICENSE.molstar).
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# molstar-cli
|
|
2
|
+
|
|
3
|
+
Open local structure and map files in the [Mol*](https://molstar.org) viewer from the terminal.
|
|
4
|
+
|
|
5
|
+
```console
|
|
6
|
+
$ pip install molstar-cli
|
|
7
|
+
$ molstar 5me2.cif emd_3488.map.gz
|
|
8
|
+
Mol* viewer: http://127.0.0.1:34037/MtXDcbb3cYRnGhsxczKvZw/
|
|
9
|
+
Press Ctrl-C to stop.
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
All files open together in one Mol* scene in your default browser — e.g. a model fitted
|
|
13
|
+
into its cryo-EM map. The Mol* viewer is bundled, so it works offline; there are no
|
|
14
|
+
dependencies beyond Python ≥ 3.10.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
molstar FILE [FILE ...] [-p PORT] [--no-browser]
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```console
|
|
23
|
+
$ molstar *.cif # several structures, one scene
|
|
24
|
+
$ molstar model.cif emd_1234.map.gz # model + EMDB map
|
|
25
|
+
$ molstar PDBDEV_00000001.cif # integrative (IHM) models, incl. coarse-grained beads
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The command keeps serving while you look at the structures; stop it with Ctrl-C.
|
|
29
|
+
Reloading the browser tab re-reads the files from disk.
|
|
30
|
+
|
|
31
|
+
| Option | |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `-p`, `--port PORT` | listen on a fixed port instead of a random free one |
|
|
34
|
+
| `--no-browser` | only print the URL |
|
|
35
|
+
| `-V`, `--version` | print the molstar-cli and bundled Mol* versions |
|
|
36
|
+
|
|
37
|
+
### Supported formats
|
|
38
|
+
|
|
39
|
+
Anything Mol*'s *Open Files* dialog accepts, detected by file extension, optionally
|
|
40
|
+
wrapped in `.gz` or `.zip`:
|
|
41
|
+
|
|
42
|
+
- **Structures:** mmCIF / PDBx (`.cif`, `.mmcif`, `.mcif`) including IHM integrative
|
|
43
|
+
models, BinaryCIF (`.bcif`), PDB (`.pdb`, `.ent`), PDBQT, PQR, GRO, XYZ, SDF / MOL /
|
|
44
|
+
MOL2, LAMMPS data/dump
|
|
45
|
+
- **Volumes:** CCP4 / MRC / MAP (`.map`, `.mrc`, `.ccp4` — EMDB maps), DSN6 / BRIX,
|
|
46
|
+
DX, Cube, density server CIF, MTZ
|
|
47
|
+
- **Trajectories and topologies:** DCD, XTC, TRR, NetCDF, PSF, PRMTOP, TOP
|
|
48
|
+
- **Other:** PLY / OBJ meshes, MolViewSpec (`.mvsj`, `.mvsx`), Mol* sessions (`.molj`, `.molx`)
|
|
49
|
+
|
|
50
|
+
Unsupported files are skipped with a warning in the Mol* log panel.
|
|
51
|
+
|
|
52
|
+
Maps open at Mol*'s default isovalue (2σ) — the EMDB-recommended contour level is not
|
|
53
|
+
stored in the map file. Adjust it in the Volume panel on the right.
|
|
54
|
+
|
|
55
|
+
### Remote machines
|
|
56
|
+
|
|
57
|
+
With `--no-browser`, or on a Linux machine without a display (e.g. over SSH), `molstar`
|
|
58
|
+
doesn't start a browser; it prints an `ssh -L` command instead:
|
|
59
|
+
|
|
60
|
+
```console
|
|
61
|
+
server$ molstar model.cif
|
|
62
|
+
Mol* viewer: http://127.0.0.1:41235/Xy.../
|
|
63
|
+
On a remote machine? Run `ssh -L 41235:127.0.0.1:41235 server` on your computer, then open the URL above there.
|
|
64
|
+
Press Ctrl-C to stop.
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Use `--port` to keep the same forwarded port between runs.
|
|
68
|
+
|
|
69
|
+
### Security
|
|
70
|
+
|
|
71
|
+
The server listens on `127.0.0.1` only, every URL carries a random token, and only the
|
|
72
|
+
files named on the command line can be read — no directory listing, no other paths.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```console
|
|
77
|
+
$ python -m venv .venv && .venv/bin/pip install -e . pytest
|
|
78
|
+
$ .venv/bin/pytest
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Updating the bundled Mol*
|
|
82
|
+
|
|
83
|
+
The prebuilt viewer from the [`molstar` npm package](https://www.npmjs.com/package/molstar)
|
|
84
|
+
is vendored in `molstar_cli/static/molstar/` (no Node.js needed):
|
|
85
|
+
|
|
86
|
+
```console
|
|
87
|
+
$ python scripts/update_molstar.py 5.11.0
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Check that it loads, then commit the result.
|
|
91
|
+
|
|
92
|
+
### Releasing
|
|
93
|
+
|
|
94
|
+
Create a GitHub release with a tag like `v0.0.2`. The package version is taken from the
|
|
95
|
+
tag, so there is nothing to bump. The *Publish to PyPI* workflow builds and uploads it
|
|
96
|
+
using [trusted publishing](https://docs.pypi.org/trusted-publishers/) (PyPI publisher:
|
|
97
|
+
owner `aozalevsky`, repository `molstar_cli`, workflow `publish.yml`, environment `pypi`).
|
|
98
|
+
|
|
99
|
+
## Citing Mol*
|
|
100
|
+
|
|
101
|
+
If you use Mol* in your work, please cite:
|
|
102
|
+
|
|
103
|
+
> D. Sehnal, S. Bittrich, M. Deshpande, R. Svobodová, K. Berka, V. Bazgier, S. Velankar,
|
|
104
|
+
> S.K. Burley, J. Koča, A.S. Rose. Mol* Viewer: modern web app for 3D visualization and
|
|
105
|
+
> analysis of large biomolecular structures. *Nucleic Acids Research* 49(W1), W431–W437
|
|
106
|
+
> (2021). [doi:10.1093/nar/gkab314](https://doi.org/10.1093/nar/gkab314)
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
MIT. The bundled Mol* viewer is © Mol* contributors, also MIT —
|
|
111
|
+
see [`LICENSE.molstar`](molstar_cli/static/molstar/LICENSE.molstar).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Open local molecular structure and volume files in the Mol* viewer."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
from ._version import __version__ # written from the git tag at build/install time
|
|
6
|
+
except ImportError: # source tree that was never built or installed
|
|
7
|
+
__version__ = "0+unknown"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def molstar_version() -> str:
|
|
11
|
+
"""Version of the bundled Mol* viewer."""
|
|
12
|
+
return (Path(__file__).parent / "static" / "molstar" / "VERSION").read_text().strip()
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.0.1'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 0, 1)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Command-line entry point: ``molstar FILE [FILE ...]``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
import webbrowser
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import __version__, molstar_version
|
|
12
|
+
from .server import MolstarServer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_args(argv: list[str] | None) -> argparse.Namespace:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="molstar",
|
|
18
|
+
description="Open structure and volume files (mmCIF, BinaryCIF, PDB, EMDB maps, ...) "
|
|
19
|
+
"together in one Mol* viewer scene in your browser.",
|
|
20
|
+
)
|
|
21
|
+
parser.add_argument("files", nargs="+", metavar="FILE", help="files to open")
|
|
22
|
+
parser.add_argument("-p", "--port", type=int, default=0, help="port to listen on (default: a random free port)")
|
|
23
|
+
parser.add_argument("--no-browser", action="store_true", help="only print the URL, do not open a browser")
|
|
24
|
+
parser.add_argument("-V", "--version", action="version",
|
|
25
|
+
version=f"molstar-cli {__version__} (Mol* {molstar_version()})")
|
|
26
|
+
return parser.parse_args(argv)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def can_open_browser() -> bool:
|
|
30
|
+
"""Whether webbrowser.open would reach a graphical browser rather than lynx/w3m in this terminal."""
|
|
31
|
+
if sys.platform in ("darwin", "win32") or os.environ.get("BROWSER"):
|
|
32
|
+
return True
|
|
33
|
+
return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv: list[str] | None = None) -> int:
|
|
37
|
+
args = parse_args(argv)
|
|
38
|
+
|
|
39
|
+
bad = False
|
|
40
|
+
for name in args.files:
|
|
41
|
+
path = Path(name)
|
|
42
|
+
if not path.is_file():
|
|
43
|
+
reason = "is a directory" if path.is_dir() else "no such file"
|
|
44
|
+
print(f"molstar: error: {name}: {reason}", file=sys.stderr)
|
|
45
|
+
bad = True
|
|
46
|
+
if bad:
|
|
47
|
+
return 2
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
server = MolstarServer(args.files, port=args.port)
|
|
51
|
+
except OSError as e:
|
|
52
|
+
print(f"molstar: error: cannot listen on port {args.port}: {e.strerror or e}", file=sys.stderr)
|
|
53
|
+
return 1
|
|
54
|
+
|
|
55
|
+
with server:
|
|
56
|
+
port = server.server_address[1]
|
|
57
|
+
print(f"Mol* viewer: {server.url}")
|
|
58
|
+
if args.no_browser or not can_open_browser():
|
|
59
|
+
print(f"On a remote machine? Run `ssh -L {port}:127.0.0.1:{port} {socket.gethostname()}` "
|
|
60
|
+
"on your computer, then open the URL above there.")
|
|
61
|
+
else:
|
|
62
|
+
webbrowser.open(server.url)
|
|
63
|
+
# Flush now: when stdout is a pipe or file it is block-buffered, and the URL
|
|
64
|
+
# would otherwise only appear after the server stops.
|
|
65
|
+
print("Press Ctrl-C to stop.", flush=True)
|
|
66
|
+
try:
|
|
67
|
+
server.serve_forever()
|
|
68
|
+
except KeyboardInterrupt:
|
|
69
|
+
pass
|
|
70
|
+
return 0
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Local HTTP server for the bundled Mol* viewer and the files it should open."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import shutil
|
|
8
|
+
import socketserver
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from urllib.parse import quote, unquote, urlsplit
|
|
14
|
+
|
|
15
|
+
STATIC_DIR = Path(__file__).resolve().parent / "static"
|
|
16
|
+
VIEWER_DIR = STATIC_DIR / "molstar"
|
|
17
|
+
INDEX_HTML = STATIC_DIR / "open.html"
|
|
18
|
+
|
|
19
|
+
CONTENT_TYPES = {
|
|
20
|
+
".html": "text/html; charset=utf-8",
|
|
21
|
+
".js": "text/javascript; charset=utf-8",
|
|
22
|
+
".css": "text/css; charset=utf-8",
|
|
23
|
+
".json": "application/json",
|
|
24
|
+
".ico": "image/x-icon",
|
|
25
|
+
".jpg": "image/jpeg",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MolstarServer(ThreadingHTTPServer):
|
|
30
|
+
"""Serves the viewer and ``files`` on localhost under a random URL token.
|
|
31
|
+
|
|
32
|
+
Only the files passed in are readable; everything else is 403 (wrong token) or 404.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
daemon_threads = True
|
|
36
|
+
# On Windows SO_REUSEADDR lets a second socket bind a port that is already in use.
|
|
37
|
+
allow_reuse_address = sys.platform != "win32"
|
|
38
|
+
|
|
39
|
+
def __init__(self, files: Iterable[str | os.PathLike], host: str = "127.0.0.1", port: int = 0):
|
|
40
|
+
self.files = [Path(f).resolve() for f in files]
|
|
41
|
+
self.token = secrets.token_urlsafe(16)
|
|
42
|
+
super().__init__((host, port), _Handler)
|
|
43
|
+
|
|
44
|
+
def server_bind(self):
|
|
45
|
+
# Skip HTTPServer.server_bind: its socket.getfqdn() reverse DNS lookup can block
|
|
46
|
+
# for ~35 s on macOS, and server_name is only used by CGI handlers.
|
|
47
|
+
socketserver.TCPServer.server_bind(self)
|
|
48
|
+
self.server_name, self.server_port = self.server_address[:2]
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def url(self) -> str:
|
|
52
|
+
host, port = self.server_address[:2]
|
|
53
|
+
return f"http://{host}:{port}/{self.token}/"
|
|
54
|
+
|
|
55
|
+
def manifest(self) -> list[dict[str, str]]:
|
|
56
|
+
return [{"name": f.name, "url": f"files/{i}/{quote(f.name)}"} for i, f in enumerate(self.files)]
|
|
57
|
+
|
|
58
|
+
def handle_error(self, request, client_address):
|
|
59
|
+
# The browser dropping a connection mid-transfer is not worth a traceback.
|
|
60
|
+
if not isinstance(sys.exc_info()[1], ConnectionError):
|
|
61
|
+
super().handle_error(request, client_address)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
65
|
+
server: MolstarServer
|
|
66
|
+
|
|
67
|
+
def do_GET(self):
|
|
68
|
+
path = unquote(urlsplit(self.path).path)
|
|
69
|
+
prefix = f"/{self.server.token}/"
|
|
70
|
+
if not path.startswith(prefix):
|
|
71
|
+
self.send_error(403)
|
|
72
|
+
return
|
|
73
|
+
rest = path[len(prefix):]
|
|
74
|
+
if rest == "":
|
|
75
|
+
self._send_file(INDEX_HTML)
|
|
76
|
+
elif rest == "files.json":
|
|
77
|
+
self._send_bytes(json.dumps(self.server.manifest()).encode(), CONTENT_TYPES[".json"])
|
|
78
|
+
elif rest.startswith("files/"):
|
|
79
|
+
self._send_file(self._listed_file(rest), "application/octet-stream")
|
|
80
|
+
else:
|
|
81
|
+
self._send_file(self._viewer_asset(rest))
|
|
82
|
+
|
|
83
|
+
def _listed_file(self, rest: str) -> Path | None:
|
|
84
|
+
parts = rest.split("/")
|
|
85
|
+
if len(parts) != 3 or not parts[1].isdecimal():
|
|
86
|
+
return None
|
|
87
|
+
index, name = int(parts[1]), parts[2]
|
|
88
|
+
if index >= len(self.server.files) or self.server.files[index].name != name:
|
|
89
|
+
return None
|
|
90
|
+
return self.server.files[index]
|
|
91
|
+
|
|
92
|
+
def _viewer_asset(self, rest: str) -> Path | None:
|
|
93
|
+
try:
|
|
94
|
+
target = (VIEWER_DIR / rest).resolve()
|
|
95
|
+
except (OSError, ValueError):
|
|
96
|
+
return None
|
|
97
|
+
return target if target.is_relative_to(VIEWER_DIR) and target.is_file() else None
|
|
98
|
+
|
|
99
|
+
def _send_file(self, path: Path | None, content_type: str | None = None):
|
|
100
|
+
if path is None:
|
|
101
|
+
self.send_error(404)
|
|
102
|
+
return
|
|
103
|
+
try:
|
|
104
|
+
f = path.open("rb")
|
|
105
|
+
except OSError:
|
|
106
|
+
self.send_error(404)
|
|
107
|
+
return
|
|
108
|
+
with f:
|
|
109
|
+
self._send_headers(os.fstat(f.fileno()).st_size,
|
|
110
|
+
content_type or CONTENT_TYPES.get(path.suffix.lower(), "application/octet-stream"))
|
|
111
|
+
try:
|
|
112
|
+
shutil.copyfileobj(f, self.wfile)
|
|
113
|
+
except ConnectionError:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
def _send_bytes(self, data: bytes, content_type: str):
|
|
117
|
+
self._send_headers(len(data), content_type)
|
|
118
|
+
self.wfile.write(data)
|
|
119
|
+
|
|
120
|
+
def _send_headers(self, length: int, content_type: str):
|
|
121
|
+
self.send_response(200)
|
|
122
|
+
self.send_header("Content-Type", content_type)
|
|
123
|
+
self.send_header("Content-Length", str(length))
|
|
124
|
+
self.send_header("Cache-Control", "no-store")
|
|
125
|
+
self.end_headers()
|
|
126
|
+
|
|
127
|
+
def log_message(self, format, *args):
|
|
128
|
+
pass
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 - now, Mol* contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
5.11.0
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|