xcursor-format 0.0.0__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.
@@ -0,0 +1,38 @@
1
+ name: Publish to PyPI and Create Release
2
+ on:
3
+ push:
4
+ tags: [ "v*" ]
5
+
6
+ jobs:
7
+ build-and-publish:
8
+ runs-on: ubuntu-latest
9
+ permissions:
10
+ id-token: write
11
+ environment: pypi
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: '3.x'
17
+ - run: |
18
+ python -m pip install --upgrade pip
19
+ pip install build
20
+ - run: python -m build
21
+ - uses: pypa/gh-action-pypi-publish@release/v1
22
+
23
+ create-release:
24
+ runs-on: ubuntu-latest
25
+ needs: build-and-publish
26
+ permissions:
27
+ contents: write
28
+ steps:
29
+ - uses: actions/github-script@v6
30
+ with:
31
+ script: |
32
+ github.rest.repos.createRelease({
33
+ owner: context.repo.owner,
34
+ repo: context.repo.repo,
35
+ tag_name: context.ref.replace('refs/tags/', ''),
36
+ name: context.ref.replace('refs/tags/', ''),
37
+ generate_release_notes: true
38
+ })
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 russiandesman
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,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: xcursor-format
3
+ Version: 0.0.0
4
+ Summary: Library and CLI tool for Xcursor files
5
+ Author-email: russiandesman <des.maryin@googlemail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: Pillow>=10
11
+ Dynamic: license-file
12
+
13
+ # xcursor-format
14
+
15
+ Library to work with XCursor files
16
+
17
+ # xcursor_theme_leftifier
18
+
19
+ Take cursor theme you like (look at /usr/share/icons/), make it left hand friendly.
20
+
21
+ Usage:
22
+
23
+ ```
24
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test
25
+ ```
26
+
27
+ Advanced usage (when you know exactly which cursors need to be flipped and not satisfied with automation results):
28
+
29
+ ```
30
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test --files=left_ptr,left_ptr_watch
31
+ ```
32
+
33
+ # xcur2png
34
+
35
+ Drop-in replacement for great and misterious xcur2png (https://github.com/eworm-de/xcur2png)
36
+
37
+ Usage:
38
+
39
+ ```
40
+ xcur2png --show-hot --outdir=test /usr/share/icons/DMZ-Black/cursors/cross
41
+ ```
@@ -0,0 +1,29 @@
1
+ # xcursor-format
2
+
3
+ Library to work with XCursor files
4
+
5
+ # xcursor_theme_leftifier
6
+
7
+ Take cursor theme you like (look at /usr/share/icons/), make it left hand friendly.
8
+
9
+ Usage:
10
+
11
+ ```
12
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test
13
+ ```
14
+
15
+ Advanced usage (when you know exactly which cursors need to be flipped and not satisfied with automation results):
16
+
17
+ ```
18
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test --files=left_ptr,left_ptr_watch
19
+ ```
20
+
21
+ # xcur2png
22
+
23
+ Drop-in replacement for great and misterious xcur2png (https://github.com/eworm-de/xcur2png)
24
+
25
+ Usage:
26
+
27
+ ```
28
+ xcur2png --show-hot --outdir=test /usr/share/icons/DMZ-Black/cursors/cross
29
+ ```
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "setuptools-scm>=8"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xcursor-format"
7
+ dynamic = ["version"]
8
+ description = "Library and CLI tool for Xcursor files"
9
+ readme = "README.md"
10
+ authors = [{name = "russiandesman", email = "des.maryin@googlemail.com"}]
11
+ license = {text = "MIT"}
12
+ requires-python = ">=3.10"
13
+ dependencies = ["Pillow>=10"]
14
+
15
+ [project.scripts]
16
+ xcur2png = "xcur2png:main"
17
+ xcursor_theme_leftifier = "xcursor_theme_leftifier:main"
18
+
19
+ [tool.setuptools]
20
+ py-modules = ["xcursor_format", "xcur2png", "xcursor_theme_leftifier"]
21
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env python3
2
+ """Extract XCursor files into PNG images + xcursorgen-compatible config."""
3
+ """drop-in replacement for xcur2png (https://github.com/eworm-de/xcur2png)"""
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+ from PIL import Image
8
+
9
+ from xcursor_format import XCursor
10
+
11
+ def build_png(xcursor_frame, show_hotpoint):
12
+ def unpremultiply(argb):
13
+ def cap(color, a):
14
+ return 0 if a == 0 else min(255, color * 255 // a)
15
+ b = (argb >> 0) & 0xFF
16
+ g = (argb >> 8) & 0xFF
17
+ r = (argb >> 16) & 0xFF
18
+ a = (argb >> 24) & 0xFF
19
+ return cap(r, a), cap(g, a), cap(b, a), a
20
+
21
+ img = Image.new("RGBA", (xcursor_frame.width, xcursor_frame.height))
22
+ img.putdata([unpremultiply(p) for p in xcursor_frame.pixels])
23
+ if show_hotpoint:
24
+ img.putpixel((xcursor_frame.xhot, xcursor_frame.yhot),(255, 0, 0, 255))
25
+
26
+ return img
27
+
28
+ def main():
29
+ ap = argparse.ArgumentParser(description="Extract XCursor to PNGs")
30
+ ap.add_argument("cursor", help="Input XCursor file")
31
+ ap.add_argument("-o", "--outdir", help="Output directory (default: next to cursor file)")
32
+ ap.add_argument("-c", "--conf", help="Config file path (default: <cursor>.conf)")
33
+ ap.add_argument("-s", "--suffix", type=int, default=0, help="Starting numeric suffix (default: 0)")
34
+ ap.add_argument("-n", "--dry-run", action="store_true")
35
+ ap.add_argument("-x", "--show-hot", action="store_true")
36
+ args = ap.parse_args()
37
+
38
+ cursor_path = Path(args.cursor)
39
+ outdir = Path(args.outdir) if args.outdir else cursor_path.parent
40
+ conf_path = Path(args.conf) if args.conf else cursor_path.with_suffix(".conf")
41
+ cursor_bytes = cursor_path.read_bytes()
42
+ xcursor = XCursor(cursor_bytes)
43
+
44
+ if not args.dry_run:
45
+ outdir.mkdir(parents=True, exist_ok=True)
46
+
47
+ suffix = args.suffix
48
+ conf_lines = []
49
+
50
+ for image in xcursor.images:
51
+ png_name = f"{cursor_path.stem}_{suffix:03d}.png"
52
+ png_path = outdir / png_name
53
+
54
+ try:
55
+ rel_path = png_path.relative_to(conf_path.parent)
56
+ except ValueError:
57
+ rel_path = png_path
58
+
59
+ conf_lines.append(f"{image.header.subtype} {image.body.xhot} {image.body.yhot} {rel_path} {image.body.delay}")
60
+
61
+ if not args.dry_run:
62
+ img = build_png(image.body, args.show_hot)
63
+ img.save(png_path)
64
+ print(f" {png_path}")
65
+
66
+ suffix += 1
67
+
68
+ if not args.dry_run:
69
+ conf_path.write_text("\n".join(conf_lines) + "\n")
70
+ print(f"Config: {conf_path}")
71
+ else:
72
+ print("\n".join(conf_lines))
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: xcursor-format
3
+ Version: 0.0.0
4
+ Summary: Library and CLI tool for Xcursor files
5
+ Author-email: russiandesman <des.maryin@googlemail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: Pillow>=10
11
+ Dynamic: license-file
12
+
13
+ # xcursor-format
14
+
15
+ Library to work with XCursor files
16
+
17
+ # xcursor_theme_leftifier
18
+
19
+ Take cursor theme you like (look at /usr/share/icons/), make it left hand friendly.
20
+
21
+ Usage:
22
+
23
+ ```
24
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test
25
+ ```
26
+
27
+ Advanced usage (when you know exactly which cursors need to be flipped and not satisfied with automation results):
28
+
29
+ ```
30
+ xcursor_theme_leftifier.py --input=/usr/share/icons/DMZ-Black --output=test --files=left_ptr,left_ptr_watch
31
+ ```
32
+
33
+ # xcur2png
34
+
35
+ Drop-in replacement for great and misterious xcur2png (https://github.com/eworm-de/xcur2png)
36
+
37
+ Usage:
38
+
39
+ ```
40
+ xcur2png --show-hot --outdir=test /usr/share/icons/DMZ-Black/cursors/cross
41
+ ```
@@ -0,0 +1,14 @@
1
+ .gitignore
2
+ LICENSE
3
+ README.md
4
+ pyproject.toml
5
+ xcur2png.py
6
+ xcursor_format.py
7
+ xcursor_theme_leftifier.py
8
+ .github/workflows/publish.yml
9
+ xcursor_format.egg-info/PKG-INFO
10
+ xcursor_format.egg-info/SOURCES.txt
11
+ xcursor_format.egg-info/dependency_links.txt
12
+ xcursor_format.egg-info/entry_points.txt
13
+ xcursor_format.egg-info/requires.txt
14
+ xcursor_format.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ xcur2png = xcur2png:main
3
+ xcursor_theme_leftifier = xcursor_theme_leftifier:main
@@ -0,0 +1 @@
1
+ Pillow>=10
@@ -0,0 +1,3 @@
1
+ xcur2png
2
+ xcursor_format
3
+ xcursor_theme_leftifier
@@ -0,0 +1,174 @@
1
+ from dataclasses import dataclass, astuple
2
+ import struct
3
+
4
+ class XCursorBase:
5
+ @classmethod
6
+ def raw_unpack(cls, data: bytes, offset: int, fmt: str):
7
+ required_size = struct.calcsize(fmt)
8
+ available_size = len(data) - offset
9
+ if available_size < required_size:
10
+ raise ValueError(f"Processing {cls.__name__}; required {required_size} bytes, only {available_size} available")
11
+ fields = struct.unpack_from(fmt, data, offset)
12
+ return fields, offset + required_size
13
+
14
+ @classmethod
15
+ def unpack(cls, data: bytes, offset: int, fmt: str | None = None):
16
+ if fmt is None:
17
+ fmt = cls.FMT
18
+ fields, new_offset = cls.raw_unpack(data, offset, fmt)
19
+ return cls(*fields), new_offset
20
+
21
+ def serialize(self):
22
+ return struct.pack(self.FMT, *astuple(self))
23
+
24
+
25
+ @dataclass
26
+ class XCursorHdr(XCursorBase):
27
+ EXPECTED_MAGIC = 0x72756358 # "Xcur"
28
+ FMT = "<IIII"
29
+ magic: int
30
+ size: int
31
+ version: int
32
+ toc_count: int
33
+
34
+ @classmethod
35
+ def unpack(cls, data: bytes, offset: int):
36
+ instance, new_offset = super().unpack(data, offset)
37
+ if instance.magic != cls.EXPECTED_MAGIC:
38
+ raise ValueError(f"Invalid magic number: {instance.magic:#x}, expected {cls.EXPECTED_MAGIC:#x}")
39
+ return instance, new_offset
40
+
41
+ def __repr__(self):
42
+ return f"[magic={self.magic:#x}, sz={self.size}, ver={self.version:#x}, toc_sz={self.toc_count}]"
43
+
44
+
45
+ @dataclass
46
+ class XCursorTocEntry(XCursorBase):
47
+ FMT = "<III"
48
+ type: int
49
+ subtype: int
50
+ position: int
51
+
52
+ def __repr__(self):
53
+ return f"[type={self.type:#x}, sub={self.subtype:#x}, filepos={self.position}]"
54
+
55
+
56
+ @dataclass
57
+ class XCursorChunkHdr(XCursorBase):
58
+ COMMENT = 0xfffd0001
59
+ IMAGE = 0xfffd0002
60
+ FMT = "<IIII"
61
+ chunk_len: int
62
+ type: int
63
+ subtype: int
64
+ version: int
65
+
66
+ def __repr__(self):
67
+ return f"[len={self.chunk_len}, type={self.type:#x}, sub={self.subtype:#x}, ver={self.version:#x}]"
68
+
69
+
70
+ @dataclass
71
+ class XCursorChunkComment(XCursorBase):
72
+ FMT = "<I"
73
+ str_len: int
74
+ string: str
75
+
76
+ @classmethod
77
+ def unpack(cls, data: bytes, offset: int):
78
+ instance, new_offset = super().unpack(data, offset)
79
+ string_bytes, new_offset = cls.raw_unpack(data, new_offset, f"{instance.str_len}s")
80
+ instance.string = string_bytes.decode('utf-8')
81
+ return instance, new_offset
82
+
83
+ def __repr__(self):
84
+ return f"[len={self.str_len}, s='{self.string}']"
85
+
86
+ def serialize(self):
87
+ return struct.pack(self.FMT + f"{self.str_len}s", self.str_len, self.string.encode('utf-8'))
88
+
89
+
90
+ @dataclass
91
+ class XCursorChunkImage(XCursorBase):
92
+ FMT = "<IIIII" # followed by "157I" for 157 pixels image
93
+ width: int
94
+ height: int
95
+ xhot: int
96
+ yhot: int
97
+ delay: int
98
+ pixels: tuple[int, ...] = ()
99
+
100
+ @classmethod
101
+ def unpack(cls, data: bytes, offset: int):
102
+ instance, new_offset = super().unpack(data, offset)
103
+ instance.pixels, new_offset = cls.raw_unpack(data, new_offset, f"{instance.width * instance.height}I")
104
+ return instance, new_offset
105
+
106
+ def __repr__(self):
107
+ return f"[{self.width}x{self.height} with {self.xhot}x{self.yhot}, delay={self.delay}, {len(self.pixels)} pixels]"
108
+
109
+ def serialize(self):
110
+ return struct.pack(self.FMT + f"{self.width * self.height}I", *(astuple(self)[:-1] + self.pixels))
111
+
112
+
113
+ @dataclass
114
+ class XCursorChunk:
115
+ header: XCursorChunkHdr
116
+ body: XCursorChunkComment | XCursorChunkImage
117
+
118
+ @classmethod
119
+ def unpack(cls, data: bytes, offset: int):
120
+ header, body_offset = XCursorChunkHdr.unpack(data, offset)
121
+ if header.type == XCursorChunkHdr.COMMENT:
122
+ body, _ = XCursorChunkComment.unpack(data, body_offset)
123
+ elif header.type == XCursorChunkHdr.IMAGE:
124
+ body, _ = XCursorChunkImage.unpack(data, body_offset)
125
+ else:
126
+ raise ValueError(f"Unknown chunk type: {header.type:#x}")
127
+
128
+ return cls(header, body)
129
+
130
+ def __repr__(self):
131
+ return f"[{self.header}, {self.body}]"
132
+
133
+ def serialize(self):
134
+ return self.header.serialize() + self.body.serialize()
135
+
136
+
137
+ class XCursor:
138
+ def __init__(self, data: bytes):
139
+ self.toc = []
140
+ self.chunks = []
141
+ self.hdr, offset = XCursorHdr.unpack(data, 0)
142
+ for i in range(self.hdr.toc_count):
143
+ toc_item, offset = XCursorTocEntry.unpack(data, offset)
144
+ self.toc.append(toc_item)
145
+ chunk = XCursorChunk.unpack(data, toc_item.position)
146
+ self.chunks.append(chunk)
147
+
148
+ def serialize(self):
149
+ result = self.hdr.serialize()
150
+ for toc_item in self.toc:
151
+ result += toc_item.serialize()
152
+ for chunk in self.chunks:
153
+ result += chunk.serialize()
154
+ return result
155
+
156
+ @property
157
+ def images(self):
158
+ for chunk in self.chunks:
159
+ if isinstance(chunk.body, XCursorChunkImage):
160
+ yield chunk
161
+
162
+ @property
163
+ def largest_image(self):
164
+ return max(self.images, key=lambda chunk: chunk.body.width)
165
+
166
+ def flip(self):
167
+ def flip_horizontal(pixels: tuple[int, ...], width: int):
168
+ for i in range(0, len(pixels), width):
169
+ yield from reversed(pixels[i:i+width])
170
+ for chunk in self.images:
171
+ chunk.body.pixels = tuple(flip_horizontal(chunk.body.pixels, chunk.body.width))
172
+ chunk.body.xhot = chunk.body.width - 1 - chunk.body.xhot
173
+
174
+
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env python3
2
+ """Make cursor theme left-handed. Uses own heuristics to choose which cursors to flip"""
3
+ """Allows overriding the heuristics by providing own comma-separated --files list"""
4
+
5
+ import argparse
6
+ import shutil
7
+ from configparser import ConfigParser
8
+ from pathlib import Path
9
+ from xcursor_format import XCursor
10
+
11
+ ALWAYS_MIRROR = {
12
+ "hand1", "hand2", "grab", "openhand", "closedhand", "grabbing",
13
+ "pointer", "pointing_hand",
14
+ "dnd-ask",
15
+ }
16
+
17
+ NEVER_MIRROR = {
18
+ "sb_left_arrow", "sb_right_arrow",
19
+ "left-arrow", "right-arrow",
20
+ "left_tee", "right_tee",
21
+ "ul_angle", "ur_angle", "ll_angle", "lr_angle",
22
+ "right_ptr",
23
+ }
24
+
25
+ def should_mirror(name: str, xcursor: XCursor, user_list: set | None) -> bool:
26
+ if user_list is not None:
27
+ return name in user_list
28
+ if name in NEVER_MIRROR:
29
+ return False
30
+ if name in ALWAYS_MIRROR:
31
+ return True
32
+ frame = xcursor.largest_image.body
33
+ return frame.xhot / frame.width < 0.4
34
+
35
+ def main():
36
+ parser = argparse.ArgumentParser()
37
+ parser.add_argument('--input', '-i', type=Path, required=True)
38
+ parser.add_argument('--output', '-o', type=Path, required=True)
39
+ parser.add_argument('--files', type=lambda s: set(s.split(',')))
40
+
41
+ args = parser.parse_args()
42
+ input_dir: Path = args.input
43
+ output_dir: Path = args.output
44
+
45
+ if output_dir.exists():
46
+ shutil.rmtree(output_dir)
47
+ shutil.copytree(args.input, args.output, symlinks=True)
48
+
49
+ for path in (output_dir / "cursors").iterdir():
50
+ if path.is_file() and not path.is_symlink():
51
+ print(f"Processing {path}")
52
+ name = path.stem
53
+ try:
54
+ xcursor = XCursor(path.read_bytes())
55
+ if should_mirror(name, xcursor, args.files):
56
+ xcursor.flip()
57
+ path.write_bytes(xcursor.serialize())
58
+ print("Flipped")
59
+ else:
60
+ print("Skipped")
61
+ except Exception as e:
62
+ print("Irrelevant")
63
+
64
+ cfg = ConfigParser()
65
+ cfg.read(output_dir / "index.theme")
66
+ lh_theme = f"[LeftHanded] {cfg['Icon Theme']['name']}"
67
+ cfg['Icon Theme']['name'] = lh_theme
68
+ with open(output_dir / "index.theme", "w") as f:
69
+ cfg.write(f, space_around_delimiters=False)
70
+
71
+ if __name__ == '__main__':
72
+ main()