├── .github
└── ISSUE_TEMPLATE
│ ├── bug-report.md
│ └── feature_request.md
├── .gitignore
├── .idea
├── .gitignore
├── CursorCreate.iml
├── inspectionProfiles
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── CursorCreate.spec
├── CursorCreate
├── __init__.py
├── cursorcreate.py
├── gui
│ ├── QtKit.py
│ ├── __init__.py
│ ├── cursorhotspotedit.py
│ ├── cursorpreviewdialog.py
│ ├── cursorselector.py
│ ├── cursorthememaker.py
│ ├── cursorviewedit.py
│ ├── cursorviewer.py
│ └── layouts.py
└── lib
│ ├── __init__.py
│ ├── ani_format.py
│ ├── cur_format.py
│ ├── cur_theme.py
│ ├── cursor.py
│ ├── cursor_util.py
│ ├── format_core.py
│ ├── theme_util.py
│ └── xcur_format.py
├── LICENSE
├── README.md
├── build_executable.py
├── icon_linux.xpm
├── icon_mac.icns
├── icon_windows.ico
├── pyproject.toml
├── requirements.txt
└── setup.py
/.github/ISSUE_TEMPLATE/bug-report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug Report
3 | about: Create a report to make CursorCreate better!
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe The Bug:**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected Behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots or Terminal Output (Optional)**
24 | If applicable, add screenshots or terminal output to help explain your problem.
25 | ```
26 | Include terminal output in a code block, like this.
27 | ```
28 |
29 | **Desktop (please complete the following information):**
30 | - OS: [Windows, Mac OS, Linux, etc.]
31 | - CursorCreate Version: [e.g. v1.3.1]
32 | - Install Method: [e.g. pre-packaged binary, pip, source]
33 |
34 | **Additional Context: **
35 | Add any other context about the problem here.
36 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for CursorCreate
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered (Optional)**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context (Optional)**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | venv/
2 | __pycache__/
3 | build/
4 | dist/
5 | .idea
6 | # Nuitka stuff...
7 | cursorcreate.dist
8 | cursorcreate.build
9 | cursorcreate.bin
10 | # PyPI Build Stuff...
11 | CursorCreate.egg-info/
12 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /workspace.xml
--------------------------------------------------------------------------------
/.idea/CursorCreate.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CursorCreate.spec:
--------------------------------------------------------------------------------
1 | # -*- mode: python ; coding: utf-8 -*-
2 | import sys
3 | from pathlib import Path
4 |
5 | block_cipher = None
6 | spec_root = Path(SPECPATH).resolve()
7 |
8 | if(sys.platform.startswith("win")):
9 | icon = str(spec_root / "icon_windows.ico")
10 | else:
11 | icon = None
12 |
13 | a = Analysis(
14 | ['CursorCreate/cursorcreate.py'],
15 | pathex = [str(spec_root)],
16 | hiddenimports = [],
17 | hookspath = [],
18 | runtime_hooks = [],
19 | excludes=['FixTk', 'tcl', 'tk', '_tkinter', 'tkinter', 'Tkinter'],
20 | win_no_prefer_redirects = False,
21 | win_private_assemblies = False,
22 | cipher = block_cipher,
23 | noarchive = False
24 | )
25 |
26 | pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
27 |
28 | exe = EXE(
29 | pyz,
30 | a.scripts,
31 | a.binaries,
32 | a.zipfiles,
33 | a.datas,
34 | [],
35 | name = 'CursorCreate',
36 | debug = False,
37 | bootloader_ignore_signals = False,
38 | strip = False,
39 | upx = True,
40 | upx_exclude = [],
41 | runtime_tmpdir = None,
42 | console = False,
43 | icon=icon
44 | )
45 |
46 | if(sys.platform.startswith("darwin")):
47 | app = BUNDLE(
48 | exe,
49 | name="CursorCreate.app",
50 | icon=str(spec_root / "icon_mac.icns"),
51 | bundle_identifier=None
52 | )
53 |
54 |
55 |
--------------------------------------------------------------------------------
/CursorCreate/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isaacrobinson2000/CursorCreate/248a0863a4ef69cf32d608a661f1d97cd59afe32/CursorCreate/__init__.py
--------------------------------------------------------------------------------
/CursorCreate/cursorcreate.py:
--------------------------------------------------------------------------------
1 | """
2 | The main entry package for running CursorMaker, provides the CLI interface and handles launching the GUI when
3 | available...
4 | """
5 |
6 | # TODO: Add progress bars to things...
7 |
8 | import sys
9 | from pathlib import Path
10 |
11 | # We try to import lib for CursorCreate, if it fails we attempt to add our parent's parent to the path and try again.
12 | # This allows for execution via the command line.
13 | try:
14 | from CursorCreate.lib import theme_util
15 | except ImportError as exp:
16 | sys.path.append(str(Path(__file__).resolve().parent.parent))
17 | from CursorCreate.lib import theme_util
18 |
19 | # Attempt to import the gui, if it fails(gui packages missing) set the module to none to let methods below know...
20 | try:
21 | from CursorCreate.gui.cursorthememaker import launch_gui
22 | except ImportError as exp:
23 | print(repr(exp))
24 | launch_gui = None
25 |
26 |
27 | def print_help():
28 | """
29 | Print the usage info for CursorMaker to the command line.
30 | """
31 | print("Cursor Theme Maker")
32 | print("Usage:")
33 | print("No arguments: Launch the GUI")
34 | print("'--help': Display help")
35 | print(
36 | "'--build FILE1 FILE2 ...': Build cursor projects from the command line \n"
37 | "by passing the json files of the projects..."
38 | )
39 | print(
40 | "'--open FILE': Open the specified cursor project in the GUI by providing the json file..."
41 | )
42 | # TODO: print("'--convert INPUT_FILE OUTPUT_FILE FORMAT': Convert")
43 |
44 |
45 | def main():
46 | """
47 | Main method of the cursor maker program. Parses the first flag and figures out what to do based on it...
48 | """
49 | args = sys.argv[1:]
50 |
51 | if len(args) == 0:
52 | # No arguments, launch the gui if possible
53 | if launch_gui is not None:
54 | launch_gui(None)
55 | else:
56 | print("Unable to import and run gui, check if PySide2 is installed...")
57 | print_help()
58 | return
59 |
60 | # --help, print the help info...
61 | if args[0] == "--help":
62 | print_help()
63 | # --open, grab next argument, and attempt to have gui open it...
64 | elif args[0] == "--open":
65 | if len(args) > 1:
66 | if launch_gui is not None:
67 | launch_gui(args[1])
68 | else:
69 | print("Unable to import and run gui, check if PySide2 is installed...")
70 | else:
71 | print("No file provided...")
72 | launch_gui(None)
73 | # --build, load in the project file and build the theme in place using utils api...
74 | elif args[0] == "--build":
75 | for config_file in args[1:]:
76 | try:
77 | config_path = Path(config_file).resolve()
78 | metadata, fc_data = theme_util.load_project(config_path)
79 | fc_data = {name: cursor for name, (cur_path, cursor) in fc_data.items()}
80 | theme_util.build_theme(
81 | config_path.parent.name,
82 | config_path.parent.parent,
83 | metadata,
84 | fc_data,
85 | )
86 | except Exception as e:
87 | print(e)
88 | raise e
89 | print("Build Successful!")
90 | else:
91 | # Rogue arguments or flags passed, just print help...
92 | print_help()
93 |
94 |
95 | if __name__ == "__main__":
96 | main()
97 |
--------------------------------------------------------------------------------
/CursorCreate/gui/QtKit.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | from typing import Any
4 |
5 | # Change Qt Implementation here...
6 | if("PYTHON_QT_LIB" in os.environ):
7 | val = os.environ["PYTHON_QT_LIB"]
8 | # We have to hard code imports for nuitka...
9 | # this forces nuitka to look for Qt and include it.
10 | if(val == "PySide2"):
11 | from PySide2 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebEngineCore
12 | elif(val == "PyQt6"):
13 | from PyQt6 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebEngineCore
14 | elif(val == "PyQt5"):
15 | from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebEngineCore
16 | else:
17 | from PySide6 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebEngineCore
18 | else:
19 | # Load the Qt Implementation dynamically in all other cases...
20 | _QT_IMPLEMENTATIONS = ["PySide6", "PySide2", "PyQt6", "PyQt5"]
21 | _SELECTED_QT_IMPL = None
22 |
23 | for impl_name in _QT_IMPLEMENTATIONS:
24 | try:
25 | _SELECTED_QT_IMPL = __import__(impl_name, globals(), locals(), [], 0)
26 | break
27 | except ImportError:
28 | continue
29 |
30 | if(_SELECTED_QT_IMPL is None):
31 | raise ImportError("Unable to find a Python Qt library to use!")
32 |
33 | __name__ = _SELECTED_QT_IMPL.__name__
34 |
35 | def __dir__() -> list:
36 | return dir(_SELECTED_QT_IMPL)
37 |
38 | def __getattr__(name: str) -> Any:
39 | return getattr(_SELECTED_QT_IMPL, name)
40 |
41 |
42 | # Keep qt from freezing on MacOS...
43 | if(sys.platform.startswith("darwin")):
44 | os.environ["QT_MAC_WANTS_LAYER"] = "1"
--------------------------------------------------------------------------------
/CursorCreate/gui/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isaacrobinson2000/CursorCreate/248a0863a4ef69cf32d608a661f1d97cd59afe32/CursorCreate/gui/__init__.py
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorhotspotedit.py:
--------------------------------------------------------------------------------
1 | from typing import Tuple
2 |
3 | import numpy as np
4 | from PIL import Image
5 | from PIL.ImageQt import toqpixmap
6 |
7 | from CursorCreate.gui.QtKit import QtCore, QtGui, QtWidgets
8 |
9 | from CursorCreate.gui.cursorpreviewdialog import CursorPreviewDialog
10 | from CursorCreate.gui.layouts import FlowLayout
11 | from CursorCreate.lib.cursor import AnimatedCursor, Cursor, CursorIcon
12 |
13 | Signal = getattr(QtCore, "Signal", getattr(QtCore, "pyqtSignal", None))
14 |
15 | class CursorHotspotWidget(QtWidgets.QWidget):
16 | VIEW_SIZE = (64, 64)
17 |
18 | userHotspotChange = Signal((int, int))
19 |
20 | def __init__(
21 | self, parent=None, cursor: AnimatedCursor = None, frame=0, *args, **kwargs
22 | ):
23 | super().__init__(parent, *args, **kwargs)
24 | self._frame = 0
25 | self._frame_img = None
26 | self._pressed = False
27 |
28 | if (cursor is None) or (len(cursor) == 0):
29 | tmp_img = Image.fromarray(np.zeros(self.VIEW_SIZE + (4,), dtype=np.uint8))
30 | tmp_cursor = Cursor([CursorIcon(tmp_img, 0, 0)])
31 | self._cursor = AnimatedCursor([tmp_cursor], [100])
32 | else:
33 | self._cursor = cursor
34 | self._cursor.normalize([self.VIEW_SIZE])
35 |
36 | self.__painter = QtGui.QPainter()
37 | self.frame = frame
38 | self.setCursor(QtCore.Qt.CrossCursor)
39 |
40 | self.setMinimumSize(QtCore.QSize(*self.VIEW_SIZE))
41 | self.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
42 | self.resize(self.minimumSize())
43 |
44 | def paintEvent(self, event: QtGui.QPaintEvent):
45 | self.__painter.begin(self)
46 |
47 | self.__painter.setPen(QtGui.QColor("black"))
48 | self.__painter.setBrush(QtGui.QColor("red"))
49 |
50 | self.__painter.drawPixmap(0, 0, self._frame_img)
51 |
52 | hotspot = QtCore.QPoint(*self.hotspot)
53 |
54 | self.__painter.setPen(QtGui.QColor(0, 0, 0, 150))
55 | self.__painter.setBrush(QtGui.QColor(255, 0, 0, 100))
56 | self.__painter.drawEllipse(hotspot, 4, 4)
57 |
58 | self.__painter.setPen(QtGui.QColor(0, 0, 255, 255))
59 | self.__painter.setBrush(QtGui.QColor(0, 0, 255, 255))
60 | self.__painter.drawEllipse(hotspot, 1, 1)
61 |
62 | self.__painter.end()
63 |
64 | def sizeHint(self) -> QtCore.QSize:
65 | return QtCore.QSize(*self.VIEW_SIZE)
66 |
67 | def mousePressEvent(self, event: QtGui.QMouseEvent):
68 | self._pressed = True
69 |
70 | def mouseMoveEvent(self, event: QtGui.QMouseEvent):
71 | if self._pressed:
72 | x, y = event.x(), event.y()
73 | self.hotspot = x, y
74 | self.userHotspotChange.emit(x, y)
75 |
76 | def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
77 | if self._pressed:
78 | self.mouseMoveEvent(event)
79 | self._pressed = False
80 |
81 | @property
82 | def frame(self) -> int:
83 | return self._frame
84 |
85 | @frame.setter
86 | def frame(self, value: int):
87 | if 0 <= value < len(self._cursor):
88 | self._frame = value
89 | self._frame_img = toqpixmap(
90 | self._cursor[self._frame][0][self.VIEW_SIZE].image
91 | )
92 | self.update()
93 | else:
94 | raise ValueError(
95 | f"The frame must land within length of the animated cursor!"
96 | )
97 |
98 | @property
99 | def hotspot(self) -> Tuple[int, int]:
100 | return self._cursor[self._frame][0][self.VIEW_SIZE].hotspot
101 |
102 | @hotspot.setter
103 | def hotspot(self, value: Tuple[int, int]):
104 | if not (isinstance(value, Tuple) and len(value) == 2):
105 | raise ValueError("Not a coordinate pair!")
106 |
107 | value = min(max(0, value[0]), self.VIEW_SIZE[0] - 1), min(
108 | max(0, value[1]), self.VIEW_SIZE[1] - 1
109 | )
110 |
111 | for size in self._cursor[self._frame][0]:
112 | x_rat, y_rat = size[0] / self.VIEW_SIZE[0], size[1] / self.VIEW_SIZE[1]
113 | x_hot, y_hot = int(value[0] * x_rat), int(value[1] * y_rat)
114 |
115 | self._cursor[self._frame][0][size].hotspot = x_hot, y_hot
116 |
117 | self.update()
118 |
119 | @property
120 | def current_cursor(self) -> AnimatedCursor:
121 | return self._cursor
122 |
123 |
124 | class CursorEditWidget(QtWidgets.QFrame):
125 | userDelayChange = Signal((int,))
126 | userHotspotChange = Signal((int, int))
127 |
128 | def __init__(
129 | self, parent=None, cursor: AnimatedCursor = None, frame=0, *args, **kwargs
130 | ):
131 | super().__init__(parent, *args, **kwargs)
132 |
133 | self._main_layout = QtWidgets.QVBoxLayout(self)
134 | self._hotspot_picker = CursorHotspotWidget(cursor=cursor, frame=frame)
135 | self._delay_adjuster = QtWidgets.QSpinBox()
136 | self._delay_adjuster.setRange(0, 0xFFFF)
137 | self._delay_adjuster.setSingleStep(1)
138 |
139 | self._frame = QtWidgets.QFrame()
140 | self._f_lay = QtWidgets.QVBoxLayout()
141 | self._f_lay.setContentsMargins(0, 0, 0, 0)
142 | self._f_lay.addWidget(self._hotspot_picker)
143 | self._frame.setLayout(self._f_lay)
144 | self._frame.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Sunken)
145 | self._frame.setSizePolicy(
146 | QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed
147 | )
148 |
149 | self._main_layout.addWidget(self._frame)
150 | self._main_layout.setAlignment(self._frame, QtCore.Qt.AlignHCenter)
151 | self._main_layout.addWidget(self._delay_adjuster)
152 |
153 | self.setLayout(self._main_layout)
154 | self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Raised)
155 |
156 | # Copy properties from the hotspot picking widget...
157 | self._hotspot_picker.userHotspotChange.connect(
158 | lambda x, y: self.userHotspotChange.emit(x, y)
159 | )
160 |
161 | # Update the delay value...
162 | self.delay = self.delay
163 | self._delay_adjuster.setValue(self.delay)
164 |
165 | # Connect spin box to delay value
166 | self._delay_adjuster.valueChanged.connect(self._change_delay)
167 |
168 | def _change_delay(self, value: int):
169 | self.delay = value
170 | self.userDelayChange.emit(self.delay)
171 |
172 | @property
173 | def current_cursor(self) -> AnimatedCursor:
174 | return self._hotspot_picker.current_cursor
175 |
176 | @property
177 | def hotspot(self) -> Tuple[int, int]:
178 | return self._hotspot_picker.hotspot
179 |
180 | @hotspot.setter
181 | def hotspot(self, value: Tuple[int, int]):
182 | self._hotspot_picker.hotspot = value
183 |
184 | @property
185 | def frame(self):
186 | return self._hotspot_picker.frame
187 |
188 | @frame.setter
189 | def frame(self, value: int):
190 | self._hotspot_picker.frame = value
191 | self.delay = self.delay
192 |
193 | @property
194 | def delay(self) -> int:
195 | return self.current_cursor[self.frame][1]
196 |
197 | @delay.setter
198 | def delay(self, value: int):
199 | if not (0 <= value < 0xFFFF and isinstance(value, int)):
200 | return
201 |
202 | self._delay_adjuster.setValue(value)
203 | self.current_cursor[self.frame] = (self.current_cursor[self.frame][0], value)
204 |
205 |
206 | class HotspotEditDialog(QtWidgets.QDialog):
207 | CURS_PER_LINE = 5
208 |
209 | def __init__(self, parent=None, cursor: AnimatedCursor = None):
210 | super().__init__(parent)
211 | super().setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowCloseButtonHint)
212 |
213 | self._outer_layout = QtWidgets.QVBoxLayout(self)
214 | self._inner_layout = FlowLayout()
215 | self._in_scroll_wid = QtWidgets.QWidget()
216 | self._scroll_area = QtWidgets.QScrollArea()
217 | self._scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
218 | self._scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
219 |
220 | self._info_text = "Modify cursor hotspots below: "
221 | self._info_label = QtWidgets.QLabel(self._info_text)
222 |
223 | if (cursor is None) or (len(cursor) == 0):
224 | self._hotspot_picker_lst = [CursorEditWidget()]
225 | self._cursor = self._hotspot_picker_lst[0].current_cursor
226 | else:
227 | self._hotspot_picker_lst = [
228 | CursorEditWidget(None, cursor, i) for i in range(len(cursor))
229 | ]
230 | self._cursor = cursor
231 |
232 | for i, cur_picker in enumerate(self._hotspot_picker_lst):
233 | self._inner_layout.addWidget(cur_picker)
234 | self._scroll_area.setWidgetResizable(True)
235 | self._in_scroll_wid.setLayout(self._inner_layout)
236 | self._scroll_area.setWidget(self._in_scroll_wid)
237 |
238 | self._share_hotspots = QtWidgets.QCheckBox("Share Hotspots Between Frames")
239 | self._share_hotspots.setTristate(False)
240 |
241 | self._share_delays = QtWidgets.QCheckBox("Share Delays Between Frames")
242 | self._share_delays.setTristate(False)
243 |
244 | self._preview = QtWidgets.QPushButton("Preview")
245 |
246 | self._outer_layout.addWidget(self._info_label)
247 | self._outer_layout.addWidget(self._scroll_area)
248 | self._outer_layout.addWidget(self._share_hotspots)
249 | self._outer_layout.addWidget(self._share_delays)
250 | self._outer_layout.addWidget(self._preview)
251 |
252 | self.setLayout(self._outer_layout)
253 | self.resize(self.sizeHint())
254 |
255 | # Event connections...
256 | self._share_hotspots.stateChanged.connect(self._share_hotspot_chg)
257 | self._share_delays.stateChanged.connect(self._share_delays_chg)
258 | self._preview.clicked.connect(self._on_preview)
259 | for cur_picker in self._hotspot_picker_lst:
260 | cur_picker.userHotspotChange.connect(self._on_hotspot_changed)
261 | cur_picker.userDelayChange.connect(self._on_delay_changed)
262 | # Set to delete this dialog on close...
263 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
264 |
265 | def _share_hotspot_chg(self, state: int):
266 | if state == QtCore.Qt.Checked:
267 | # Trigger an update...
268 | self._on_hotspot_changed(*self._hotspot_picker_lst[0].hotspot)
269 |
270 | def _share_delays_chg(self, state: int):
271 | if state == QtCore.Qt.Checked:
272 | # Trigger update to all delays...
273 | self._on_delay_changed(self._hotspot_picker_lst[0].delay)
274 |
275 | def _on_hotspot_changed(self, x: int, y: int):
276 | if self._share_hotspots.isChecked():
277 | for cur_picker in self._hotspot_picker_lst:
278 | cur_picker.hotspot = x, y
279 |
280 | def _on_delay_changed(self, value: int):
281 | if self._share_delays.isChecked():
282 | for cur_picker in self._hotspot_picker_lst:
283 | cur_picker.delay = value
284 |
285 | def _on_preview(self):
286 | dialog = CursorPreviewDialog(self, self.current_cursor)
287 | dialog.exec_()
288 |
289 | def closeEvent(self, evt: QtGui.QCloseEvent):
290 | super().closeEvent(evt)
291 | self.accept()
292 |
293 | @property
294 | def current_cursor(self) -> AnimatedCursor:
295 | return self._cursor
296 |
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorpreviewdialog.py:
--------------------------------------------------------------------------------
1 | from PIL.ImageQt import toqpixmap
2 | from CursorCreate.gui.QtKit import QtCore, QtGui, QtWidgets
3 | from CursorCreate.gui.cursorviewer import CursorDisplayWidget
4 | from CursorCreate.lib import cursor_util
5 | from CursorCreate.lib.cursor import AnimatedCursor
6 |
7 |
8 | class CursorPreviewDialog(QtWidgets.QDialog):
9 | def __init__(self, parent=None, cursor: AnimatedCursor = None):
10 | super().__init__(parent)
11 | super().setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowCloseButtonHint)
12 |
13 | self._colors = ["white", "black"]
14 |
15 | self._main_layout = QtWidgets.QVBoxLayout()
16 |
17 | self._preview_panel = PreviewArea(None, cursor)
18 | self._frame = QtWidgets.QFrame()
19 | self._frame.setFrameStyle(QtWidgets.QFrame.Box | QtWidgets.QFrame.Plain)
20 | self._box = QtWidgets.QVBoxLayout()
21 | self._box.addWidget(self._preview_panel)
22 | self._frame.setLayout(self._box)
23 | self._box.setContentsMargins(0, 0, 0, 0)
24 |
25 | self._viewers = []
26 |
27 | for color in self._colors:
28 | widget = QtWidgets.QWidget()
29 | widget.setStyleSheet(f"background-color: {color};")
30 | hbox = QtWidgets.QHBoxLayout()
31 |
32 | for size in cursor_util.DEFAULT_SIZES:
33 | c_view = CursorDisplayWidget(cursor=cursor, size=size[0])
34 | self._viewers.append(c_view)
35 | hbox.addWidget(c_view)
36 |
37 | widget.setLayout(hbox)
38 | self._main_layout.addWidget(widget)
39 |
40 | self._main_layout.addWidget(self._frame)
41 |
42 | self.setLayout(self._main_layout)
43 | self.setMinimumSize(self.sizeHint())
44 |
45 | # Set to delete this dialog on close...
46 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
47 |
48 | def closeEvent(self, evt: QtGui.QCloseEvent):
49 | super().closeEvent(evt)
50 | self.accept()
51 |
52 |
53 | class PreviewArea(QtWidgets.QWidget):
54 | CURSOR_SIZE = (32, 32)
55 |
56 | def __init__(self, parent, cursor: AnimatedCursor):
57 | super().__init__(parent)
58 | self._core_painter = QtGui.QPainter()
59 | self._pixmaps = [
60 | toqpixmap(sub_cur[self.CURSOR_SIZE].image)
61 | for sub_cur, delay in cursor
62 | ]
63 | self._hotspots = [
64 | sub_cur[self.CURSOR_SIZE].hotspot for sub_cur, delay in cursor
65 | ]
66 | self._delays = [delay for sub_cur, delay in cursor]
67 |
68 | self._animation_timer = QtCore.QTimer()
69 | self._animation_timer.setSingleShot(True)
70 | self._animation_timer.timeout.connect(self.moveStep)
71 | self._current_frame = -1
72 |
73 | self._main_layout = QtWidgets.QVBoxLayout()
74 | self._example_label = QtWidgets.QLabel(
75 | "Hover over me to see the cursor! Click to see the hotspot."
76 | )
77 | self._main_layout.addWidget(self._example_label)
78 | self.setLayout(self._main_layout)
79 |
80 | self._hotspot_preview_loc = None
81 | self._pressed = False
82 |
83 | self.moveStep()
84 |
85 | def moveStep(self):
86 | self._current_frame = (self._current_frame + 1) % len(self._delays)
87 | if len(self._pixmaps) > 0:
88 | self.setCursor(
89 | QtGui.QCursor(
90 | self._pixmaps[self._current_frame],
91 | *self._hotspots[self._current_frame],
92 | )
93 | )
94 | if len(self._pixmaps) > 1:
95 | self._animation_timer.setInterval(self._delays[self._current_frame])
96 | self._animation_timer.start()
97 |
98 | def paintEvent(self, event: QtGui.QPaintEvent):
99 | self._core_painter.begin(self)
100 |
101 | if self._hotspot_preview_loc is not None:
102 | self._core_painter.setPen(QtGui.QColor(0, 0, 0, 0))
103 | colors = [(0, 0, 255, 100), (0, 255, 0, 200), (255, 0, 0, 255)]
104 | widths = [20, 8, 3]
105 | for color, width in zip(colors, widths):
106 | self._core_painter.setBrush(QtGui.QBrush(QtGui.QColor(*color)))
107 | self._core_painter.drawEllipse(
108 | QtCore.QPoint(*self._hotspot_preview_loc), width, width
109 | )
110 |
111 | self._core_painter.end()
112 |
113 | def mousePressEvent(self, event: QtGui.QMouseEvent):
114 | self._pressed = True
115 | self._hotspot_preview_loc = (event.x(), event.y())
116 | self.update()
117 |
118 | def mouseMoveEvent(self, event: QtGui.QMouseEvent):
119 | if self._pressed:
120 | self._hotspot_preview_loc = (event.x(), event.y())
121 | self.update()
122 |
123 | def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
124 | if self._pressed:
125 | self.mouseMoveEvent(event)
126 | self._pressed = False
127 |
128 | def __del__(self):
129 | del self._animation_timer
130 |
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorselector.py:
--------------------------------------------------------------------------------
1 | import pathlib
2 | from io import BytesIO
3 | from urllib.error import URLError
4 | from urllib.request import urlopen
5 |
6 | from CursorCreate.gui.QtKit import QtCore, QtGui, QtWidgets
7 |
8 | from CursorCreate.gui.cursorviewedit import CursorViewEditWidget
9 | from CursorCreate.lib.cursor_util import load_cursor
10 |
11 |
12 | class CursorSelectWidget(QtWidgets.QFrame):
13 | FILE_DIALOG_TYPES = "Image, Cursor, or SVG (*)"
14 |
15 | def __init__(
16 | self, parent=None, label_text="Label", def_cursor=None, *args, **kwargs
17 | ):
18 | super().__init__(parent, *args, **kwargs)
19 |
20 | self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Raised)
21 |
22 | self._main_layout = QtWidgets.QVBoxLayout()
23 | self._label = QtWidgets.QLabel(label_text)
24 | self._label.setAlignment(QtCore.Qt.AlignCenter)
25 | self._viewer = CursorViewEditWidget(cursor=def_cursor)
26 | self._file_sel_btn = QtWidgets.QPushButton("Select File")
27 | self._current_file = None
28 |
29 | # Make a frame to wrap around the hotspot picker and add a border...
30 | self._frame = QtWidgets.QFrame()
31 | self._f_lay = QtWidgets.QVBoxLayout()
32 | # self._f_lay.setMargin(0)
33 | self._f_lay.setContentsMargins(0, 0, 0, 0)
34 | self._f_lay.addWidget(self._viewer)
35 | self._frame.setLayout(self._f_lay)
36 | self._frame.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Sunken)
37 | self._frame.setSizePolicy(
38 | QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed
39 | )
40 |
41 | self._main_layout.addWidget(self._label)
42 | self._main_layout.addWidget(self._frame)
43 | self._main_layout.addWidget(self._file_sel_btn)
44 |
45 | self._main_layout.setAlignment(self._frame, QtCore.Qt.AlignHCenter)
46 |
47 | self.setLayout(self._main_layout)
48 | self.setAcceptDrops(True)
49 |
50 | # Events...
51 | self._file_sel_btn.clicked.connect(self.open_file)
52 |
53 | def open_file(self):
54 | path, __ = QtWidgets.QFileDialog.getOpenFileName(
55 | self, "Select a Cursor", filter=self.FILE_DIALOG_TYPES
56 | )
57 | if path != "":
58 | with open(path, "rb") as f:
59 | try:
60 | self.current_cursor = load_cursor(f)
61 | self._current_file = path
62 | except ValueError as e:
63 | print(e)
64 | return
65 |
66 | def dragEnterEvent(self, event: QtGui.QDragEnterEvent):
67 | if event.mimeData().hasImage() or event.mimeData().hasUrls():
68 | event.acceptProposedAction()
69 |
70 | def dragMoveEvent(self, event: QtGui.QDragMoveEvent):
71 | self.dragEnterEvent(event)
72 |
73 | def dropEvent(self, event: QtGui.QDropEvent):
74 | if event.mimeData().hasUrls():
75 | cursor = None
76 | working_path = None
77 |
78 | for cur_path in event.mimeData().urls():
79 | if cur_path.isLocalFile():
80 | path = cur_path.path(options=QtCore.QUrl.FullyDecoded)
81 |
82 | if isinstance(
83 | pathlib.PurePath(), pathlib.PureWindowsPath
84 | ) and path.startswith("/"):
85 | path = path[1:]
86 |
87 | with open(path, "rb") as f:
88 | try:
89 | cursor = load_cursor(f)
90 | working_path = path
91 | except ValueError as e:
92 | print(e)
93 | else:
94 | try:
95 | req = urlopen(cur_path.url())
96 | data = BytesIO(req.read())
97 | data.seek(0)
98 | cursor = load_cursor(data)
99 | working_path = None
100 | except (URLError, ValueError) as e:
101 | print(e)
102 |
103 | if cursor is not None:
104 | self.current_cursor = cursor
105 | self._current_file = working_path
106 | event.acceptProposedAction()
107 | return
108 |
109 | if event.mimeData().hasImage():
110 | mem_img = BytesIO()
111 | buffer = QtCore.QBuffer()
112 | image = QtGui.QImage(event.mimeData().imageData())
113 | image.save(buffer, "PNG")
114 |
115 | mem_img.write(buffer)
116 | mem_img.seek(0)
117 |
118 | self.current_cursor = load_cursor(mem_img)
119 | self._current_file = None
120 | event.acceptProposedAction()
121 | return
122 |
123 | @property
124 | def current_cursor(self):
125 | return self._viewer.current_cursor
126 |
127 | @current_cursor.setter
128 | def current_cursor(self, value):
129 | self._viewer.current_cursor = value
130 |
131 | @property
132 | def label_text(self):
133 | return self._label.text()
134 |
135 | @label_text.setter
136 | def label_text(self, value):
137 | self._label.setText(value)
138 |
139 | @property
140 | def current_file(self):
141 | return self._current_file
142 |
143 | @current_file.setter
144 | def current_file(self, value):
145 | if (not isinstance(value, str)) and (value is not None):
146 | raise ValueError("The file path must be a string!!!")
147 |
148 | self._current_file = value
149 |
150 |
151 | if __name__ == "__main__":
152 | app = QtWidgets.QApplication([])
153 | window = CursorSelectWidget(label_text="wait")
154 | window.show()
155 | app.exec_()
156 | print(window.current_cursor, window.current_file)
157 |
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorthememaker.py:
--------------------------------------------------------------------------------
1 | import base64
2 | import copy
3 | import re
4 | import sys
5 | from io import BytesIO
6 | from pathlib import Path
7 | from typing import Any, Dict, Union
8 |
9 | from PIL import Image
10 | from PIL.ImageQt import toqpixmap
11 | from CursorCreate.gui.QtKit import QtCore, QtGui, QtWidgets
12 |
13 | from CursorCreate.gui.cursorselector import CursorSelectWidget
14 | from CursorCreate.gui.layouts import FlowLayout
15 | from CursorCreate.lib import theme_util
16 | from CursorCreate.lib.cur_theme import CursorThemeBuilder
17 |
18 | ICON = """
19 | iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAIlElEQVR42u1ZWUyb6RWl+zxUrdSR
20 | OtNFaqsu07e+TdWHqvNQzbQvVaU2aqvMTJMmTbORjRmSJiROIGzGgWEbxmBwIGaJs0CwDcYYGwib
21 | wWC8gNlig8EGzGLj3WD79P5/Q9rJ0k4DTkg1n/S9YAT33HvPPed+Tkj49OzQc4xT4GvQDM+0GswH
22 | XkgA+97LCgjlnbg7aQs39w8W0Y8+80IB2Hvy8krRDTnax6yYWHJFb7Z3N53LLfnWCwPgLycvT2VV
23 | 3ELb6D1Y3H6EI1GIFB12Tmnpj14IAO8mcnrO51+DwjiJ8WUPYrEYbC4vpFrjypWq2j07HsA7hy9I
24 | k9L5aB4ew8iiiwXgDq3D6vKhzTSJ4puS/MTExC/tWAD7T6XmHTlfEGvUmqCfX0GUAPjXN2D3BjHn
25 | CWBozhkruSMf4giFL+1IAH87nX78wOmc6K1eHQZnFxEiACHigcMXYu8sgTA4lnCrZ3CKk1fyxo4D
26 | 8NekS7/eeyojUtuuQf/MPHzRGNaj/wLAXKYaUytraOjTRXgi8e85HM5ndwyAA0kZP959hBOpaulC
27 | r9UOVySGyEMANkFME7nvTsyEBfUSJZ/P/8KOACCWyV7ddeDsRplEjbtTNiyGNxADHgGweW1rfgza
28 | 5lEua20vFot/sCNA7Dl2cX1TzGz+MJizFAg/EQRTDTNNLHFX/1JR3e3nrxdvJ17o5FU1QMWI2VqQ
29 | rcBqcP2JAB7wYnkNkgF9NLvq+sHnCuDg+5nlafzraKW5P77qRYQAeML/GcDHeTGNkoam1Cy++KvP
30 | x5GmZJ88myuE3DAOk9OFdSqBPxz5rwA275wnCL19CbyaW4uFtbXffPYVSL78+om0Ykh1oxh2LCNE
31 | ozSw8ckBbFZjbMlNo3ZoXHD9xslnCkCrNX7/0Llc3BkwQDu7gAAJ2b+L2f9yLWRBmodHUVjXsPfA
32 | sxy1R1LyIje6h6CZccBL2V+PPh0A5s7QqL1LE00gU/ETEvBs9ot972XOXFP2oMcyBxdpQYTaaP4p
33 | AbAtRXdo1glytK5MwbX468W7J1J1pY0qdJGYOYNhRGJbA7DJi8llN25r9CFuefmb8dWCo5z2/DoZ
34 | OmgkMtmLbQOATRCWVQ8UxItMoYhLPurzcQHwp0MpUq7wNlRjFljJgTJith0AHrha4oVm2oGrMiWf
35 | Wyx8NR6bWU1qSQ2UpMZTtFoyZzkY3jYAm9ac0QthU9sc/fntnVCJZ7k8RsxaDBMYW/GwFfAQmbcT
36 | wD9FL4AxEsu6jr5Q4bWbb28bgEOns44kZXwEmc4M4+IqGEsX3IhuW+AMFxwUvJ3uvMcHL219gVAI
37 | omZ52bYAOJqc9dbRC/loHDRBR2UOEICtaMGDywTuDVDwfrioJQMUeOT+2up0r2HCZo/26E1VGrP5
38 | 5S36ofwf7k/ORr1GjwHbAry02DD78dMGvZlxpy8AT2gdG5SMMAmkJxiEbXEJxikr+kxmdOpHoNaZ
39 | Ys19upwtAWhSq7/9zrFL5PG16LM64KJ/RvE/FYBpshNOX5AC3mCTEKRsL6y6KdtzGBgdR49hFB36
40 | USjIutxUaSC4pUJxjSK0dTvx9xwwatx9bxZLoQ12Ei0Gnq7ftbSeGq02TC84YaBsa0bG2Wy3DRog
41 | 6RqESHYXJddbwauQ4crV5mhhjfKjrY/SYxc7SiUqdI6TmPlD7CRafsxmttkeTF/P033c8mOlvULc
42 | 3oObLW2U7RG0PMh2G/Iqm5FTIYulltyZL6pT7k9I2KZHgj3HU6uviBqhNltYQ8YAWHk4OArYQVNk
43 | 2R9kiRik3l6PPP4RQE/ONruiGuW3lSiuVTBBI6NUgivClosForY3CwqatvfB7GByJi+NXwflyBSm
44 | KIMMB1yh8IOML3hpkgSotyMRbFDQPuYzl4edKu71RzVjxk3WWmtEMleA9FKpilcpPy4SNX0lfs+M
45 | R88fPJNTAYVxAualNSIg7cYUsJMCDzKEvP9mtOrzw2Kfx/DEPYzOOrBGPGFALPgfrcI4aUquSIx9
46 | See+8wyeGS//4XhqMWTDJGYLK6ylZrNNQXtp/DmWV2EmYg6YJ9BFk6RNSyPXPAmrcwVh+h3fY6rA
47 | KG/3uBWpxfzKuANIusB76/DZvNidfgN5FidClPVl6vd79gXoJ++hmxl/wyYoB41o6BxArbQVaq0O
48 | BosN82tedmQ6H/JPdhIxy/IaKW4bUrKzX4vvO+mp1J/sf5+7LqYxN2idw6h1Bv00/phst+tG0NSr
49 | Q21LN/jiVuSU30FeWS0kHd3oNZoxQSBDDKk3Cc2I2X3CuwmUy+9HdaNs5vDhw1+O33J/gvPdP59I
50 | C1Ure9FlHGPHn0JrQH37AK42dqCwuoUdf1yBzHQuR6i+yCtDVX0zlJpBDBEf5lbX2GdJhuxLpMBe
51 | CpxpP6aSLG/mF6MdWu3uuAHIKan6+h8PnQ9WNrWjqW8YNfJulNQpkCuUxTJLJdE0fmN7paT7Z8zv
52 | vkGLyamLH0S5xVWob+tEp86IUZsdbiI0EzTTTozvcay4YJ62USXH0EmV7DSYfSbgi3EBIBQKX/rd
53 | vmR/fpUERdVycAVScMtlxvxrLZy0DxteU6vVH9um0vIEv73A5aO0pgHN3Rr0E6HtZBlWvD5YHQsY
54 | nrSgl/E7RiI8caeRbEolVbJWrvl5HJf7dF+WQLqUIZAqcytbfyk2mZ6YLRN9duZyUX9GgZBVXPXg
55 | MBu0lvxOFwXdziqwHjfa+og3ShIwGZMQd1Gt6qdxA5Bb1fiLdL78GxwOPpG8n03/4JUz6UUorKiD
56 | rLOHWmSEDZzJdkW9CgUiORFeyijwanG1KjunquV7u3aJP7ejviRJyfpQcOlKGWpkKtQpeths5wqb
57 | QJVcSy+T1lHwuyuVmpcTduqxWBZfSU7ND/MEDYy7jFDQLl6lolDSM/7ifN+cwiv/DU2rBuLOr3IF
58 | PV9L+PT8n51/ADoCxpfaGXQMAAAAAElFTkSuQmCC
59 | """
60 |
61 |
62 | class CursorThemeMaker(QtWidgets.QWidget):
63 | def __init__(self, parent=None, *args, **kwargs):
64 | super().__init__(parent, *args, **kwargs)
65 |
66 | mem_icon = BytesIO(base64.b64decode(ICON))
67 |
68 | self.setWindowTitle("Cursor Theme Builder")
69 | self.setWindowIcon(QtGui.QIcon(toqpixmap(Image.open(mem_icon))))
70 |
71 | self._open_build_project = None
72 |
73 | self._metadata = {"author": None, "licence": None}
74 |
75 | self._main_layout = QtWidgets.QVBoxLayout(self)
76 |
77 | self._scroll_pane = QtWidgets.QScrollArea()
78 | self._scroll_pane.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
79 | self._scroll_pane.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
80 | self._scroll_pane.setWidgetResizable(True)
81 |
82 | self._inner_pane_area = QtWidgets.QWidget()
83 | self._flow_layout = FlowLayout()
84 |
85 | self._cursor_selectors = {}
86 |
87 | for cursor_name in sorted(CursorThemeBuilder.DEFAULT_CURSORS):
88 | self._cursor_selectors[cursor_name] = CursorSelectWidget(
89 | label_text=cursor_name
90 | )
91 | self._flow_layout.addWidget(self._cursor_selectors[cursor_name])
92 |
93 | self._edit_metadata = QtWidgets.QPushButton("Edit Artist Info")
94 | self._main_layout.addWidget(self._edit_metadata)
95 |
96 | self._inner_pane_area.setLayout(self._flow_layout)
97 | self._scroll_pane.setWidget(self._inner_pane_area)
98 |
99 | self._button_layout = QtWidgets.QHBoxLayout()
100 | self._main_layout.addWidget(self._scroll_pane)
101 |
102 | self._build_button = QtWidgets.QPushButton("Build Project")
103 | self._create_proj_btn = QtWidgets.QPushButton("Save Project")
104 | self._load_proj_btn = QtWidgets.QPushButton("Load Project")
105 | self._update_proj_btn = QtWidgets.QPushButton("Update Project")
106 | self._build_in_place = QtWidgets.QPushButton("Build in Place")
107 | self._clear_btn = QtWidgets.QPushButton("New Project")
108 | self._update_proj_btn.setEnabled(False)
109 | self._build_in_place.setEnabled(False)
110 | self._button_layout.addWidget(self._build_button)
111 | self._button_layout.addWidget(self._create_proj_btn)
112 | self._button_layout.addWidget(self._load_proj_btn)
113 | self._button_layout.addWidget(self._update_proj_btn)
114 | self._button_layout.addWidget(self._build_in_place)
115 | self._button_layout.addWidget(self._clear_btn)
116 |
117 | self._main_layout.addLayout(self._button_layout)
118 |
119 | self.setLayout(self._main_layout)
120 | # self.setMinimumSize(self.sizeHint())
121 |
122 | self._build_button.clicked.connect(self.build_project)
123 | self._create_proj_btn.clicked.connect(self.create_project)
124 | self._load_proj_btn.clicked.connect(self.load_project)
125 | self._update_proj_btn.clicked.connect(self.update_project)
126 | self._build_in_place.clicked.connect(self.build_in_place)
127 | self._clear_btn.clicked.connect(self.clear_ui)
128 | self._edit_metadata.clicked.connect(self._chg_metadata)
129 |
130 | def create_project(self):
131 | dir_picker = DirectoryPicker(self, "Select Directory to Create Project In")
132 | dir_picker.exec_()
133 | directory_info = dir_picker.get_results()
134 |
135 | if directory_info is not None:
136 | theme_name, theme_dir = directory_info
137 | files_and_cursors = {}
138 |
139 | for cursor_name, selector in self._cursor_selectors.items():
140 | if selector.current_cursor is not None:
141 | c_f_path = (
142 | Path(selector.current_file)
143 | if (selector.current_file is not None)
144 | else None
145 | )
146 | files_and_cursors[cursor_name] = (c_f_path, selector.current_cursor)
147 |
148 | theme_util.save_project(
149 | theme_name, theme_dir, self._metadata, files_and_cursors
150 | )
151 | self._open_build_project = str(
152 | (Path(theme_dir) / theme_name) / "build.json"
153 | )
154 | self._update_proj_btn.setEnabled(True)
155 | self._build_in_place.setEnabled(True)
156 |
157 | def build_project(self):
158 | dir_picker = DirectoryPicker(self, "Select Directory to Build Project In")
159 | dir_picker.exec_()
160 | directory_info = dir_picker.get_results()
161 |
162 | if directory_info is not None:
163 | theme_name, theme_dir = directory_info
164 | cursors = {}
165 |
166 | for cursor_name, selector in self._cursor_selectors.items():
167 | if selector.current_cursor is not None:
168 | cursors[cursor_name] = selector.current_cursor
169 |
170 | theme_util.build_theme(theme_name, theme_dir, self._metadata, cursors)
171 |
172 | def build_in_place(self):
173 | if self._open_build_project is None:
174 | return
175 |
176 | project_folder = Path(self._open_build_project).parent
177 | theme_name, dir_path = project_folder.name, project_folder.parent
178 |
179 | cursors = {}
180 |
181 | for cursor_name, selector in self._cursor_selectors.items():
182 | if selector.current_cursor is not None:
183 | cursors[cursor_name] = selector.current_cursor
184 |
185 | theme_util.build_theme(theme_name, dir_path, self._metadata, cursors)
186 |
187 | QtWidgets.QMessageBox.information(
188 | self, "Cursor Theme Maker", f"Project '{self._open_build_project}' Built!!!"
189 | )
190 |
191 | def update_project(self):
192 | if self._open_build_project is None:
193 | return
194 |
195 | path_total = Path(self._open_build_project).parent
196 | theme_name, dir_path = path_total.name, path_total.parent
197 |
198 | files_and_cursors = {}
199 |
200 | for cursor_name, selector in self._cursor_selectors.items():
201 | if selector.current_cursor is not None:
202 | c_f_path = (
203 | Path(selector.current_file)
204 | if (selector.current_file is not None)
205 | else None
206 | )
207 | files_and_cursors[cursor_name] = (c_f_path, selector.current_cursor)
208 |
209 | theme_util.save_project(theme_name, dir_path, self._metadata, files_and_cursors)
210 |
211 | QtWidgets.QMessageBox.information(
212 | self,
213 | "Cursor Theme Maker",
214 | f"Project '{self._open_build_project}' Updated!!!",
215 | )
216 |
217 | def load_project(self):
218 | file_name, __ = QtWidgets.QFileDialog.getOpenFileName(
219 | self,
220 | "Select the build file for the project.",
221 | filter="JSON Build File (*.json)",
222 | )
223 |
224 | self.load_from_path(file_name)
225 |
226 | def load_from_path(self, file_name: str):
227 | if file_name != "":
228 | try:
229 | metadata, data = theme_util.load_project(Path(file_name))
230 |
231 | for name, (path, cursor) in data.items():
232 | if name in self._cursor_selectors:
233 | self._cursor_selectors[name].current_cursor = cursor
234 | self._cursor_selectors[name].current_file = str(path)
235 |
236 | self._open_build_project = file_name
237 | self._metadata = metadata
238 | self._update_proj_btn.setEnabled(True)
239 | self._build_in_place.setEnabled(True)
240 | except Exception as e:
241 | print(e)
242 |
243 | def _chg_metadata(self):
244 | dialog = MetaDataEdit(self, self._metadata)
245 | dialog.exec_()
246 | self._metadata = dialog.get_metadata()
247 |
248 | def clear_ui(self):
249 | for name, cursor_selector in self._cursor_selectors.items():
250 | cursor_selector.current_cursor = None
251 | cursor_selector.current_file = None
252 | self._metadata = {"author": None, "licence": None}
253 | self._open_build_project = None
254 | self._update_proj_btn.setEnabled(False)
255 | self._build_in_place.setEnabled(False)
256 |
257 |
258 | class DirectoryPicker(QtWidgets.QDialog):
259 | IS_VALID_THEME_NAME = re.compile(r"[-.\w ]+")
260 |
261 | def __init__(self, parent=None, name=""):
262 | super().__init__(parent)
263 | super().setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowCloseButtonHint)
264 | self.setWindowTitle(name)
265 | self._result = None
266 |
267 | self._form_layout = QtWidgets.QFormLayout(self)
268 | self._hbox_layout = QtWidgets.QHBoxLayout()
269 |
270 | self._button = QtWidgets.QPushButton("Select")
271 | self._text = QtWidgets.QLineEdit("")
272 | self._text.setReadOnly(True)
273 | self._hbox_layout.addWidget(self._button)
274 | self._hbox_layout.addWidget(self._text)
275 |
276 | self._theme_text = QtWidgets.QLineEdit()
277 |
278 | self._form_layout.addRow("Theme Name:", self._theme_text)
279 | self._form_layout.addRow("Theme Directory:", self._hbox_layout)
280 |
281 | self._submit_btns = QtWidgets.QDialogButtonBox(
282 | QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
283 | )
284 | self._submit_btns.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
285 | self._form_layout.addRow(self._submit_btns)
286 |
287 | self.setLayout(self._form_layout)
288 |
289 | self._button.clicked.connect(self.open_dir)
290 |
291 | self._submit_btns.rejected.connect(self.reject)
292 | self._submit_btns.accepted.connect(self.accept)
293 | self._theme_text.textChanged.connect(lambda a: self.validate())
294 |
295 | self.accepted.connect(self.on_submit_stuff)
296 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
297 |
298 | def open_dir(self):
299 | sel_dir = QtWidgets.QFileDialog.getExistingDirectory(self, "Select a Directory")
300 | self._text.setText(sel_dir)
301 | self.validate()
302 |
303 | def validate(self):
304 | folder_name = self._theme_text.text().strip()
305 | dir_name = self._text.text().strip()
306 |
307 | path_exists = (Path(dir_name) / folder_name).exists()
308 |
309 | if (
310 | self.IS_VALID_THEME_NAME.fullmatch(folder_name)
311 | and (dir_name != "")
312 | and (not path_exists)
313 | ):
314 | self._submit_btns.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
315 | else:
316 | self._submit_btns.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
317 |
318 | def on_submit_stuff(self):
319 | self._result = (
320 | self._theme_text.text().strip(),
321 | Path(self._text.text().strip()).resolve(),
322 | )
323 |
324 | def get_results(self):
325 | return self._result
326 |
327 |
328 | class MetaDataEdit(QtWidgets.QDialog):
329 | FILE_PICKER_FILTER = "Text Files (*.txt)"
330 | TITLE = "CursorCreate Metadata"
331 |
332 | def __init__(self, parent=None, metadata: Dict[str, Any] = None):
333 | super().__init__(parent)
334 | super().setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowCloseButtonHint)
335 | self.setWindowTitle(self.TITLE)
336 |
337 | if metadata is None:
338 | self._metadata = {"author": None, "licence": None}
339 | else:
340 | self._metadata = copy.deepcopy(metadata)
341 |
342 | self._main_layout = QtWidgets.QFormLayout(self)
343 | self._author = QtWidgets.QLineEdit()
344 | self._author.setText(
345 | ""
346 | if (self._metadata.get("author", None) is None)
347 | else self._metadata["author"]
348 | )
349 |
350 | self._licence_text = QtWidgets.QTextEdit()
351 | self._licence_text.setText(
352 | ""
353 | if (self._metadata.get("licence", None) is None)
354 | else self._metadata["licence"]
355 | )
356 |
357 | self._licence_btn = QtWidgets.QPushButton("From File")
358 |
359 | self._submit_btns = QtWidgets.QDialogButtonBox(
360 | QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok
361 | )
362 |
363 | self._main_layout.addRow("Author:", self._author)
364 | self._main_layout.addRow("Licence:", self._licence_btn)
365 | self._main_layout.addRow(self._licence_text)
366 | self._main_layout.addRow(self._submit_btns)
367 |
368 | self._licence_btn.clicked.connect(self._on_file_req)
369 | self._submit_btns.accepted.connect(self._on_accept)
370 | self._submit_btns.rejected.connect(self.reject)
371 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
372 |
373 | def _on_file_req(self):
374 | path, __ = QtWidgets.QFileDialog.getOpenFileName(
375 | self, "Select a Licence File", filter=self.FILE_PICKER_FILTER
376 | )
377 |
378 | if path != "":
379 | try:
380 | with open(path) as f:
381 | self._licence_text.setText(f.read())
382 | except IOError as e:
383 | print(e)
384 |
385 | def _on_accept(self):
386 | self._metadata["author"] = (
387 | None if (self._author.text() == "") else self._author.text()
388 | )
389 | self._metadata["licence"] = (
390 | None
391 | if (self._licence_text.toPlainText() == "")
392 | else self._licence_text.toPlainText()
393 | )
394 | self.accept()
395 |
396 | def get_metadata(self):
397 | return self._metadata
398 |
399 |
400 | def launch_gui(def_project: Union[str, None]):
401 | app = QtWidgets.QApplication(sys.argv)
402 | window = CursorThemeMaker()
403 | window.show()
404 |
405 | if def_project is not None:
406 | window.load_from_path(def_project)
407 |
408 | app.exec_()
409 |
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorviewedit.py:
--------------------------------------------------------------------------------
1 | from CursorCreate.gui.QtKit import QtGui, QtCore
2 | from CursorCreate.gui.cursorhotspotedit import HotspotEditDialog
3 | from CursorCreate.gui.cursorviewer import CursorDisplayWidget
4 |
5 |
6 | class CursorViewEditWidget(CursorDisplayWidget):
7 | def __init__(self, *args, **kwargs):
8 | super().__init__(*args, **kwargs)
9 | self.setCursor(QtCore.Qt.PointingHandCursor)
10 |
11 | def mousePressEvent(self, event: QtGui.QMouseEvent):
12 | self._pressed = True
13 |
14 | def mouseReleaseEvent(self, event: QtGui.QMouseEvent):
15 | if self._pressed:
16 | self._pressed = False
17 | if self.current_cursor is not None:
18 | mod_hotspot = HotspotEditDialog(self.window(), self.current_cursor)
19 | mod_hotspot.exec_()
20 | self.current_cursor = self.current_cursor
21 | del mod_hotspot
22 |
--------------------------------------------------------------------------------
/CursorCreate/gui/cursorviewer.py:
--------------------------------------------------------------------------------
1 | from PIL.ImageQt import toqpixmap
2 | from CursorCreate.gui.QtKit import QtCore, QtGui, QtWidgets
3 |
4 | from CursorCreate.lib.cursor import AnimatedCursor
5 |
6 |
7 | class CursorDisplayWidget(QtWidgets.QWidget):
8 | DEF_SIZE = 64
9 |
10 | def __init__(
11 | self, parent=None, cursor: AnimatedCursor = None, size=None, *args, **kwargs
12 | ):
13 | super().__init__(parent, *args, **kwargs)
14 |
15 | self._cur = None
16 | self._current_frame = None
17 | self._is_ani = None
18 | self.__painter = QtGui.QPainter()
19 | self.__animation_timer = QtCore.QTimer()
20 | self.__animation_timer.setSingleShot(True)
21 | self.__animation_timer.timeout.connect(self.move_step)
22 | self._imgs = None
23 | self._delays = None
24 | self._pressed = False
25 | self._size = self.DEF_SIZE if (size is None) else int(size)
26 |
27 | self.current_cursor = cursor
28 |
29 | self.setMinimumSize(self._imgs[self._current_frame].size())
30 | self.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
31 | self.resize(self._imgs[self._current_frame].size())
32 |
33 | def paintEvent(self, event: QtGui.QPaintEvent):
34 | self.__painter.begin(self)
35 | self.__painter.drawPixmap(0, 0, self._imgs[self._current_frame])
36 | self.__painter.end()
37 |
38 | def sizeHint(self) -> QtCore.QSize:
39 | return QtCore.QSize(self.DEF_SIZE, self.DEF_SIZE)
40 |
41 | def move_step(self):
42 | self._current_frame = (self._current_frame + 1) % len(self._imgs)
43 | self.update()
44 | if self._is_ani:
45 | self.__animation_timer.setInterval(self._delays[self._current_frame])
46 | self.__animation_timer.start()
47 |
48 | @property
49 | def current_cursor(self) -> AnimatedCursor:
50 | return self._cur
51 |
52 | @current_cursor.setter
53 | def current_cursor(self, cursor: AnimatedCursor):
54 | self._cur = cursor
55 | self._current_frame = -1
56 | self._is_ani = False
57 | self.__animation_timer.stop()
58 |
59 | if cursor is not None and (len(cursor) > 0):
60 | self._cur.normalize([(self._size, self._size)])
61 | self._imgs = [
62 | toqpixmap(cur[(self._size, self._size)].image)
63 | for cur, delay in cursor
64 | ]
65 | self._delays = [delay for cur, delay in cursor]
66 |
67 | if len(cursor) > 1:
68 | self._is_ani = True
69 | else:
70 | self._imgs = [
71 | QtGui.QPixmap(
72 | QtGui.QImage(
73 | bytes(4 * self._size**2),
74 | self._size,
75 | self._size,
76 | 4,
77 | QtGui.QImage.Format_ARGB32,
78 | )
79 | )
80 | ]
81 | self._delays = [0]
82 |
83 | self.move_step()
84 |
85 | def stop_and_destroy(self):
86 | """Forcefully destroys the cursor viewers animation timer by stopping it and deleting it."""
87 | if (self.__animation_timer is not None) and (self.__animation_timer.isActive()):
88 | self.__animation_timer.stop()
89 |
90 | del self.__animation_timer
91 | self.__animation_timer = None
92 |
93 | def __del__(self):
94 | self.stop_and_destroy()
95 |
--------------------------------------------------------------------------------
/CursorCreate/gui/layouts.py:
--------------------------------------------------------------------------------
1 | """
2 | A Port of FlowLayout from the original PySide examples
3 | Link to original code: (https://github.com/pyside/Examples/blob/master/examples/layouts/flowlayout.py)
4 |
5 | Corrects a couple of incorrect imports and references, other then that not much...
6 | """
7 |
8 | from CursorCreate.gui.QtKit import QtCore, QtWidgets
9 |
10 |
11 | class FlowLayout(QtWidgets.QLayout):
12 | def __init__(self, parent=None, margin=0, spacing=-1):
13 | super(FlowLayout, self).__init__(parent)
14 |
15 | if parent is not None:
16 | self.setContentsMargins(margin, margin, margin, margin)
17 |
18 | self.setSpacing(spacing)
19 |
20 | self.itemList = []
21 |
22 | def __del__(self):
23 | item = self.takeAt(0)
24 | while item:
25 | item = self.takeAt(0)
26 |
27 | def addItem(self, item):
28 | self.itemList.append(item)
29 |
30 | def count(self):
31 | return len(self.itemList)
32 |
33 | def itemAt(self, index):
34 | if 0 <= index < len(self.itemList):
35 | return self.itemList[index]
36 |
37 | return None
38 |
39 | def takeAt(self, index):
40 | if 0 <= index < len(self.itemList):
41 | return self.itemList.pop(index)
42 |
43 | return None
44 |
45 | def expandingDirections(self):
46 | return QtCore.Qt.Orientations(QtCore.Qt.Orientation(0))
47 |
48 | def hasHeightForWidth(self):
49 | return True
50 |
51 | def heightForWidth(self, width):
52 | height = self.do_layout(QtCore.QRect(0, 0, width, 0), True)
53 | return height
54 |
55 | def setGeometry(self, rect):
56 | super(FlowLayout, self).setGeometry(rect)
57 | self.do_layout(rect, False)
58 |
59 | def sizeHint(self):
60 | return self.minimumSize()
61 |
62 | def minimumSize(self):
63 | size = QtCore.QSize()
64 |
65 | for item in self.itemList:
66 | size = size.expandedTo(item.minimumSize())
67 |
68 | size += QtCore.QSize(
69 | 2 * self.contentsMargins().top(), 2 * self.contentsMargins().top()
70 | )
71 | return size
72 |
73 | def do_layout(self, rect, test_only):
74 | x = rect.x()
75 | y = rect.y()
76 | line_height = 0
77 |
78 | for item in self.itemList:
79 | wid = item.widget()
80 | space_x = self.spacing() + wid.style().layoutSpacing(
81 | QtWidgets.QSizePolicy.PushButton,
82 | QtWidgets.QSizePolicy.PushButton,
83 | QtCore.Qt.Horizontal,
84 | )
85 | space_y = self.spacing() + wid.style().layoutSpacing(
86 | QtWidgets.QSizePolicy.PushButton,
87 | QtWidgets.QSizePolicy.PushButton,
88 | QtCore.Qt.Vertical,
89 | )
90 | next_x = x + item.sizeHint().width() + space_x
91 | if next_x - space_x > rect.right() and line_height > 0:
92 | x = rect.x()
93 | y = y + line_height + space_y
94 | next_x = x + item.sizeHint().width() + space_x
95 | line_height = 0
96 |
97 | if not test_only:
98 | item.setGeometry(QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
99 |
100 | x = next_x
101 | line_height = max(line_height, item.sizeHint().height())
102 |
103 | return y + line_height - rect.y()
104 |
--------------------------------------------------------------------------------
/CursorCreate/lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isaacrobinson2000/CursorCreate/248a0863a4ef69cf32d608a661f1d97cd59afe32/CursorCreate/lib/__init__.py
--------------------------------------------------------------------------------
/CursorCreate/lib/ani_format.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 | from typing import Any, BinaryIO, Dict, Iterator, Set, Tuple
3 |
4 | from PIL import BmpImagePlugin
5 |
6 | from CursorCreate.lib.cur_format import CurFormat
7 | from CursorCreate.lib.cursor import AnimatedCursor, Cursor, CursorIcon
8 | from CursorCreate.lib.format_core import AnimatedCursorStorageFormat, to_bytes, to_int
9 |
10 |
11 | # UTILITY METHODS:
12 | def read_chunks(
13 | buffer: BinaryIO,
14 | skip_chunks: Set[bytes] = None,
15 | list_chunks: Set[bytes] = None,
16 | byteorder="little",
17 | ) -> Iterator[Tuple[bytes, int, bytes]]:
18 | """
19 | Reads a valid RIFF file, reading all the chunks in the file...
20 |
21 | :param buffer: The file buffer with valid RIFF data.
22 | :param skip_chunks: A set of length 4 bytes specifying chunks which are not actual chunks but are identifiers
23 | followed by valid chunks.
24 | :param list_chunks: A set of length 4 bytes specifying chunks which containing sub-chunks, meaning there data
25 | should be sub-iterated.
26 | :param byteorder: The byteorder of the integers in the file, "big" or "little". Default is "little".
27 | :return: A generator which yields each chunks identifier, size, and data as bytes.
28 | """
29 | if skip_chunks is None:
30 | skip_chunks = set()
31 | if list_chunks is None:
32 | list_chunks = set()
33 |
34 | while True:
35 | next_id = buffer.read(4)
36 | if next_id == b"":
37 | return
38 | if next_id in skip_chunks:
39 | continue
40 |
41 | size = to_int(buffer.read(4), byteorder=byteorder)
42 |
43 | if next_id in list_chunks:
44 | # print(f"(entering {next_id} chunk) -> [")
45 | yield from read_chunks(
46 | BytesIO(buffer.read(size)), skip_chunks, list_chunks, byteorder
47 | )
48 | # print(f"](exiting {next_id} chunk)")
49 | continue
50 |
51 | # print(f"emit chunk {next_id} of size {size}")
52 | yield next_id, size, buffer.read(size)
53 |
54 |
55 | def write_chunk(
56 | buffer: BinaryIO, chunk_id: bytes, chunk_data: bytes, byteorder="little"
57 | ):
58 | """
59 | Writes a chunk to file.
60 |
61 | :param buffer: The file buffer to write to.
62 | :param chunk_id: The 4 byte chunk identifier.
63 | :param chunk_data: The chunk's data as a bytes object.
64 | :param byteorder: The byteorder to use when writing the byte's size, defaults to "little"
65 | """
66 | buffer.write(chunk_id[:4])
67 | buffer.write(to_bytes(len(chunk_data), 4, byteorder=byteorder))
68 | buffer.write(chunk_data)
69 |
70 |
71 | def _header_chunk(header: None, data: bytes, data_out: Dict[str, Any]):
72 | """
73 | Represents .ani's header chunk, which has an identifier of "anih".
74 | """
75 | if header is not None:
76 | raise SyntaxError("This ani has 2 headers!")
77 |
78 | if len(data) == 36:
79 | data = data[4:]
80 |
81 | h_data = {
82 | "num_frames": to_int(data[0:4]),
83 | "num_steps": to_int(data[4:8]),
84 | "width": to_int(data[8:12]),
85 | "height": to_int(data[12:16]),
86 | "bit_count": to_int(data[16:20]),
87 | "num_planes": 1,
88 | "display_rate": to_int(data[24:28]),
89 | "contains_seq": bool((to_int(data[28:32]) >> 1) & 1),
90 | "is_in_ico": bool(to_int(data[28:32]) & 1),
91 | }
92 |
93 | data_out["header"] = h_data
94 | data_out["seq"] = [i % h_data["num_frames"] for i in range(h_data["num_steps"])]
95 | data_out["rate"] = [h_data["display_rate"]] * h_data["num_steps"]
96 |
97 |
98 | def _icon_chunk(header: Dict[str, Any], data: bytes, data_out: Dict[str, Any]):
99 | """
100 | Represents .ani icon chunk, which has an identifier of "icon".
101 | """
102 | if header is None:
103 | raise SyntaxError("icon chunk became before header!")
104 |
105 | if header["is_in_ico"]:
106 | # Cursors are stored as either .cur or .ico, use CurFormat to read them...
107 | cursor = CurFormat.read(BytesIO(data))
108 | else:
109 | # BMP format, load in and then correct the height...
110 | c_icon = CursorIcon(BmpImagePlugin.DibImageFile(BytesIO(data)), 0, 0)
111 | c_icon.image._size = (c_icon.image.size[0], c_icon.image.size[1] // 2)
112 | d, e, o, a = c_icon.image.tile[0]
113 | c_icon.image.tile[0] = d, (0, 0) + c_icon.image.size, o, a
114 | # Add the image to the cursor list...
115 | cursor = Cursor([c_icon])
116 |
117 | if "list" not in data_out:
118 | data_out["list"] = []
119 |
120 | data_out["list"].append(cursor)
121 |
122 |
123 | def _seq_chunk(header: Dict[str, Any], data: bytes, data_out: Dict[str, Any]):
124 | """
125 | Represents .ani's sequence chunk, which has an identifier of "seq ".
126 | """
127 | if header is None:
128 | raise SyntaxError("seq chunk came before header!")
129 |
130 | if (len(data) // 4) != header["num_steps"]:
131 | raise SyntaxError(
132 | "Length of sequence chunk does not match the number of steps!"
133 | )
134 |
135 | data_out["seq"] = [to_int(data[i : i + 4]) for i in range(0, len(data), 4)]
136 |
137 |
138 | def _rate_chunk(header: Dict[str, Any], data: bytes, data_out: Dict[str, Any]):
139 | """
140 | Represents .ani's rate chunk, which has an identifier of "rate".
141 | """
142 | if header is None:
143 | raise SyntaxError("rate chunk became before header!")
144 |
145 | if (len(data) // 4) != header["num_steps"]:
146 | raise SyntaxError("Length of rate chunk does not match the number of steps!")
147 |
148 | data_out["rate"] = [to_int(data[i : i + 4]) for i in range(0, len(data), 4)]
149 |
150 |
151 | class AniFormat(AnimatedCursorStorageFormat):
152 | """
153 | Represents the windows .ani format, used on windows for storing animated cursors. The file is a type of RIFF file
154 | with an identifier of "ACON" and contains a list of .cur files internally in "icon" chunks. The "seq " chunk stores
155 | the order to play the icons in and and "rate" chunk specifies the rate each frame should last on screen, measured
156 | in 1/60ths of a second.
157 | """
158 |
159 | # Magic for general RIFF format and ANI format.
160 | RIFF_MAGIC = b"RIFF"
161 | ACON_MAGIC = b"ACON"
162 |
163 | # All important .ani RIFF chunks which are vital to reading the file.
164 | CHUNKS = {
165 | b"anih": _header_chunk,
166 | b"icon": _icon_chunk,
167 | b"rate": _rate_chunk,
168 | b"seq ": _seq_chunk,
169 | }
170 |
171 | @classmethod
172 | def check(cls, first_bytes) -> bool:
173 | """
174 | Check if the first bytes of this file are a valid windows .ani file
175 |
176 | :param first_bytes: The first 12 bytes of the file being tested.
177 | :return: True if a valid windows .ani file, otherwise False.
178 | """
179 | return (first_bytes[:4] == cls.RIFF_MAGIC) and (
180 | first_bytes[8:12] == cls.ACON_MAGIC
181 | )
182 |
183 | @classmethod
184 | def read(cls, cur_file: BinaryIO) -> AnimatedCursor:
185 | """
186 | Read a windows .ani file from disk to an AnimatedCursor.
187 |
188 | :param cur_file: The file buffer pointer to the windows .ani data.
189 | :return: An AnimatedCursor object storing all cursor info.
190 | """
191 | magic_header = cur_file.read(12)
192 |
193 | if not cls.check(magic_header):
194 | raise SyntaxError("Not a .ani file!")
195 |
196 | ani_data: Dict[str, Any] = {"header": None}
197 |
198 | for chunk_id, chunk_len, chunk_data in read_chunks(
199 | cur_file, {b"fram"}, {b"LIST"}
200 | ):
201 | if chunk_id in cls.CHUNKS:
202 | cls.CHUNKS[chunk_id](ani_data["header"], chunk_data, ani_data)
203 |
204 | ani_cur = AnimatedCursor()
205 |
206 | for idx, rate in zip(ani_data["seq"], ani_data["rate"]):
207 | # We have to convert the rate to milliseconds. Normally stored in jiffies(1/60ths of a second)
208 | ani_cur.append((ani_data["list"][idx], int((rate * 1000) / 60)))
209 |
210 | return ani_cur
211 |
212 | @classmethod
213 | def write(cls, cursor: AnimatedCursor, out: BinaryIO):
214 | """
215 | Write an AnimatedCursor to the specified file in the windows .ani format.
216 |
217 | :param cursor: The AnimatedCursor object to write.
218 | :param out: The file buffer to write the new .ani data to.
219 | """
220 | # Write the magic...
221 | out.write(cls.RIFF_MAGIC)
222 | # We will deal with writing the length of the entire file later...
223 | out.write(b"\0\0\0\0")
224 | out.write(cls.ACON_MAGIC)
225 |
226 | # Write the header...
227 | header = bytearray(36)
228 | # We write the header length twice for some dumb reason...
229 | header[0:4] = to_bytes(36, 4) # Header length...
230 | header[4:8] = to_bytes(len(cursor), 4) # Number of frames
231 | header[8:12] = to_bytes(len(cursor), 4) # Number of steps
232 | # Ignore width, height, and bits per pixel...
233 | # The number of planes should always be 1....
234 | header[24:28] = to_bytes(1, 4)
235 | header[28:32] = to_bytes(10, 4) # We just pass 10 as the default delay...
236 | header[32:36] = to_bytes(
237 | 1, 4
238 | ) # The flags, last flag is flipped which specifies data is stored in .cur
239 |
240 | write_chunk(out, b"anih", header)
241 |
242 | # Write the LIST of icons...
243 | list_data = bytearray(b"fram")
244 | delay_data = bytearray()
245 |
246 | for sub_cursor, delay in cursor:
247 | # Writing a single cursor to the list...
248 | mem_stream = BytesIO()
249 | CurFormat.write(sub_cursor, mem_stream)
250 | # We write these chunks manually to avoid wasting a ton of lines of code, as using "write_chunks" ends up
251 | # being just as complicated...
252 | cur_data = mem_stream.getvalue()
253 | list_data.extend(b"icon")
254 | list_data.extend(to_bytes(len(cur_data), 4))
255 | list_data.extend(cur_data)
256 | # Writing the delay to the rate chunk
257 | delay_data.extend(to_bytes(round((delay * 60) / 1000), 4))
258 |
259 | # Now that we have gathered the data actually write the chunks...
260 | write_chunk(out, b"LIST", list_data)
261 | write_chunk(out, b"rate", delay_data)
262 |
263 | # Now we are to the end, get the length of the file and write it as the RIFF chunk length...
264 | entire_file_len = out.tell() - 8
265 | out.seek(4)
266 | out.write(to_bytes(entire_file_len, 4))
267 |
268 | @classmethod
269 | def get_identifier(cls) -> str:
270 | return "ani"
271 |
--------------------------------------------------------------------------------
/CursorCreate/lib/cur_format.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 | from typing import BinaryIO
3 |
4 | import numpy as np
5 | from PIL import Image
6 | from PIL.IcoImagePlugin import IcoFile
7 |
8 | from CursorCreate.lib.cursor import Cursor, CursorIcon
9 | from CursorCreate.lib.format_core import CursorStorageFormat, to_bytes, to_signed_bytes
10 |
11 | # The default dpi for BMP images written by this encoder...
12 | DEF_BMP_DPI = (96, 96)
13 |
14 |
15 | def _write_bmp(img: Image.Image, out_file: BinaryIO):
16 | # Grab the dpi for calculations later...
17 | dpi = img.info.get("dpi", DEF_BMP_DPI)
18 | ppm = tuple(int(dpi_val * 39.3701 + 0.5) for dpi_val in dpi)
19 |
20 | # BMP HEADER:
21 | out_file.write(to_bytes(40, 4)) # BMP Header size
22 | out_file.write(to_signed_bytes(img.size[0], 4)) # Image Width
23 | out_file.write(to_signed_bytes(img.size[1] * 2, 4)) # Image Height
24 | out_file.write(to_bytes(1, 2)) # Number of planes
25 | out_file.write(to_bytes(32, 2)) # The bits per pixel...
26 | out_file.write(
27 | to_bytes(0, 4)
28 | ) # The compression method, we set it to raw or no compression...
29 | out_file.write(
30 | to_bytes(4 * img.size[0] * (img.size[1] * 2), 4)
31 | ) # The size of the image data...
32 | out_file.write(
33 | to_signed_bytes(ppm[0], 4)
34 | ) # The resolution of the width in pixels per meter...
35 | out_file.write(
36 | to_signed_bytes(ppm[1], 4)
37 | ) # The resolution of the height in pixels per meter...
38 | out_file.write(
39 | to_bytes(0, 4)
40 | ) # The number of colors in the color table, in this case none...
41 | out_file.write(
42 | to_bytes(0, 4)
43 | ) # Number of important colors in the color table, again none...
44 |
45 | img = img.convert("RGBA")
46 | data = np.array(img)
47 | # Create the alpha channel...
48 | alpha_channel = data[:, :, 3]
49 | alpha_channel = np.packbits(alpha_channel == 0, axis=1)[::-1]
50 | # Create the main image with transparency...
51 | bgrx_data: np.ndarray = data[::-1, :, (2, 1, 0, 3)]
52 | # Dump the main image...
53 | out_file.write(bgrx_data.tobytes())
54 |
55 | # We now dump the mask and some zeros to finish filling the space...
56 | mask_data = alpha_channel.tobytes()
57 | leftover_space = (img.size[0] * img.size[1] * 4) - len(mask_data)
58 | out_file.write(mask_data)
59 | out_file.write(bytes(leftover_space))
60 |
61 |
62 | class CurFormat(CursorStorageFormat):
63 | """
64 | The windows .cur format, which is used for storing static cursors. It is a subset of the windows .ico format.
65 | Although windows supports placing png's in the cur rather then bmp images, it is poorly supported in the
66 | .ani decoder on windows so this encoder uses the older more well support nested bmp format.
67 | """
68 |
69 | MAGIC = b"\0\0\2\0"
70 | ICO_MAGIC = b"\0\0\1\0"
71 |
72 | @classmethod
73 | def check(cls, first_bytes) -> bool:
74 | """
75 | Check if the first bytes of this file match the windows .cur magic bytes.
76 |
77 | :param first_bytes: First 12 bytes of the file, this format actually only needs the first 4.
78 | :return: True if valid .cur, otherwise false...
79 | """
80 | return first_bytes[:4] == cls.MAGIC or first_bytes[:4] == cls.ICO_MAGIC
81 |
82 | @classmethod
83 | def read(cls, cur_file: BinaryIO) -> Cursor:
84 | """
85 | Read a cursor file in the windows .cur format.
86 |
87 | :param cur_file: The file or file-like object to read from.
88 | :return: A Cursor
89 | """
90 | magic_header = cur_file.read(4)
91 |
92 | if not cls.check(magic_header):
93 | raise SyntaxError("Not a Cur Type File!!!")
94 |
95 | is_ico = magic_header == cls.ICO_MAGIC
96 |
97 | # Dump the file with the ico header to allow to be read by Pillow Ico reader...
98 | data = BytesIO()
99 | data.write(cls.ICO_MAGIC)
100 | data.write(cur_file.read())
101 | data.seek(0)
102 |
103 | ico_img = IcoFile(data)
104 | cursor = Cursor()
105 |
106 | for head in ico_img.entry:
107 | width = head["width"]
108 | height = head["height"]
109 | x_hot = 0 if is_ico else head["planes"]
110 | y_hot = 0 if is_ico else head["bpp"]
111 |
112 | # Check that hotspots are valid...
113 | if not (0 <= x_hot < width):
114 | x_hot = 0
115 | if not (0 <= y_hot < height):
116 | y_hot = 0
117 |
118 | image = ico_img.getimage((width, height))
119 |
120 | cursor.add(CursorIcon(image, x_hot, y_hot))
121 |
122 | return cursor
123 |
124 | @classmethod
125 | def _to_png(cls, image: Image.Image, size) -> bytes:
126 | if image.size != size:
127 | raise ValueError(
128 | "Size of image stored in image and cursor object don't match!!!"
129 | )
130 | byte_io = BytesIO()
131 | image.save(byte_io, "png")
132 | return byte_io.getvalue()
133 |
134 | @classmethod
135 | def _to_bmp(cls, image: Image.Image, size) -> bytes:
136 | if image.size != size:
137 | raise ValueError(
138 | "Size of image stored in image and cursor object don't match!!!"
139 | )
140 | byte_io = BytesIO()
141 | _write_bmp(image, byte_io)
142 | return byte_io.getvalue()
143 |
144 | @classmethod
145 | def write(cls, cursor: Cursor, out: BinaryIO):
146 | """
147 | Writes cursor to a file in the form of the windows .cur format...
148 |
149 | :param cursor: The cursor object to save.
150 | :param out: The file handle to output the cursor to.
151 | """
152 | out.write(cls.MAGIC)
153 | out.write(to_bytes(len(cursor), 2))
154 |
155 | offset = out.tell() + len(cursor) * 16
156 | imgs = []
157 |
158 | for size in sorted(cursor):
159 | width, height = size
160 |
161 | if width > 256 or height > 256:
162 | continue
163 |
164 | hot_x, hot_y = cursor[size].hotspot
165 | hot_x, hot_y = (
166 | hot_x if (0 <= hot_x < width) else 0,
167 | hot_y if (0 <= hot_y < height) else 0,
168 | )
169 |
170 | image_data = cls._to_bmp(cursor[size].image, (width, height))
171 |
172 | width, height = (
173 | width if (width < 256) else 0,
174 | height if (height < 256) else 0,
175 | )
176 |
177 | out.write(to_bytes(width, 1)) # Width, 1 byte.
178 | out.write(to_bytes(height, 1)) # Height, 1 byte.
179 | out.write(b"\0\0")
180 | out.write(to_bytes(hot_x, 2))
181 | out.write(to_bytes(hot_y, 2))
182 | out.write(to_bytes(len(image_data), 4))
183 | out.write(to_bytes(offset, 4))
184 |
185 | offset += len(image_data)
186 | imgs.append(image_data)
187 |
188 | for image_data in imgs:
189 | out.write(image_data)
190 |
191 | @classmethod
192 | def get_identifier(cls) -> str:
193 | return "cur"
194 |
--------------------------------------------------------------------------------
/CursorCreate/lib/cur_theme.py:
--------------------------------------------------------------------------------
1 | import plistlib
2 |
3 | # For building archives dynamically in-place...
4 | import tarfile
5 | import zipfile
6 | from abc import ABC, abstractmethod
7 | from io import BytesIO, StringIO
8 | from pathlib import Path
9 | from typing import Any, Dict, List, Tuple, Type, Union
10 |
11 | import numpy as np
12 | from PIL import Image, ImageDraw
13 |
14 | from CursorCreate.lib.ani_format import AniFormat
15 | from CursorCreate.lib.cur_format import CurFormat
16 | from CursorCreate.lib.cursor import AnimatedCursor
17 | from CursorCreate.lib.xcur_format import XCursorFormat
18 |
19 |
20 | class CursorThemeBuilder(ABC):
21 | """
22 | Abstract class for representing theme builders for different platforms. Also includes a list of cursors which
23 | a cursor theme can provide, in a class variable call DEFAULT_CURSORS.
24 | """
25 |
26 | # List of cursors need to be supported for full theme support on all platforms...(Most for linux)
27 | DEFAULT_CURSORS = {
28 | "alias",
29 | "all-scroll",
30 | "bottom_left_corner",
31 | "bottom_right_corner",
32 | "bottom_side",
33 | "cell",
34 | "center_ptr",
35 | "col-resize",
36 | "color-picker",
37 | "context-menu",
38 | "copy",
39 | "crosshair",
40 | "default",
41 | "dnd-move",
42 | "dnd-no-drop",
43 | "down-arrow",
44 | "draft",
45 | "fleur",
46 | "help",
47 | "left-arrow",
48 | "left_side",
49 | "no-drop",
50 | "not-allowed",
51 | "openhand",
52 | "pencil",
53 | "pirate",
54 | "pointer",
55 | "progress",
56 | "right-arrow",
57 | "right_ptr",
58 | "right_side",
59 | "row-resize",
60 | "size_bdiag",
61 | "size_fdiag",
62 | "size_hor",
63 | "size_ver",
64 | "text",
65 | "top_left_corner",
66 | "top_right_corner",
67 | "top_side",
68 | "up-arrow",
69 | "vertical-text",
70 | "wait",
71 | "wayland-cursor",
72 | "x-cursor",
73 | "zoom-in",
74 | "zoom-out",
75 | }
76 |
77 | __ERROR_MSG = "Subclass doesn't implement this method!!!"
78 |
79 | @classmethod
80 | @abstractmethod
81 | def build_theme(
82 | cls,
83 | theme_name: str,
84 | metadata: Dict[str, Any],
85 | cursor_dict: Dict[str, AnimatedCursor],
86 | directory: Path,
87 | ):
88 | """
89 | Build the passed cursor theme for this platform...
90 |
91 | :param theme_name: The name of the Theme to build...
92 | :param metadata: A dictionary of string to any(mostly string) stores "author", "licence", and "licence_name".
93 | :param cursor_dict: A dictionary of cursor name to AnimatedCursor, specifying cursors and the types they
94 | are suppose to be. Look at the "DEFAULT_CURSORS" class variable in the CursorThemeBuilder
95 | class to see all valid types which a theme builder will accept...
96 | :param directory: The directory to build the theme for this platform in.
97 | """
98 | raise NotImplementedError(cls.__ERROR_MSG)
99 |
100 | @classmethod
101 | @abstractmethod
102 | def get_name(cls):
103 | """
104 | Get the name of this theme builder. Usually specifies the platform this theme builder applies to.
105 |
106 | :return: A string, the name of this theme builder"s platform.
107 | """
108 | raise NotImplementedError(cls.__ERROR_MSG)
109 |
110 |
111 | class ArchivePath:
112 | """
113 | For creating archive paths in .zip and .tar file. Provides basic path string manipulations...
114 | """
115 |
116 | def __init__(self, *path_seg):
117 | self._paths_segments = path_seg
118 |
119 | def __truediv__(self, other):
120 | return self._new_path(*self._paths_segments, other)
121 |
122 | def parent(self):
123 | return self._new_path(*self._paths_segments[:-1])
124 |
125 | def __str__(self):
126 | return "/".join(self._paths_segments)
127 |
128 | @classmethod
129 | def _new_path(cls, *path_seg):
130 | return cls(*path_seg)
131 |
132 |
133 | class LinuxThemeBuilder(CursorThemeBuilder):
134 | """
135 | The theme builder for the linux platform. Technically works for any platform which uses X-Org or Wayland
136 | (FreeBSD, etc.), but is called Linux as this is the most common platform known for using X-Org Cursor Theme
137 | Format for loading cursors. Generates a valid X-Org Cursor Theme which when placed in the ~/.icons or
138 | /usr/share/icons folder on linux becomes visible in the system settings and can be selected.
139 | """
140 |
141 | # All symlinks required by x-org cursor themes to be fully compatible with all software...
142 | SYM_LINKS_TO_CUR = {
143 | "e29285e634086352946a0e7090d73106": "pointer",
144 | "9d800788f1b08800ae810202380a0822": "pointer",
145 | "xterm": "text",
146 | "crossed_circle": "not-allowed",
147 | "1081e37283d90000800003c07f3ef6bf": "copy",
148 | "closedhand": "dnd-move",
149 | "hand2": "pointer",
150 | "hand1": "pointer",
151 | "sb_h_double_arrow": "size_hor",
152 | "a2a266d0498c3104214a47bd64ab0fc8": "alias",
153 | "split_h": "col-resize",
154 | "dnd-none": "dnd-move",
155 | "split_v": "row-resize",
156 | "3085a0e285430894940527032f8b26df": "alias",
157 | "5c6cd98b3f3ebcb1f9c7f1c204630408": "help",
158 | "fcf21c00b30f7e3f83fe0dfd12e71cff": "dnd-move",
159 | "left_ptr": "default",
160 | "circle": "not-allowed",
161 | "d9ce0ab605698f320427677b458ad60b": "help",
162 | "03b6e0fcb3499374a867c041f52298f0": "not-allowed",
163 | "size-hor": "default",
164 | "00008160000006810000408080010102": "size_ver",
165 | "size-ver": "default",
166 | "forbidden": "no-drop",
167 | "08e8e1c95fe2fc01f976f1e063a24ccd": "progress",
168 | "ibeam": "text",
169 | "4498f0e0c1937ffe01fd06f973665830": "dnd-move",
170 | "left_ptr_watch": "progress",
171 | "cross": "crosshair",
172 | "watch": "wait",
173 | "3ecb610c1bf2410f44200f48c40d3599": "progress",
174 | "link": "alias",
175 | "9081237383d90e509aa00f00170e968f": "dnd-move",
176 | "h_double_arrow": "size_hor",
177 | "640fb0e74195791501fd1ed57b41487f": "alias",
178 | "plus": "cell",
179 | "b66166c04f8c3109214a4fbd64a50fc8": "copy",
180 | "pointing_hand": "pointer",
181 | "size-bdiag": "default",
182 | "w-resize": "size_hor",
183 | "n-resize": "size_ver",
184 | "s-resize": "size_ver",
185 | "question_arrow": "help",
186 | "sb_v_double_arrow": "size_ver",
187 | "dnd-copy": "copy",
188 | "half-busy": "progress",
189 | "e-resize": "size_hor",
190 | "00000000000000020006000e7e9ffc3f": "progress",
191 | "top_left_arrow": "default",
192 | "whats_this": "help",
193 | "size-fdiag": "default",
194 | "move": "dnd-move",
195 | "v_double_arrow": "size_ver",
196 | "left_ptr_help": "help",
197 | "size_all": "fleur",
198 | "6407b0e94181790501fd1e167b474872": "copy",
199 | }
200 | # The file name which gives the preview in system settings...
201 | PREVIEW_FILE = "thumbnail.png"
202 | # The x-org index theme file name...
203 | THEME_FILE_NAME = "index.theme"
204 | # Name of file storing licence...
205 | LICENCE_FILE_NAME = "LICENSE.txt"
206 | # Legal export sizes...
207 | LEGAL_EXPORT_SIZES = {(32, 32), (48, 48), (64, 64), (128, 128)}
208 |
209 | @classmethod
210 | def _tarinfo(
211 | cls,
212 | name: ArchivePath,
213 | tar_type: bytes,
214 | data: Union[StringIO, BytesIO] = None,
215 | **other_args,
216 | ) -> tarfile.TarInfo:
217 | new_tarinfo = tarfile.TarInfo(str(name))
218 |
219 | if tar_type == tarfile.DIRTYPE:
220 | new_tarinfo.mode = 0o777
221 | else:
222 | new_tarinfo.mode = 0o666
223 |
224 | new_tarinfo.type = tar_type
225 | if data is not None:
226 | new_tarinfo.size = len(data.getvalue())
227 |
228 | for key, value in other_args.items():
229 | setattr(new_tarinfo, key, value)
230 |
231 | return new_tarinfo
232 |
233 | @classmethod
234 | def build_theme(
235 | cls,
236 | theme_name: str,
237 | metadata: Dict[str, Any],
238 | cursor_dict: Dict[str, AnimatedCursor],
239 | directory: Path,
240 | ):
241 | with tarfile.open(str(directory / (theme_name + ".tar.gz")), "w|gz") as tar:
242 | # Write the theme directory...
243 | theme_dir = ArchivePath(theme_name)
244 | tar.addfile(cls._tarinfo(theme_dir, tarfile.DIRTYPE))
245 |
246 | # Write the theme config file...
247 | theme_f = BytesIO()
248 | author = metadata.get("author", None)
249 | if author is not None:
250 | theme_f.write(
251 | f"# {theme_name} cursor theme created by {author}.\n".encode()
252 | )
253 | theme_f.write(f"[Icon Theme]\nName={theme_name}\n".encode())
254 | theme_f.seek(0)
255 |
256 | tar.addfile(
257 | cls._tarinfo(theme_dir / cls.THEME_FILE_NAME, tarfile.REGTYPE, theme_f),
258 | theme_f,
259 | )
260 |
261 | # If the license actually exists, write it to a file...
262 | licence_text = metadata.get("licence", None)
263 | if licence_text is not None:
264 | license_file = BytesIO(licence_text.encode())
265 | tar.addfile(
266 | cls._tarinfo(
267 | theme_dir / cls.LICENCE_FILE_NAME, tarfile.REGTYPE, license_file
268 | ),
269 | license_file,
270 | )
271 |
272 | cursor_dir = theme_dir / "cursors"
273 | tar.addfile(cls._tarinfo(cursor_dir, tarfile.DIRTYPE))
274 |
275 | # Write all of the cursors...
276 | for name, cursor in cursor_dict.items():
277 | cursor = cursor.copy()
278 | cursor.restrict_to_sizes(cls.LEGAL_EXPORT_SIZES)
279 |
280 | cur_out = BytesIO()
281 | XCursorFormat.write(cursor, cur_out)
282 | cur_out.seek(0)
283 | tar.addfile(
284 | cls._tarinfo(cursor_dir / name, tarfile.REGTYPE, cur_out), cur_out
285 | )
286 |
287 | # If default is in the cursor dictionary, create a preview file for this theme...
288 | if "default" in cursor_dict:
289 | d_cur = cursor_dict["default"]
290 | preview_out = BytesIO()
291 | d_cur[0][0][d_cur[0][0].max_size()].image.save(preview_out, "png")
292 | preview_out.seek(0)
293 | tar.addfile(
294 | cls._tarinfo(
295 | cursor_dir / cls.PREVIEW_FILE, tarfile.REGTYPE, preview_out
296 | ),
297 | preview_out,
298 | )
299 |
300 | # Create all required symlinks for linux theme to work fully....
301 | for link, link_to in cls.SYM_LINKS_TO_CUR.items():
302 | if link_to in cursor_dict:
303 | tar.addfile(
304 | cls._tarinfo(
305 | cursor_dir / link, tarfile.SYMTYPE, linkname=link_to
306 | )
307 | )
308 |
309 | @classmethod
310 | def get_name(cls):
311 | return "linux"
312 |
313 |
314 | # Window inf file template...
315 | WINDOWS_INF_FILE = """\
316 | ; Windows installer for {name} cursor theme{author}.
317 | ; Right click on this file ("install.inf"), and click "Install" to install the cursor theme.
318 | ; After installing, change the cursors via windows mouse pointer settings dialog.
319 |
320 | [Version]
321 | signature="$CHICAGO$"
322 |
323 | [DefaultInstall]
324 | CopyFiles = Scheme.Cur, Scheme.Txt
325 | AddReg = Scheme.Reg
326 |
327 | [DestinationDirs]
328 | Scheme.Cur = 10,"%CUR_DIR%"
329 | Scheme.Txt = 10,"%CUR_DIR%"
330 |
331 | [Scheme.Reg]
332 | HKCU,"Control Panel\Cursors\Schemes","%SCHEME_NAME%",,"{reg_list}"
333 |
334 | [Scheme.Cur]
335 | "install.inf"
336 | {cursor_list}
337 |
338 | {licence_txt}
339 |
340 | [Strings]
341 | CUR_DIR = "Cursors\{name}"
342 | SCHEME_NAME = "{name}"
343 | {cursor_reg_list}
344 | """
345 |
346 |
347 | class WindowsThemeBuilder(CursorThemeBuilder):
348 | """
349 | The theme builder for the windows platform. Takes a subset of the cursors which actually apply to the windows
350 | platform, converts them to windows formats, and then packages them in a folder with a install.inf file which
351 | will automatically move the cursors into the right system paths and add them to Registry as a cursor theme
352 | the user can set in the control panel.
353 | """
354 |
355 | # Converts cursor names specified in DEFAULT_CURSORS to the cursors for windows...
356 | LINUX_TO_WIN_CURSOR = {
357 | "default": ("pointer", "normal-select"),
358 | "help": ("help", "help-select"),
359 | "progress": ("work", "working-in-background"),
360 | "wait": ("busy", "busy"),
361 | "text": ("text", "text-select"),
362 | "no-drop": ("unavailable", "unavailable"),
363 | "size_ver": ("vert", "vertical-resize"),
364 | "size_hor": ("horz", "horizontal-resize"),
365 | "size_fdiag": ("dgn1", "diagonal-resize-1"),
366 | "size_bdiag": ("dgn2", "diagonal-resize-2"),
367 | "fleur": ("move", "move"),
368 | "pointer": ("link", "link-select"),
369 | "crosshair": ("cross", "precision-select"),
370 | "pencil": ("hand", "handwriting"),
371 | "up-arrow": ("alternate", "alt-select"),
372 | }
373 |
374 | # Order of cursor pseudo-names in the registry...
375 | REGISTRY_ORDER = [
376 | "pointer",
377 | "help",
378 | "work",
379 | "busy",
380 | "cross",
381 | "text",
382 | "hand",
383 | "unavailable",
384 | "vert",
385 | "horz",
386 | "dgn1",
387 | "dgn2",
388 | "move",
389 | "alternate",
390 | "link",
391 | ]
392 |
393 | # Legal export sizes...
394 | LEGAL_EXPORT_SIZES = {(32, 32), (48, 48), (64, 64)}
395 |
396 | # Name of file storing licence...
397 | LICENCE_FILE_NAME = "LICENSE.txt"
398 |
399 | @classmethod
400 | def build_theme(
401 | cls,
402 | theme_name: str,
403 | metadata: Dict[str, Any],
404 | cursor_dict: Dict[str, AnimatedCursor],
405 | directory: Path,
406 | ):
407 | with zipfile.ZipFile(str(directory / (theme_name + ".zip")), "w") as zip_f:
408 | theme_dir = ArchivePath(theme_name)
409 |
410 | win_cursors = {
411 | name: cursor
412 | for name, cursor in cursor_dict.items()
413 | if (name in cls.LINUX_TO_WIN_CURSOR)
414 | }
415 | reg_used = {cls.LINUX_TO_WIN_CURSOR[name][0] for name in win_cursors}
416 |
417 | reg_list = []
418 | for name in cls.REGISTRY_ORDER:
419 | reg_list.append(
420 | f"%10%\%CUR_DIR%\%{name}%" if (name in reg_used) else ""
421 | )
422 | reg_list = ",".join(reg_list)
423 |
424 | cursor_names = {}
425 | for name, cursor in win_cursors.items():
426 | cursor = cursor.copy()
427 | cursor.restrict_to_sizes(cls.LEGAL_EXPORT_SIZES)
428 | reg_name, file_name = cls.LINUX_TO_WIN_CURSOR[name]
429 |
430 | if len(cursor) == 0:
431 | continue
432 | elif len(cursor) == 1:
433 | file_name += ".cur"
434 | out_f = BytesIO()
435 | CurFormat.write(cursor[0][0], out_f)
436 | zip_f.writestr(str(theme_dir / file_name), out_f.getvalue())
437 | else:
438 | file_name += ".ani"
439 | out_f = BytesIO()
440 | AniFormat.write(cursor, out_f)
441 | zip_f.writestr(str(theme_dir / file_name), out_f.getvalue())
442 |
443 | cursor_names[reg_name] = file_name
444 |
445 | cursor_list = "\n".join(
446 | [f'"{file_name}"' for file_name in cursor_names.values()]
447 | )
448 | cursor_reg_list = "\n".join(
449 | [f'{name} = "{file_name}"' for name, file_name in cursor_names.items()]
450 | )
451 |
452 | licence_text = metadata.get("licence")
453 | if licence_text is not None:
454 | zip_f.writestr(str(theme_dir / cls.LICENCE_FILE_NAME), licence_text)
455 | licence_info = f"[Scheme.Txt]\n{cls.LICENCE_FILE_NAME}"
456 | else:
457 | licence_info = ""
458 |
459 | author = metadata.get("author", None)
460 | author = "" if (author is None) else f" by {author}"
461 |
462 | inf_file = WINDOWS_INF_FILE.format(
463 | name=theme_name,
464 | author=author,
465 | reg_list=reg_list,
466 | cursor_list=cursor_list,
467 | licence_txt=licence_info,
468 | cursor_reg_list=cursor_reg_list,
469 | )
470 |
471 | zip_f.writestr(str(theme_dir / "install.inf"), inf_file)
472 |
473 | # Set windows as the os it was created on such that permissions are not copied...
474 | for z_info in zip_f.filelist:
475 | z_info: zipfile.ZipInfo = z_info
476 | z_info.create_system = 0
477 |
478 | @classmethod
479 | def get_name(cls):
480 | return "windows"
481 |
482 |
483 | class MacOSMousecapeThemeBuilder(CursorThemeBuilder):
484 | """
485 | Cursor theme builder for the MacOS platform. MacOS doesn"t natively support themes, so we actually build a .cape
486 | file for the Mousecape software on Mac, which allows the user to change cursors. A cape file is a mac plist
487 | format(xml) containing each cursor as a dictionary. Animated images are stored vertically, in tiles.
488 | """
489 |
490 | # Converts cursor names to correct mac cursors
491 | LINUX_TO_MAC_CUR = {
492 | "default": (
493 | "com.apple.coregraphics.Arrow",
494 | "com.apple.coregraphics.ArrowCtx",
495 | "com.apple.coregraphics.Move",
496 | ),
497 | "alias": ("com.apple.coregraphics.Alias", "com.apple.cursor.2"),
498 | "wait": ("com.apple.coregraphics.Wait",),
499 | "text": ("com.apple.coregraphics.IBeam", "com.apple.coregraphics.IBeamXOR"),
500 | "no-drop": ("com.apple.cursor.3",),
501 | "progress": ("com.apple.cursor.4",),
502 | "copy": ("com.apple.cursor.5",),
503 | "crosshair": ("com.apple.cursor.7", "com.apple.cursor.8"),
504 | "dnd-move": ("com.apple.cursor.11",),
505 | "openhand": ("com.apple.cursor.12",),
506 | "pointer": ("com.apple.cursor.13",),
507 | "left_side": ("com.apple.cursor.17",),
508 | "right_side": ("com.apple.cursor.18",),
509 | "col-resize": ("com.apple.cursor.19",),
510 | "top_side": ("com.apple.cursor.21",),
511 | "bottom_side": ("com.apple.cursor.22",),
512 | "row-resize": ("com.apple.cursor.23",),
513 | "context-menu": ("com.apple.cursor.24",),
514 | "pirate": ("com.apple.cursor.25",),
515 | "vertical-text": ("com.apple.cursor.26",),
516 | "right-arrow": ("com.apple.cursor.27",),
517 | "size_hor": ("com.apple.cursor.28",),
518 | "size_bdiag": ("com.apple.cursor.30",),
519 | "up-arrow": ("com.apple.cursor.31",),
520 | "size_ver": ("com.apple.cursor.32",),
521 | "size_fdiag": ("com.apple.cursor.34",),
522 | "down-arrow": ("com.apple.cursor.36",),
523 | "left-arrow": ("com.apple.cursor.38",),
524 | "fleur": ("com.apple.cursor.39",),
525 | "help": ("com.apple.cursor.40",),
526 | "cell": ("com.apple.cursor.41", "com.apple.cursor.20"),
527 | "zoom-in": ("com.apple.cursor.42",),
528 | "zoom-out": ("com.apple.cursor.43",),
529 | }
530 |
531 | CURSOR_EXPORT_SIZES = [(32, 32), (64, 64), (160, 160)]
532 |
533 | Vec2D = Tuple[int, int]
534 |
535 | @classmethod
536 | def __unify_frames(
537 | cls, cur: AnimatedCursor
538 | ) -> Tuple[int, float, Vec2D, Vec2D, List[Image.Image]]:
539 | """
540 | Private method, takes a cursor and converts it into a vertically tiled image with a single delay and single
541 | hotspot. Uses some hacky shenanigans to do this. :)......
542 |
543 | :param cur: An AnimatedCursor
544 | :return: A tuple with:
545 | - Integer: Number of frames
546 | - Float: Delay in seconds for each frame.
547 | - Vec2D: Hotspot location.
548 | - Vec2D: Size of image
549 | - List[PIL.Image]: Image representations, at 1x, 2x, and 5x...
550 | """
551 | cur = cur.copy()
552 |
553 | delays = np.array([delay for sub_cur, delay in cur])
554 | cumulative_delay = np.cumsum(delays)
555 | half_avg = int(np.mean(delays) / 4)
556 | gcd_of_em = np.gcd.reduce(delays)
557 |
558 | unified_delay = max(gcd_of_em, half_avg)
559 | num_frames = cumulative_delay[-1] // unified_delay
560 |
561 | cur.restrict_to_sizes(cls.CURSOR_EXPORT_SIZES)
562 | new_images = [
563 | Image.new("RGBA", (size[0] * 2, (size[1] * 2) * num_frames), (0, 0, 0, 0))
564 | for size in cls.CURSOR_EXPORT_SIZES
565 | ]
566 |
567 | next_ani_frame = 1
568 | for current_out_frame in range(num_frames):
569 | time_in = current_out_frame * unified_delay
570 | while (next_ani_frame < len(cumulative_delay)) and (
571 | time_in >= cumulative_delay[next_ani_frame]
572 | ):
573 | next_ani_frame += 1
574 |
575 | for i, img in enumerate(new_images):
576 | current_size = cls.CURSOR_EXPORT_SIZES[i]
577 | current_cur = cur[next_ani_frame - 1][0][current_size]
578 | x_off = current_size[0] - current_cur.hotspot[0]
579 | y_off = ((current_size[1] * 2) * current_out_frame) + (
580 | current_size[1] - current_cur.hotspot[1]
581 | )
582 | img.paste(current_cur.image, (x_off, y_off))
583 |
584 | final_hotspot = (cls.CURSOR_EXPORT_SIZES[0][0], cls.CURSOR_EXPORT_SIZES[0][1])
585 | final_dims = (
586 | cls.CURSOR_EXPORT_SIZES[0][0] * 2,
587 | cls.CURSOR_EXPORT_SIZES[0][1] * 2,
588 | )
589 |
590 | return (
591 | int(num_frames),
592 | float(unified_delay) / 1000,
593 | final_hotspot,
594 | final_dims,
595 | new_images,
596 | )
597 |
598 | @classmethod
599 | def build_theme(
600 | cls,
601 | theme_name: str,
602 | metadata: Dict[str, Any],
603 | cursor_dict: Dict[str, AnimatedCursor],
604 | directory: Path,
605 | ):
606 | author = metadata.get("author", None)
607 |
608 | auth_str = "unknown" if (author is None) else "".join(author.lower().split())
609 | theme_str = "".join(theme_name.lower().split())
610 |
611 | plist_data = {
612 | "Author": author if (author is not None) else "",
613 | "CapeName": theme_name,
614 | "CapeVersion": 1.0,
615 | "Cloud": True,
616 | "Cursors": {},
617 | "HiDPI": True,
618 | "Identifier": ".".join(["com", auth_str, theme_str]),
619 | "MinimumVersion": 2.0,
620 | "Version": 2.0,
621 | }
622 |
623 | for name, cur in cursor_dict.items():
624 | if name in cls.LINUX_TO_MAC_CUR:
625 | mac_names = cls.LINUX_TO_MAC_CUR[name]
626 | num_frames, delay_secs, hotspot, size, images = cls.__unify_frames(cur)
627 | representations = []
628 |
629 | for img in images:
630 | b = BytesIO()
631 | img.save(b, "png")
632 | representations.append(b.getvalue())
633 |
634 | for mac_name in mac_names:
635 | plist_data["Cursors"][mac_name] = {
636 | "FrameCount": num_frames,
637 | "FrameDuration": delay_secs,
638 | "HotSpotX": float(hotspot[0]),
639 | "HotSpotY": float(hotspot[1]),
640 | "PointsWide": float(size[0]),
641 | "PointsHigh": float(size[1]),
642 | "Representations": representations,
643 | }
644 |
645 | licence = metadata.get("licence", None)
646 |
647 | if licence is not None:
648 | with (directory / "LICENSE.txt").open("w") as l:
649 | l.write(licence)
650 |
651 | with (directory / (theme_name + ".cape")).open("wb") as cape:
652 | plistlib.dump(plist_data, cape, fmt=plistlib.FMT_XML, sort_keys=True)
653 |
654 | @classmethod
655 | def get_name(cls):
656 | return "mousecape_macos"
657 |
658 |
659 | class PreviewPictureBuilder(CursorThemeBuilder):
660 | """
661 | Not really a theme builder, but constructs a transparent png image with all of the cursors arranged in a grid.
662 | This image is meant to be pasted on top of a background to provide a preview of your cursor theme if you plan
663 | on posting it on the internet or giving it to others...
664 | """
665 |
666 | SIZE_PER_CURSOR = 64
667 |
668 | CURSOR_ORDER = [
669 | "default",
670 | "alias",
671 | "copy",
672 | "context-menu",
673 | "help",
674 | "no-drop",
675 | "center_ptr",
676 | "right_ptr",
677 | "text",
678 | "vertical-text",
679 | "progress",
680 | "wait",
681 | "pointer",
682 | "openhand",
683 | "dnd-move",
684 | "dnd-no-drop",
685 | "not-allowed",
686 | "pirate",
687 | "draft",
688 | "pencil",
689 | "color-picker",
690 | "zoom-in",
691 | "zoom-out",
692 | "crosshair",
693 | "cell",
694 | "fleur",
695 | "all-scroll",
696 | "up-arrow",
697 | "right-arrow",
698 | "down-arrow",
699 | "left-arrow",
700 | "top_side",
701 | "right_side",
702 | "bottom_side",
703 | "left_side",
704 | "top_left_corner",
705 | "top_right_corner",
706 | "bottom_right_corner",
707 | "bottom_left_corner",
708 | "col-resize",
709 | "row-resize",
710 | "size_ver",
711 | "size_bdiag",
712 | "size_hor",
713 | "size_fdiag",
714 | "wayland-cursor",
715 | "x-cursor",
716 | ]
717 |
718 | @classmethod
719 | def build_theme(
720 | cls,
721 | theme_name: str,
722 | metadata: Dict[str, Any],
723 | cursor_dict: Dict[str, AnimatedCursor],
724 | directory: Path,
725 | ):
726 | cur_center = cls.SIZE_PER_CURSOR
727 | w_in_curs = int(np.ceil(np.sqrt(len(cursor_dict))))
728 | cur_w = cls.SIZE_PER_CURSOR * 2
729 |
730 | new_image = Image.new(
731 | "RGBA", (w_in_curs * cur_w, w_in_curs * cur_w), (0, 0, 0, 0)
732 | )
733 | drawer = ImageDraw.Draw(new_image)
734 |
735 | cursor_order_dict = {name: i for i, name in enumerate(cls.CURSOR_ORDER)}
736 |
737 | for i, name in enumerate(sorted(cursor_dict, key=cursor_order_dict.get)):
738 | lookup_s = (cls.SIZE_PER_CURSOR,) * 2
739 | cur = cursor_dict[name].copy()
740 | cur.restrict_to_sizes([lookup_s])
741 |
742 | x_center = ((i % w_in_curs) * cur_w) + cur_center
743 | y_center = ((i // w_in_curs) * cur_w) + cur_center
744 | x_img_off = x_center - cur[0][0][lookup_s].hotspot[0]
745 | y_img_off = y_center - cur[0][0][lookup_s].hotspot[1]
746 |
747 | for x_mult, y_mult in zip([0, 0, 1, -1], [1, -1, 0, 0]):
748 | x_cross_end = x_center + int(x_mult * cur_center * 0.25)
749 | y_cross_end = y_center + int(y_mult * cur_center * 0.25)
750 | drawer.line(
751 | (x_center, y_center, x_cross_end, y_cross_end),
752 | fill=(50, 50, 50, 150),
753 | width=3,
754 | )
755 | drawer.line(
756 | (x_center, y_center, x_cross_end, y_cross_end),
757 | fill=(205, 205, 205, 150),
758 | width=1,
759 | )
760 |
761 | cur_img = cur[0][0][lookup_s].image
762 | new_image.paste(cur_img, (x_img_off, y_img_off), cur_img)
763 |
764 | new_image.save(str(directory / f"{theme_name}_preview.png"), "png")
765 |
766 | @classmethod
767 | def get_name(cls):
768 | return "preview_picture"
769 |
770 |
771 | def get_theme_builders() -> List[Type[CursorThemeBuilder]]:
772 | """
773 | Returns all subclasses of CursorThemeBuilder or all cursor builders loaded into python currently.
774 |
775 | :return: A list of theme builders currently visible to the python interpreter...
776 | """
777 | # We have to do this as it doesn"t think types match...
778 | # noinspection PyTypeChecker
779 | return CursorThemeBuilder.__subclasses__()
780 |
--------------------------------------------------------------------------------
/CursorCreate/lib/cursor.py:
--------------------------------------------------------------------------------
1 | """
2 | Cursor Package:
3 | Provides core objects or data types for manipulating cursor data, including images, hotspots, and delays...
4 | """
5 |
6 | from typing import Iterable, Iterator, Tuple, Union
7 | from PIL import Image, ImageOps
8 |
9 |
10 | class CursorIcon:
11 | """
12 | Represents a single icon within a cursor of a unique size. Contains an image and a hotspot...
13 | """
14 |
15 | def __init__(self, img: Image, hot_x: int, hot_y: int):
16 | """
17 | Create a new CursorIcon, which represents a single picture of fixed size stored in a cursor. The image of
18 | this object can't be modified once set, but the hotspot can.
19 |
20 | :param img: The PIL Image representing the cursor bitmap...
21 | :param hot_x: The x location of the hotspot relative to the top right corner.
22 | :param hot_y: The y location of the
23 | """
24 | self._image: Image.Image = img
25 | self._hotspot = None
26 | self.hotspot = (hot_x, hot_y)
27 |
28 | @property
29 | def image(self) -> Image.Image:
30 | """
31 | Get the PIL Image of this icon within the cursor.
32 |
33 | :return: The image representing this cursor at a given size...
34 | """
35 | return self._image
36 |
37 | @property
38 | def hotspot(self) -> Tuple[int, int]:
39 | """
40 | Get or Set the hotspot of this cursor, being the x, y tuple representing the hotspot's offset from the top
41 | right corner of the image. Must land within the bounds of the actual image...
42 | """
43 | return self._hotspot
44 |
45 | @hotspot.setter
46 | def hotspot(self, value: Tuple[int, int]):
47 | new_x, new_y = int(value[0]), int(value[1])
48 |
49 | if not (
50 | (0 <= new_x < self.image.size[0]) and (0 <= new_y < self.image.size[1])
51 | ):
52 | raise ValueError(
53 | f"{(new_x, new_y)} is not a valid hotspot for cursor icon of size {self.image.size}!!!"
54 | )
55 |
56 | self._hotspot = (new_x, new_y)
57 |
58 |
59 | class Cursor:
60 | """
61 | Represents a static cursor. Stores image and hotspot data for unique sizes. CursorIcons are accessed by size...
62 | """
63 |
64 | def __init__(self, cursors: Iterable[CursorIcon] = None):
65 | """
66 | Construct a new cursor.
67 |
68 | :param cursors: Optional, an iterable of CursorIcons of which to initialize this cursor with
69 | """
70 | self._curs = {}
71 | if cursors is not None:
72 | self.extend(cursors)
73 |
74 | def add(self, cursor: CursorIcon):
75 | """
76 | Add a cursor icon to this cursor, or override a prior cursor icon if one of the same size already exists in
77 | this cursor object.
78 |
79 | :param cursor: The CursorIcon to add to this cursor...
80 | """
81 | self._curs[cursor.image.size] = cursor
82 |
83 | def extend(self, cursors: Iterable[CursorIcon]):
84 | """
85 | Add or update a sequence of CursorIcons to this cursor.
86 |
87 | :param cursors: A sequence of CursorIcons.
88 | """
89 | for cursor in cursors:
90 | self.add(cursor)
91 |
92 | def __getitem__(self, size: Tuple[int, int]) -> CursorIcon:
93 | """
94 | Return a CursorIcon stored in this cursor, provided it's size...
95 |
96 | :param size: The size of the CursorIcon to get from this cursor.
97 | :return: The CursorIcon of the same size. If it doesn't exist throws a KeyError...
98 | """
99 | return self._curs[size]
100 |
101 | def __iter__(self) -> Iterator[Tuple[int, int]]:
102 | """
103 | Iterate over all of the sizes of the CursorIcons stored in this cursor.
104 |
105 | :return: An iterator which iterates over all image sizes stored in this cursor object.
106 | """
107 | return self._curs.__iter__()
108 |
109 | def __contains__(self, size: Tuple[int, int]) -> bool:
110 | """
111 | Check if a CursorIcon of this size exists in the cursor object...
112 |
113 | :param size: The size to check for.
114 | :return: A boolean, True if the CursorIcon of this size exists in this cursor, false otherwise...
115 | """
116 | return size in self._curs
117 |
118 | def __delitem__(self, size: Tuple[int, int]):
119 | """
120 | Delete the specified CursorIcon of given size.
121 |
122 | :param size: The size of the CursorIcon to delete in this cursor object
123 | """
124 | del self._curs[size]
125 |
126 | def pop(self, size: Tuple[int, int]) -> CursorIcon:
127 | cursor_icon = self._curs[size]
128 | del self._curs[size]
129 | return cursor_icon
130 |
131 | def __len__(self) -> int:
132 | """
133 | Returns the total number of CursorIcons stored in this cursor object...
134 |
135 | :return: The 'length' of this cursor, or how many icons are stored in it...
136 | """
137 | return len(self._curs)
138 |
139 | def max_size(self) -> Union[Tuple[int, int], None]:
140 | """
141 | Get the size of the largest CursorIcon stored in this cursor. Will return None if this cursor object is empty...
142 | """
143 | if len(self) == 0:
144 | return None
145 | return max(iter(self), key=lambda s: s[0] * s[1])
146 |
147 | def add_sizes(self, sizes: Iterable[Tuple[int, int]]):
148 | """
149 | Add specified sizes to this cursor, by resizing cursors which already exist in this CursorIcon...
150 |
151 | :param sizes: An iterable of tuples of 2 integers, representing width-height pairs to be added as sizes to
152 | this cursor.
153 | """
154 | if len(self) == 0:
155 | raise ValueError("Cursor is empty!!! Can't add sizes!!!")
156 |
157 | max_size = self.max_size()
158 |
159 | for size in sizes:
160 | if size not in self:
161 | x_ratio, y_ratio = size[0] / max_size[0], size[1] / max_size[1]
162 |
163 | if x_ratio <= y_ratio:
164 | final_img_w = size[0]
165 | w_offset = 0
166 | final_img_h = (max_size[1] / max_size[0]) * final_img_w
167 | h_offset = (size[1] - final_img_h) / 2
168 | else:
169 | final_img_h = size[1]
170 | h_offset = 0
171 | final_img_w = (max_size[0] / max_size[1]) * final_img_h
172 | w_offset = (size[0] - final_img_w) / 2
173 |
174 | new_cur = ImageOps.pad(
175 | self[max_size].image, size, Image.LANCZOS
176 | ).resize(size, Image.LANCZOS)
177 |
178 | new_hx = (
179 | w_offset + (self[max_size].hotspot[0] / max_size[0]) * final_img_w
180 | )
181 | new_hy = (
182 | h_offset + (self[max_size].hotspot[1] / max_size[1]) * final_img_h
183 | )
184 | self.add(CursorIcon(new_cur, int(new_hx), int(new_hy)))
185 |
186 | def restrict_to_sizes(self, sizes: Iterable[Tuple[int, int]]):
187 | """
188 | Restricts the sizes stored in this cursor to only the sizes passed to this method, deleting the rest.
189 |
190 | :param sizes: An iterable of Tuples of two integers, used as the only sizes to keep.
191 | """
192 | sizes = set(sizes)
193 | self.add_sizes(sizes)
194 |
195 | for size in list(self):
196 | if size not in sizes:
197 | del self[size]
198 |
199 | def remove_non_square_sizes(self):
200 | """
201 | Remove all non-square sized cursors from this cursor object.
202 | """
203 | for size in list(self):
204 | if size[0] != size[1]:
205 | del self[size]
206 |
207 | def copy(self) -> "Cursor":
208 | """
209 | Creates a shallow copy of this cursor.
210 |
211 | :return: A shallow copy of this cursor, only copies the lookup table.
212 | """
213 | return Cursor(self._curs.values())
214 |
215 |
216 | class AnimatedCursor(list):
217 | """
218 | Represents an animated cursor. Is actually a subtype of list, storing its data in the form of a list of tuples,
219 | each tuple containing the Cursor object at that frame, and then the delay as an integer in milliseconds...
220 | """
221 |
222 | # NOTE: Delay unit is milliseconds...
223 | def __init__(
224 | self, cursors: Iterable[Cursor] = None, framerates: Iterable[int] = None
225 | ):
226 | """
227 | Create a new animated cursor.
228 |
229 | :param cursors: A list of cursor object to add as frames, optional.
230 | :param framerates: A list of integer frame rates in the form of milliseconds, optional also.
231 | """
232 | framerates = framerates if (framerates is not None) else []
233 | cursors = cursors if (cursors is not None) else []
234 |
235 | super().__init__(self)
236 | self.extend(zip(cursors, framerates))
237 |
238 | def normalize(self, init_sizes: Iterable[Tuple[int, int]] = None):
239 | """
240 | Normalize this animated cursor, by making sure all frames contain the same sizes. This is done by adding
241 | missing sizes...
242 |
243 | :param init_sizes: An Iterable of a tuple of integers, being width, height pairs. These are sizes which will
244 | be added to all the cursor frames in this animated cursor...
245 | :return:
246 | """
247 | if init_sizes is None:
248 | init_sizes = []
249 |
250 | sizes = set(init_sizes)
251 |
252 | for cursor, delay in self:
253 | sizes.update(set(cursor))
254 |
255 | for cursor, delay in self:
256 | cursor.add_sizes(sizes)
257 |
258 | def remove_non_square_sizes(self):
259 | """
260 | Remove all non-square sized cursors from this animated cursor object
261 | (done by removing them from all sub-cursor objects).
262 | """
263 | for cursor, delay in self:
264 | cursor.remove_non_square_sizes()
265 |
266 | def restrict_to_sizes(self, sizes: Iterable[Tuple[int, int]]):
267 | """
268 | Forces all cursors in this animated cursor to only contain the sizes passed to this method
269 |
270 | :param sizes: An iterable of tuples of two integers, representing the sizes to keep.
271 | """
272 | for cursor, delay in self:
273 | cursor.restrict_to_sizes(sizes)
274 |
275 | def copy(self) -> "AnimatedCursor":
276 | """
277 | Creates a shallow copy of this AnimatedCursor which contains shallow copies of the Cursor objects contained
278 | inside of it.
279 |
280 | :return: An AnimatedCursor
281 | """
282 | return AnimatedCursor(
283 | [cur.copy() for cur, delay in self], [delay for cur, delay in self]
284 | )
285 |
--------------------------------------------------------------------------------
/CursorCreate/lib/cursor_util.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 | from typing import BinaryIO, Tuple
3 |
4 | from PIL import Image, ImageOps, ImageSequence
5 | from CursorCreate.lib import format_core
6 | from CursorCreate.lib.cursor import AnimatedCursor, Cursor, CursorIcon
7 |
8 | # New SVG Support...
9 | from CursorCreate.gui.QtKit import QtWidgets, QtWebEngineWidgets, QtWebEngineCore, QtCore
10 | # Qt5 Fix...
11 | if(not hasattr(QtWebEngineCore, "QWebEnginePage")):
12 | QtWebEngineCore.QWebEnginePage = QtWebEngineWidgets.QWebEnginePage
13 | import base64
14 |
15 | # Some versions of pillow don't actually have this error, so just set this exception to the general case in this case.
16 | try:
17 | from PIL import UnidentifiedImageError
18 | except ImportError as e:
19 | UnidentifiedImageError = Exception
20 |
21 | # Default sizes which all cursors loaded with this module are normalized with...
22 | DEFAULT_SIZES = [(32, 32), (48, 48), (64, 64), (128, 128)]
23 | MAX_DEFAULT_SIZE = DEFAULT_SIZES[-1]
24 |
25 |
26 | def load_cursor_from_image(file: BinaryIO) -> AnimatedCursor:
27 | """
28 | Load a cursor from an image. Image is expected to be square. If it is not square, this method will slide
29 | horizontally across the image using a height * height square, loading each following square as next frame of the
30 | cursor with a delay of 100 and hotspots of (0, 0). Note this method supports all formats supported by the
31 | PIL or pillow Image library. If the image passed is an animated image format like .gif or .apng, this method
32 | will avoid loading in horizontal square tiles and will rather load in each frame of the image as each frame of
33 | the cursor.
34 |
35 | :param file: The file handler pointing to the image data.
36 | :return: An AnimatedCursor object, representing an animated cursor. Static cursors will only have 1 frame.
37 | """
38 | image: Image.Image = Image.open(file)
39 |
40 | if hasattr(image, "is_animated") and (image.is_animated):
41 | # If this is an animated file, load in each frame as the frames of the cursor (Ex, ".gif")
42 | min_dim = min(image.size) # We fit the image to a square...
43 | images_durations = [
44 | (ImageOps.fit(image, (min_dim, min_dim)), frame.info.get("duration", 100))
45 | for frame in ImageSequence.Iterator(image)
46 | ]
47 | else:
48 | # Separate all frames (Assumed to be stored horizontally)
49 | height = image.size[1]
50 | num_frames = image.size[0] // height
51 |
52 | if num_frames == 0:
53 | raise ValueError(
54 | "Image width is smaller then height so this will load as a 0 frame cursor!!!"
55 | )
56 |
57 | images_durations = [
58 | (image.crop((i * height, 0, i * height + height, height)), 100)
59 | for i in range(num_frames)
60 | ]
61 |
62 | # Now convert images into the cursors, resizing them to match all the default sizes...
63 | final_cursor = AnimatedCursor()
64 |
65 | for img, delay in images_durations:
66 | frame = Cursor()
67 |
68 | for size in DEFAULT_SIZES:
69 | frame.add(CursorIcon(img.resize(size, Image.LANCZOS), 0, 0))
70 |
71 | final_cursor.append((frame, delay))
72 |
73 | return final_cursor
74 |
75 |
76 | class _ChromiumSVGRenderer:
77 | SVG_SIZE_SCRIPT = """
78 | function get_svg_size() {{
79 | let img_text = '{svg_text}';
80 | let img = new Image();
81 |
82 | img.onload = () => console.log([img.naturalWidth, img.naturalHeight]);
83 | img.onerror = () => {{
84 | throw "Invalid svg image!";
85 | }};
86 | img.src = 'data:image/svg+xml;base64,' + img_text;
87 | }};
88 |
89 | get_svg_size();
90 | """.replace(
91 | "\n ", "\n"
92 | )
93 |
94 | SVG_RENDER_SCRIPT = """
95 | function render_svg() {{
96 | let img_text = '{svg_text}';
97 | let img = new Image();
98 |
99 | img.onload = () => {{
100 | let c = document.createElement("canvas");
101 | c.width = {width};
102 | c.height = {height};
103 | let painter = c.getContext('2d');
104 | painter.drawImage(img, 0, 0, {width}, {height});
105 | console.log(c.toDataURL().split(',')[1]);
106 | }};
107 | img.onerror = () => {{
108 | throw "Invalid svg image!";
109 | }};
110 | img.src = 'data:image/svg+xml;base64,' + img_text;
111 | }};
112 |
113 | render_svg();
114 | """.replace(
115 | "\n ", "\n"
116 | )
117 |
118 | class DumpPage(QtWebEngineCore.QWebEnginePage):
119 | JSMessageLevel = QtWebEngineCore.QWebEnginePage.JavaScriptConsoleMessageLevel
120 |
121 | def __init__(self, parent=None):
122 | super().__init__(parent)
123 | self.on_dump = None
124 |
125 | def javaScriptConsoleMessage(
126 | self, level: JSMessageLevel, message: str, line_number: int, source_id: str
127 | ) -> None:
128 | no_error = level == self.JSMessageLevel.InfoMessageLevel
129 | if self.on_dump is not None:
130 | self.on_dump(no_error, message)
131 |
132 | def __init__(self, parent=None):
133 | self._app = QtWidgets.QApplication.instance()
134 | if self._app is None:
135 | self._app = QtWidgets.QApplication([])
136 |
137 | self._web_engine = QtWebEngineWidgets.QWebEngineView(parent)
138 | self._page = self.DumpPage(self._web_engine)
139 | self._web_engine.setPage(self._page)
140 |
141 | @classmethod
142 | def _load_file_b64(cls, file: BinaryIO) -> str:
143 | file.seek(0)
144 | return base64.b64encode(file.read()).decode()
145 |
146 | def _run_script(self, script: str, **kwargs) -> str:
147 | loop = QtCore.QEventLoop()
148 | message = (False, "Could not load browser...")
149 |
150 | def on_dump(no_error, msg):
151 | nonlocal message
152 | message = (no_error, msg)
153 | loop.quit()
154 |
155 | self._page.on_dump = on_dump
156 | self._page.runJavaScript(script.format(**kwargs), 0)
157 | loop.exec_()
158 |
159 | if not message[0]:
160 | raise ValueError(f"Error while running script: {message[1]}")
161 |
162 | return str(message[1])
163 |
164 | def get_svg_size(self, file: BinaryIO) -> Tuple[int, int]:
165 | res = self._run_script(self.SVG_SIZE_SCRIPT, svg_text=self._load_file_b64(file))
166 | w, h = [int(v) for v in res.split(",")]
167 | return (w, h)
168 |
169 | def render_svg(self, file: BinaryIO, width: int, height: int) -> BinaryIO:
170 | res = self._run_script(
171 | self.SVG_RENDER_SCRIPT,
172 | svg_text=self._load_file_b64(file),
173 | width=width,
174 | height=height,
175 | )
176 |
177 | return BytesIO(base64.b64decode(res.encode()))
178 |
179 | def __del__(self):
180 | self._web_engine.destroy()
181 | del self._page
182 | del self._web_engine
183 |
184 |
185 | def load_cursor_from_svg(file: BinaryIO) -> AnimatedCursor:
186 | """
187 | Load a cursor from an SVG. SVG is expected to be square. If it is not square, this method will slide
188 | horizontally across the SVG using a height * height square, loading each following square as next frame of the
189 | cursor with a delay of 100 and hotspots of (0, 0). Note this method uses CairoSVG library to load and render
190 | SVGs of various sizes to bitmaps. For info on supported SVG features, look at the docs for the CairoSVG library.
191 |
192 | :param file: The file handler pointing to the SVG data.
193 | :return: An AnimatedCursor object, representing an animated cursor. Static cursors will only have 1 frame.
194 | """
195 | # Convert SVG in memory to PNG, and read that in with PIL to get the default size of the SVG...
196 | svg_renderer = _ChromiumSVGRenderer()
197 | w, h = svg_renderer.get_svg_size(file)
198 |
199 | # Compute height to width ratio an the number of frame(Assumes they are stored horizontally)...
200 | h_to_w_multiplier = w / h
201 | num_frames = int(h_to_w_multiplier)
202 |
203 | if num_frames == 0:
204 | raise ValueError(
205 | "Image width is smaller then height so this will load as a 0 frame cursor!!!"
206 | )
207 |
208 | # Build empty animated cursor to start stashing frames in...
209 | ani_cur = AnimatedCursor([Cursor() for __ in range(num_frames)], [100] * num_frames)
210 |
211 | for sizes in DEFAULT_SIZES:
212 | # For each default size, resize svg to it and add all frames to the AnimatedCursor object...
213 | image = svg_renderer.render_svg(
214 | file, int(sizes[1] * h_to_w_multiplier), sizes[1]
215 | )
216 | image = Image.open(image)
217 |
218 | height = image.size[1]
219 | for i in range(num_frames):
220 | ani_cur[i][0].add(
221 | CursorIcon(
222 | image.crop((i * height, 0, i * height + height, height)), 0, 0
223 | )
224 | )
225 |
226 | return ani_cur
227 |
228 |
229 | def load_cursor_from_cursor(file: BinaryIO) -> AnimatedCursor:
230 | """
231 | Loads a cursor from one of the supported cursor formats implemented in this library. Normalizes sizes and
232 | removes non-square versions of the cursor...
233 |
234 | :param file: The file handler pointing to the SVG data.
235 | :return: An AnimatedCursor object, representing an animated cursor. Static cursors will only have 1 frame.
236 | """
237 | # Currently supported cursor formats...
238 | ani_cur_readers = format_core.AnimatedCursorStorageFormat.__subclasses__()
239 | cur_readers = format_core.CursorStorageFormat.__subclasses__()
240 |
241 | file.seek(0)
242 | magic = file.read(12)
243 | file.seek(0)
244 |
245 | for reader in ani_cur_readers:
246 | if reader.check(magic):
247 | ani_cur = reader.read(file)
248 | ani_cur.normalize(DEFAULT_SIZES)
249 | ani_cur.remove_non_square_sizes()
250 | return ani_cur
251 |
252 | for reader in cur_readers:
253 | if reader.check(magic):
254 | ani_cur = AnimatedCursor([reader.read(file)], [100])
255 | ani_cur.normalize(DEFAULT_SIZES)
256 | ani_cur.remove_non_square_sizes()
257 | return ani_cur
258 |
259 | raise ValueError("Unsupported cursor format.")
260 |
261 |
262 | def load_cursor(file: BinaryIO):
263 | """
264 | Loads a cursor from any array of formats, including cursor formats (cur, ani, xcur), Images, and SVGs.
265 |
266 | :param file: The file handler pointing to a format which is convertible to a cursor.
267 | :return: A AnimatedCursor object, will contain a single frame if representing a static cursor...
268 |
269 | :raises: A ValueError if format is unknown (not a .svg, image, or cursor format) or if the width of the image is
270 | smaller than the height of the image, meaning it would be loaded as a 0-frame cursor (only applies to
271 | non-cursor formats)...
272 | """
273 | try:
274 | return load_cursor_from_cursor(file)
275 | except ValueError:
276 | file.seek(0)
277 | try:
278 | return load_cursor_from_image(file)
279 | except UnidentifiedImageError:
280 | file.seek(0)
281 | try:
282 | return load_cursor_from_svg(file)
283 | except ValueError:
284 | raise ValueError("Unable to open file by any specified methods...")
285 |
--------------------------------------------------------------------------------
/CursorCreate/lib/format_core.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from typing import BinaryIO
3 |
4 | from CursorCreate.lib.cursor import AnimatedCursor, Cursor
5 |
6 |
7 | def to_bytes(num: int, length: int, byteorder: str = "little") -> bytes:
8 | """
9 | Encode a python integer object as a unsigned n-bit length integer, stored in a bytes object
10 |
11 | :param num: The number to encode.
12 | :param length: The length of the unsigned integer to output, measured in bytes.
13 | :param byteorder: The byteorder. Valid options are "little" and "big"...
14 | :return: A bytes object encoding the unsigned integer of length bits...
15 | """
16 | return int.to_bytes(num, length, byteorder)
17 |
18 |
19 | def to_int(b: bytes, byteorder: str = "little") -> int:
20 | """
21 | Read in bytes as an unsigned integer...
22 |
23 | :param b: The bytes to decode to an unsigned integer...
24 | :param byteorder: The byteorder. Valid options are "little" and "big"...
25 | :return: An integer, represented by the bytes...
26 | """
27 | return int.from_bytes(b, byteorder)
28 |
29 |
30 | def to_signed_int(b, byteorder="little"):
31 | """
32 | Read in bytes as an signed integer...
33 |
34 | :param b: The bytes to decode to an signed integer...
35 | :param byteorder: The byteorder. Valid options are "little" and "big"...
36 | :return: A signed integer, represented by the bytes...
37 | """
38 | new_int = to_int(b, byteorder)
39 | power = 2 ** (len(b) * 8)
40 | signed_limit = (power // 2) - 1
41 | print(new_int, power, signed_limit)
42 |
43 | if new_int > signed_limit:
44 | new_int = -(power - new_int)
45 |
46 | return new_int
47 |
48 |
49 | def to_signed_bytes(num, length, byteorder="little"):
50 | """
51 | Encode a python integer object as a signed n-bit length integer, stored in a bytes object.
52 |
53 | :param num: The number to encode.
54 | :param length: The length of the signed integer to output, measured in bytes.
55 | :param byteorder: The byteorder. Valid options are "little" and "big"...
56 | :return: A bytes object encoding the signed integer of length bits...
57 | """
58 | power = 2 ** int(length * 8)
59 | limit = power // 2
60 | num = int(num)
61 |
62 | if not (-limit <= num < limit):
63 | raise ValueError(f"Integer {num} must be between {-limit} and {limit - 1}")
64 |
65 | return to_bytes((power + num) % power, length, byteorder)
66 |
67 |
68 | class CursorStorageFormat(ABC):
69 | """
70 | Abstract class for representing static cursor formats. It allows programs to read and write cursors to a specific
71 | file format. An example of a static cursor format is '.cur', the windows format for storing OS cursors.
72 | """
73 |
74 | __ERROR_MSG = "Subclass doesn't implement this method!!!"
75 |
76 | @classmethod
77 | @abstractmethod
78 | def check(cls, first_bytes):
79 | """
80 | Check and see if the specified file is of this format. Checks if the first bytes of this file match the
81 | expected 'magic' bytes for this format.
82 |
83 | :param first_bytes: The first 12 bytes of the file.
84 | :return: True if this file is of this format, otherwise False.
85 | """
86 | raise NotImplementedError(cls.__ERROR_MSG)
87 |
88 | @classmethod
89 | @abstractmethod
90 | def read(cls, cur_file: BinaryIO) -> AnimatedCursor:
91 | """
92 | Read in a file of this format as a static cursor.
93 |
94 | :param cur_file: A binary file handler pointing to the data which is desired to be open.
95 | :return: A Cursor object, representing a static cursor.
96 | """
97 | raise NotImplementedError(cls.__ERROR_MSG)
98 |
99 | @classmethod
100 | @abstractmethod
101 | def write(cls, cursor: Cursor, out: BinaryIO):
102 | """
103 | Write a static cursor in this format out to the specified file...
104 |
105 | :param cursor: A Cursor object, the static cursor to write to the file...
106 | :param out: The file which to write the cursor to in this format...
107 | """
108 | raise NotImplementedError(cls.__ERROR_MSG)
109 |
110 | @classmethod
111 | @abstractmethod
112 | def get_identifier(cls) -> str:
113 | """
114 | Get the identifier for this format. Is usually a 3-4 character string.
115 |
116 | :return: A string, representing this file format. Usually is the same as this files most common extension.
117 | """
118 | raise NotImplementedError(cls.__ERROR_MSG)
119 |
120 |
121 | class AnimatedCursorStorageFormat(ABC):
122 | __ERROR_MSG = "Subclass doesn't implement this method!!!"
123 |
124 | @classmethod
125 | @abstractmethod
126 | def check(cls, first_bytes):
127 | """
128 | Check and see if the specified file is of this format. Checks if the first bytes of this file match the
129 | expected 'magic' bytes for this format.
130 |
131 | :param first_bytes: The first 12 bytes of the file.
132 | :return: True if this file is of this format, otherwise False.
133 | """
134 | raise NotImplementedError(cls.__ERROR_MSG)
135 |
136 | @classmethod
137 | @abstractmethod
138 | def read(cls, cur_file: BinaryIO) -> AnimatedCursor:
139 | """
140 | Read in a file of this format as an animated cursor.
141 |
142 | :param cur_file: A binary file handler pointing to the data which is desired to be open.
143 | :return: A AnimatedCursor object, representing an animated cursor.
144 | """
145 | raise NotImplementedError(cls.__ERROR_MSG)
146 |
147 | @classmethod
148 | @abstractmethod
149 | def write(cls, cursor: AnimatedCursor, out: BinaryIO):
150 | """
151 | Write an animated cursor in this format out to the specified file...
152 |
153 | :param cursor: An AnimatedCursor object, the animated cursor to write to the file...
154 | :param out: The file which to write the cursor to in this format...
155 | """
156 | raise NotImplementedError(cls.__ERROR_MSG)
157 |
158 | @classmethod
159 | @abstractmethod
160 | def get_identifier(cls) -> str:
161 | """
162 | Get the identifier for this format. Is usually a 3-4 character string.
163 |
164 | :return: A string, representing this file format. Usually is the same as this files most common extension.
165 | """
166 | raise NotImplementedError(cls.__ERROR_MSG)
167 |
--------------------------------------------------------------------------------
/CursorCreate/lib/theme_util.py:
--------------------------------------------------------------------------------
1 | import json
2 | import shutil
3 | import traceback
4 | from pathlib import Path
5 | from typing import Any, Dict, Tuple, Union
6 |
7 | from PIL import Image
8 |
9 | from CursorCreate.lib import cursor_util
10 | from CursorCreate.lib.cur_theme import get_theme_builders
11 | from CursorCreate.lib.cursor import AnimatedCursor
12 |
13 | CURRENT_FORMAT_VERSION = 1
14 | CURRENT_FORMAT_NAME = "cursor_build_file"
15 |
16 |
17 | def build_theme(
18 | theme_name: str,
19 | directory: Path,
20 | metadata: Dict[str, Any],
21 | cursor_dict: Dict[str, AnimatedCursor],
22 | ):
23 | """
24 | Build the specified theme using all currently loaded theme builders, building it for all platforms...
25 |
26 | :param theme_name: The name of the theme.
27 | :param directory: The directory to build the new theme in.
28 | :param metadata: A dictionary of string to any(mostly string) stores "author", and "licence".
29 | :param cursor_dict: A dictionary of cursor name(string) to AnimatedCursor, specifying cursors and the types they
30 | are supposed to be. Look at the 'DEFAULT_CURSORS' class variable in the CursorThemeBuilder
31 | class to see all valid types which a theme builder will accept...
32 | """
33 | build_theme_in = directory / theme_name
34 | build_theme_in.mkdir(exist_ok=True)
35 | theme_builders = get_theme_builders()
36 |
37 | for theme_builder in theme_builders:
38 | try:
39 | ext_dir = build_theme_in / theme_builder.get_name()
40 | ext_dir.mkdir(exist_ok=True)
41 | theme_builder.build_theme(theme_name, metadata, cursor_dict, ext_dir)
42 | except Exception:
43 | traceback.print_exc()
44 |
45 |
46 | def _make_image(cursor: AnimatedCursor) -> Image:
47 | """
48 | PRIVATE METHOD:
49 | Make an image from a cursor, representing all of it's frames. Used by save_project to make project art files
50 | when original files can't be found and copied over, as the cursor was loaded from the clip board as an image
51 | or dragged and dropped from the internet...
52 |
53 | :param cursor: The cursor to convert to a tiled horizontal image.
54 | :return: An picture with frames stored horizontally...
55 | """
56 | cursor.normalize([(128, 128)])
57 | im = Image.new("RGBA", (128 * len(cursor), 128), (0, 0, 0, 0))
58 |
59 | for i, (cursor, delay) in enumerate(cursor):
60 | im.paste(cursor[(128, 128)].image, (128 * i, 0))
61 |
62 | return im
63 |
64 |
65 | def _disable_newlines(json_data: str, num_lines_in: int) -> str:
66 | """
67 | PRIVATE METHOD:
68 | Strip new lines in a json made by python's json parser a certain amount of blocks in. Used by save_project
69 | to write a cleaner json file.
70 |
71 | :param json_data: The json data to strip of new lines.
72 | :param num_lines_in: Number of json "blocks" in (blocks are defined by {} and [])
73 | :return: A cleaner json string with some new line characters stripped...
74 | """
75 | json_data = list(json_data)
76 | blocks = {"{": "}", "[": "]"}
77 | block_stack = []
78 | last_enter = None
79 |
80 | for i, value in enumerate(json_data):
81 | if value in blocks:
82 | block_stack.append(blocks[value])
83 | if len(block_stack) >= num_lines_in and json_data[i + 1] == "\n":
84 | json_data[i + 1] = ""
85 | elif (len(block_stack) > 0) and (block_stack[-1] == value):
86 | if len(block_stack) >= num_lines_in and last_enter is not None:
87 | json_data[last_enter] = ""
88 | block_stack.pop()
89 | elif (len(block_stack) >= num_lines_in) and (value == "\n"):
90 | json_data[i] = " "
91 | last_enter = i
92 | elif (len(block_stack) >= num_lines_in) and (value.isspace()):
93 | json_data[i] = ""
94 |
95 | return "".join(json_data)
96 |
97 |
98 | def save_project(
99 | theme_name: str,
100 | directory: Path,
101 | metadata: Dict[str, Any],
102 | file_dict: Dict[str, Tuple[Path, AnimatedCursor]],
103 | ):
104 | """
105 | Save the cursor project to the cursor project format, which includes all source images and a build.json which
106 | specifies how to build the platform dependent cursor themes from the source images.
107 |
108 | :param theme_name: The name of this new project.
109 | :param directory: The directory to save the new project in.
110 | :param metadata: A dictionary of string to any(mostly string) stores "author", and "licence".
111 | :param file_dict: A dictionary of cursor name(string) to a tuple of source file and AnimatedCursor, specifying
112 | cursors, there source files and the types they are suppose to be. Look at the 'DEFAULT_CURSORS'
113 | class variable in the CursorThemeBuilder class to see all valid types which a theme builder
114 | will accept... The source files will be copied into the project's main directory if available,
115 | otherwise a tiled png will be made from the animated cursor object included...
116 | """
117 | build_theme_in = directory / theme_name
118 | build_theme_in.mkdir(exist_ok=True)
119 |
120 | json_obj = {
121 | "format": CURRENT_FORMAT_NAME,
122 | "version": CURRENT_FORMAT_VERSION,
123 | "metadata": metadata,
124 | "data": [],
125 | }
126 |
127 | for name, (file, cursor) in file_dict.items():
128 | cursor.normalize([(64, 64)])
129 |
130 | if file is not None:
131 | new_file = build_theme_in / (name + file.suffix)
132 | if Path(file) != Path(new_file):
133 | shutil.copy(str(file), str(new_file))
134 | else:
135 | new_file = build_theme_in / (name + ".png")
136 | _make_image(cursor).save(str(new_file), "PNG")
137 |
138 | json_obj["data"].append(
139 | {
140 | "cursor_name": name,
141 | "cursor_file": new_file.name,
142 | "hotspots_64": [
143 | sub_cursor[(64, 64)].hotspot for sub_cursor, delay in cursor
144 | ],
145 | "delays": [delay for sub_cursor, delay in cursor],
146 | }
147 | )
148 |
149 | with (build_theme_in / "build.json").open("w") as fp:
150 | fp.write(_disable_newlines(json.dumps(json_obj, indent=4), 4))
151 |
152 |
153 | def load_project(
154 | theme_build_file: Path,
155 | ) -> Union[None, Tuple[Dict[str, Any], Dict[str, Tuple[Path, AnimatedCursor]]]]:
156 | """
157 | Load a cursor theme project from it's build.json file, and return it's (source file, cursor) dictionary...
158 |
159 | :param theme_build_file: The path to the build.json of this cursor theme project.
160 | :return: A tuple, containing 2 items in order:
161 | - dictionary of string -> any. Contains metadata, including the licence, author, and etc.
162 | - dictionary of name(string) -> (source file path, cursor). This specifies all data needed to build the
163 | cursor project.
164 | """
165 | theme_build_dir = theme_build_file.resolve().parent
166 |
167 | with theme_build_file.open("r") as f:
168 | json_build_data = json.load(f)
169 |
170 | is_format = ("format" in json_build_data) and (
171 | json_build_data["format"] == CURRENT_FORMAT_NAME
172 | )
173 | is_version = ("version" in json_build_data) and (
174 | json_build_data["version"] == CURRENT_FORMAT_VERSION
175 | )
176 |
177 | file_cur_dict = {}
178 |
179 | if "metadata" in json_build_data:
180 | metadata_info = json_build_data["metadata"]
181 | else:
182 | metadata_info = {
183 | "author": None,
184 | "licence": None,
185 | }
186 |
187 | if (not is_format) or (not is_version):
188 | return None
189 |
190 | for cursor_info in json_build_data["data"]:
191 | cursor_path = theme_build_dir / cursor_info["cursor_file"]
192 |
193 | with cursor_path.open("rb") as cur_file:
194 | cursor = cursor_util.load_cursor(cur_file)
195 |
196 | for i, delay in enumerate(cursor_info["delays"]):
197 | cursor[i] = (cursor[i][0], delay)
198 |
199 | for hotspot, (sub_cursor, delay) in zip(cursor_info["hotspots_64"], cursor):
200 | for size in sub_cursor:
201 | x_hot, y_hot = (
202 | int((size[0] / 64) * hotspot[0]),
203 | int((size[1] / 64) * hotspot[1])
204 | )
205 | sub_cursor[size].hotspot = (x_hot, y_hot)
206 |
207 | file_cur_dict[cursor_info["cursor_name"]] = (cursor_path, cursor)
208 |
209 | return metadata_info, file_cur_dict
210 |
--------------------------------------------------------------------------------
/CursorCreate/lib/xcur_format.py:
--------------------------------------------------------------------------------
1 | from typing import BinaryIO, Tuple
2 |
3 | import numpy as np
4 | from PIL import Image
5 |
6 | from CursorCreate.lib.cursor import AnimatedCursor, Cursor, CursorIcon
7 | from CursorCreate.lib.format_core import AnimatedCursorStorageFormat, to_bytes, to_int
8 |
9 |
10 | class XCursorFormat(AnimatedCursorStorageFormat):
11 | """
12 | The linux for X-Org format for storing cursor, both animated and static. Contains "XCur" magic followed by the
13 | number of entries in the file. Each entry is 16 bytes and contains the type, subtype, offset, and length. Out
14 | in memory at the offset is another header which gives the type and subtype again and then gives the
15 | width, height, x hotspot, y hotspot, and the delay, followed by BGRA image data. Note all attributes in this format
16 | are stored as 4 byte or 32 bit little endian unsigned integers except image data described above.
17 | """
18 |
19 | MAGIC = b"Xcur"
20 | VERSION = 65536
21 | CURSOR_TYPE = 0xFFFD0002
22 | HEADER_SIZE = 16
23 | IMG_CHUNK_H_SIZE = 36
24 | # The downscaling factor of the nominal size...
25 | SIZE_SCALING_FACTOR = 3 / 4
26 |
27 | @classmethod
28 | def check(cls, first_bytes):
29 | """
30 | Check if the first bytes of this file are a valid x-org cursor file
31 |
32 | :param first_bytes: The first 12 bytes of the file being tested.
33 | :return: True if a valid x-org cursor file, otherwise False.
34 | """
35 | return first_bytes[:4] == cls.MAGIC
36 |
37 | @classmethod
38 | def _assert(cls, boolean, msg="Something is wrong!!!"):
39 | """Private, used for throwing exceptions when assertions don't hold while reading the format."""
40 | if not boolean:
41 | raise SyntaxError(msg)
42 |
43 | @classmethod
44 | def read(cls, cur_file: BinaryIO) -> AnimatedCursor:
45 | """
46 | Read an xcur or X-Org cursor file from the specified file buffer.
47 |
48 | :param cur_file: The file buffer with xcursor data.
49 | :return: An AnimatedCursor object, non-animated cursors will contain only 1 frame.
50 | """
51 | magic_data = cur_file.read(4)
52 |
53 | cls._assert(cls.check(magic_data), "Not a XCursor File!!!")
54 |
55 | header_size = to_int(cur_file.read(4))
56 | cls._assert(
57 | header_size == cls.HEADER_SIZE, f"Header size is not {cls.HEADER_SIZE}!"
58 | )
59 | version = to_int(cur_file.read(4))
60 |
61 | # Number of cursors...
62 | num_toc = to_int(cur_file.read(4))
63 | # Used to store cursor offsets per size...
64 | nominal_sizes = {}
65 |
66 | for i in range(num_toc):
67 | main_type = to_int(cur_file.read(4))
68 |
69 | if main_type == cls.CURSOR_TYPE:
70 | nominal_size = to_int(cur_file.read(4))
71 | offset = to_int(cur_file.read(4))
72 |
73 | if nominal_size not in nominal_sizes:
74 | nominal_sizes[nominal_size] = [offset]
75 | else:
76 | nominal_sizes[nominal_size].append(offset)
77 |
78 | max_len = max(len(nominal_sizes[size]) for size in nominal_sizes)
79 | cursors = []
80 | delays = []
81 |
82 | for i in range(max_len):
83 | cursor = Cursor()
84 | sub_delays = []
85 |
86 | for size, offsets in nominal_sizes.items():
87 | if i < len(offsets):
88 | img, x_hot, y_hot, delay = cls._read_chunk(
89 | offsets[i], cur_file, size
90 | )
91 | cursor.add(CursorIcon(img, x_hot, y_hot))
92 | sub_delays.append(delay)
93 |
94 | cursors.append(cursor)
95 | delays.append(max(sub_delays))
96 |
97 | return AnimatedCursor(cursors, delays)
98 |
99 | @classmethod
100 | def _read_chunk(
101 | cls, offset: int, buffer: BinaryIO, nominal_size: int
102 | ) -> Tuple[Image.Image, int, int, int]:
103 | buffer.seek(offset)
104 | # Begin to check if this is valid...
105 | chunk_size = to_int(buffer.read(4))
106 | cls._assert(
107 | chunk_size == cls.IMG_CHUNK_H_SIZE,
108 | f"Image chunks must be {cls.IMG_CHUNK_H_SIZE} bytes!",
109 | )
110 | cls._assert(
111 | to_int(buffer.read(4)) == cls.CURSOR_TYPE,
112 | f"Type does not match type in TOC!",
113 | )
114 | cls._assert(
115 | to_int(buffer.read(4)) == nominal_size,
116 | f"Nominal sizes in TOC and image header don't match!",
117 | )
118 | cls._assert(
119 | to_int(buffer.read(4)) == 1, f"Unsupported version of image header..."
120 | )
121 | # Checks are done, load the rest of the header as we are good from here...
122 | rest_of_chunk = buffer.read(20)
123 | width, height, x_hot, y_hot, delay = [
124 | to_int(rest_of_chunk[i : i + 4]) for i in range(0, len(rest_of_chunk), 4)
125 | ]
126 |
127 | cls._assert(width <= 0x7FFF, "Invalid width!")
128 | cls._assert(height <= 0x7FFF, "Invalid height!")
129 |
130 | x_hot, y_hot = (
131 | x_hot if (0 <= x_hot < width) else 0,
132 | y_hot if (0 <= y_hot < height) else 0,
133 | )
134 |
135 | img_data = np.frombuffer(
136 | buffer.read(width * height * 4), dtype=np.uint8
137 | ).reshape(width, height, 4)
138 |
139 | # ARGB packed in little endian format, therefore its actually BGRA when read sequentially....
140 | image = Image.fromarray(img_data[:, :, (2, 1, 0, 3)], "RGBA")
141 |
142 | return image, x_hot, y_hot, delay
143 |
144 | @classmethod
145 | def write(cls, cursor: AnimatedCursor, out: BinaryIO):
146 | """
147 | Write an AnimatedCursor to the specified file in the X-Org cursor format.
148 |
149 | :param cursor: The AnimatedCursor object to write.
150 | :param out: The file buffer to write the new X-Org Cursor data to.
151 | """
152 | cursor = cursor.copy()
153 | cursor.normalize()
154 |
155 | if len(cursor) == 0:
156 | return
157 |
158 | num_curs = sum(len(length) for length, delay in cursor)
159 |
160 | out.write(cls.MAGIC)
161 | out.write(to_bytes(cls.HEADER_SIZE, 4))
162 | out.write(to_bytes(cls.VERSION, 4))
163 |
164 | out.write(to_bytes(num_curs, 4))
165 | # The initial offset...
166 | offset = num_curs * 12 + cls.HEADER_SIZE
167 |
168 | sorted_sizes = sorted(cursor[0][0])
169 |
170 | # Write the Table of contents [type, subtype(size), offset]
171 | for size in sorted_sizes:
172 | for sub_cur, delay in cursor:
173 | out.write(to_bytes(cls.CURSOR_TYPE, 4))
174 | out.write(to_bytes(int(size[0] * cls.SIZE_SCALING_FACTOR), 4))
175 | out.write(to_bytes(offset, 4))
176 | offset += cls.IMG_CHUNK_H_SIZE + (size[0] * size[1] * 4)
177 |
178 | # Write the actual images...
179 | for size in sorted_sizes:
180 | for sub_cur, delay in cursor:
181 | cls._write_chunk(out, sub_cur[size], delay)
182 |
183 | @classmethod
184 | def _write_chunk(cls, out_file: BinaryIO, img: CursorIcon, delay: int):
185 | out_file.write(to_bytes(cls.IMG_CHUNK_H_SIZE, 4))
186 | out_file.write(to_bytes(cls.CURSOR_TYPE, 4))
187 | out_file.write(to_bytes(int(img.image.size[0] * cls.SIZE_SCALING_FACTOR), 4))
188 | out_file.write(to_bytes(1, 4))
189 |
190 | # The width and height...
191 | width, height = img.image.size
192 | x_hot, y_hot = img.hotspot
193 | cls._assert(width <= 0x7FFF, "Invalid width!")
194 | cls._assert(height <= 0x7FFF, "Invalid height!")
195 | out_file.write(to_bytes(width, 4))
196 | out_file.write(to_bytes(width, 4))
197 | x_hot, y_hot = (
198 | x_hot if (0 <= x_hot < width) else 0,
199 | y_hot if (0 <= y_hot < height) else 0,
200 | )
201 |
202 | # Hotspot and delay...
203 | out_file.write(to_bytes(x_hot, 4))
204 | out_file.write(to_bytes(y_hot, 4))
205 | out_file.write(to_bytes(delay, 4))
206 |
207 | # Now the image, ARGB packed in little endian integers...(So really BGRA)(ARGB -> BGRA)
208 | im_bytes = (np.asarray(img.image.convert("RGBA"))[:, :, (2, 1, 0, 3)]).tobytes()
209 | out_file.write(im_bytes)
210 |
211 | @classmethod
212 | def get_identifier(cls) -> str:
213 | return "xcur"
214 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CursorCreate
2 | A Multi-platform Cursor Theme Building Program.
3 |
4 | CursorCreate allows you to build cursor themes for Windows, MacOS, and Linux. It supports reading cursors from svg, xcur, cur, ani, and all image formats supported by the Pillow imaging library. Also includes a GUI for easily modifying cursor projects.
5 |
6 | ### Installing
7 |
8 | #### Packaged Binaries:
9 |
10 | If you would like to avoid going through the process of installing from source, pre-built binaries have been provided on the releases page. Just download the one for your platform, extract the zip file, and run the executable inside the extracted folder.
11 |
12 | Releases Page:
13 | [https://github.com/isaacrobinson2000/CursorCreate/releases](https://github.com/isaacrobinson2000/CursorCreate/releases)
14 |
15 | #### From PyPI:
16 |
17 | CursorCreate is also available on PyPI. To install it, execute the command below:
18 | ```bash
19 | pip install CursorCreate
20 | ```
21 | Once it is installed, it can be executed using the `CursorCreate` command in the shell:
22 | ```bash
23 | # Launch the GUI:
24 | CursorCreate
25 | # List all command line options:
26 | CursorCreate --help
27 | ```
28 |
29 | #### From Source:
30 |
31 | To install CursorCreate from source, you will need the dependencies for
32 | CursorCreate, which can be done using the requirements.txt as shown below:
33 | ```bash
34 | pip install -r requirements.txt
35 | ```
36 |
37 | Once all the dependencies are installed in your python environment (using a virtual environment is recommended) you can pull down this repository using a git clone as below:
38 |
39 | ```bash
40 | git clone https://github.com/isaacrobinson2000/CursorCreate.git
41 | ```
42 |
43 | If you are attempting to package CursorCreate for your platform, you will need nuitka installed to the virtual environment. Use the build scripts provided with this project (`build_windows.bat`, `build_linux.sh`, or `build_mac.sh`), as the scripts provide flags for including all the dependencies and making the executables standalone.
44 |
45 | ### Example Theme
46 |
47 | This program also comes with a template theme, but due to separate licensing the template theme is kept in a separate repository. Follow the link below to get the template theme:
48 |
49 | [https://github.com/isaacrobinson2000/CursorCreateTemplateTheme](https://github.com/isaacrobinson2000/CursorCreateTemplateTheme)
50 |
51 | ### How to Use
52 |
53 | To launch the GUI, simply execute the CursorCreate entry file, as below:
54 | ```bash
55 | # If you installed via prepackaged binary (Have to be in the same directory as the executable):
56 | ./CursorCreate
57 | # If you installed via PyPI (pip install):
58 | CursorCreate
59 | # If you are running it from source:
60 | python CursorCreate/cursorcreate.py
61 | ```
62 | In the GUI, images can simply be dragged and dropped onto the cursor selection widgets in order to load them in. The hotspots and delays of animation frames can be modified by simply clicking on the cursor, as shown below:
63 |
64 | 
65 | 
66 |
67 | To save a project, click the "Save Project" button, which will copy the source image files over to the user selected directory and generate a 'build.json' which tells CursorCreate how to turn the image source files into cursor themes for each platform.
68 |
69 | For static images and SVGs, the animation frames are expected to be stored horizontally as squares side by side.
70 |
71 | Note that CursorCreate is also capable of doing several actions from the command line, including building cursor themes. To see all the supported command line operations, execute the command below:
72 | ```bash
73 | # If you installed via prepackaged binary (Have to be in the same directory as the executable):
74 | ./CursorCreate --help
75 | # If you installed via PyPI (pip install):
76 | CursorCreate --help
77 | # If you are running it from source:
78 | python CursorCreate/cursorcreate.py --help
79 | ```
80 |
81 | ### Bugs/Issues
82 |
83 | This software is currently in beta, and therefore may have some bugs. If you run into any issues, feel free to open an issue on the GitHub [issues](https://github.com/isaacrobinson2000/CursorCreate/issues) page.
84 |
85 | ### Future Goals
86 |
87 | - [x] Create a setup.py for CursorCreate
88 | - [ ] Add progress indicators when building cursors or performing any other action.
89 |
--------------------------------------------------------------------------------
/build_executable.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import os
3 | import sys
4 | from pathlib import Path
5 |
6 | script_folder = Path(__file__).resolve().parent
7 |
8 | env = os.environ.copy()
9 | # Import QtKit to figure out what Qt library is being used...
10 | import CursorCreate.gui.QtKit as QtKit
11 | env["PYTHON_QT_LIB"] = QtKit.__name__
12 |
13 | if(sys.platform.startswith("win")):
14 | command = "python -m nuitka --standalone --onefile --windows-disable-console --windows-icon-from-ico=icon_windows.ico --enable-plugin=pyside6 --enable-plugin=numpy CursorCreate/cursorcreate.py"
15 | elif(sys.platform.startswith("linux")):
16 | command = "python -m nuitka --standalone --onefile --linux-onefile-icon=icon_linux.xpm --enable-plugin=pyside6 --enable-plugin=numpy CursorCreate/cursorcreate.py"
17 | elif(sys.platform.startswith("darwin")):
18 | # Would be nice to use nuitka at some point...
19 | # command = "python -m nuitka --standalone --onefile --macos-create-app-bundle --macos-disable-console --macos-onefile-icon=icon_mac.icns --enable-plugin=pyside6 --enable-plugin=numpy CursorCreate/cursorcreate.py"
20 | command = "pyinstaller CursorCreate.spec"
21 | else:
22 | raise EnvironmentError(f"Unsupported Platform: {sys.platform}")
23 |
24 | # Run the command...
25 | print("Building an executable...")
26 | process = subprocess.run(command.split(), env=env, cwd=script_folder)
27 |
--------------------------------------------------------------------------------
/icon_linux.xpm:
--------------------------------------------------------------------------------
1 | /* XPM */
2 | static char *icon_linux[] = {
3 | /* columns rows colors chars-per-pixel */
4 | "48 48 158 2 ",
5 | " c None",
6 | ". c #536376",
7 | "X c #55667A",
8 | "o c #5C6B7E",
9 | "O c #5E6E81",
10 | "+ c #5F7083",
11 | "@ c #606F81",
12 | "# c #627285",
13 | "$ c #687687",
14 | "% c #64768A",
15 | "& c #6B7A8D",
16 | "* c #6C7E92",
17 | "= c #6F8295",
18 | "- c #738292",
19 | "; c #788594",
20 | ": c #7C8896",
21 | "> c #738699",
22 | ", c #768A9C",
23 | "< c #7B8C9E",
24 | "1 c #7D91A3",
25 | "2 c #818D9B",
26 | "3 c #84949C",
27 | "4 c #8297A6",
28 | "5 c #8A95A2",
29 | "6 c #879FA4",
30 | "7 c #8C9DA6",
31 | "8 c #8399A9",
32 | "9 c #899FAE",
33 | "0 c #939EA8",
34 | "q c #8297B1",
35 | "w c #859AB3",
36 | "e c #8B9DB4",
37 | "r c #8D9FB9",
38 | "t c #8DA2A7",
39 | "y c #8DA5AC",
40 | "u c #8DA2B4",
41 | "i c #8CA1BA",
42 | "p c #91A2B3",
43 | "a c #9AA6B0",
44 | "s c #93AAB4",
45 | "d c #9CAFB3",
46 | "f c #94A5BA",
47 | "g c #96AAB9",
48 | "h c #9BACBD",
49 | "j c #97B0B6",
50 | "k c #97B1B8",
51 | "l c #9CB4BE",
52 | "z c #A2AFB7",
53 | "x c #A5B2B5",
54 | "c c #A4B6BC",
55 | "v c #ACB9BD",
56 | "b c #9FB8C2",
57 | "n c #A2B4C1",
58 | "m c #A4BAC5",
59 | "M c #ACBCC4",
60 | "N c #ACBEC9",
61 | "B c #ABC0C6",
62 | "V c #A7C0C9",
63 | "C c #ABC4CC",
64 | "Z c #B4C2C6",
65 | "A c #B3C4CC",
66 | "S c #B4C9CE",
67 | "D c #BECBCE",
68 | "F c #AFC9D1",
69 | "G c #B3CCD3",
70 | "H c #BCCCD2",
71 | "J c #B6D0D7",
72 | "K c #BCD0D5",
73 | "L c #B7D0D8",
74 | "P c #BCD4DC",
75 | "I c #BED8DE",
76 | "U c #C1CFD4",
77 | "Y c #C3D2D6",
78 | "T c #C8D4D7",
79 | "R c #C4D3D8",
80 | "E c #CBD6DA",
81 | "W c #C2D8DF",
82 | "Q c #CEDADD",
83 | "! c #D1DBDE",
84 | "~ c #C4DCE2",
85 | "^ c #CBDFE5",
86 | "/ c #D5DFE2",
87 | "( c #CAE1E7",
88 | ") c #CDE3E9",
89 | "_ c #D6E2E4",
90 | "` c #DBE3E5",
91 | "' c #D1E5EB",
92 | "] c #DDE6E8",
93 | "[ c #D4E9EE",
94 | "{ c #DBEAEE",
95 | "} c #D7EBF1",
96 | "| c #DCEDF2",
97 | " . c #DEF1F6",
98 | ".. c #E4EBED",
99 | "X. c #E2EFF2",
100 | "o. c #E8EEF0",
101 | "O. c #E5F2F6",
102 | "+. c #ECF4F5",
103 | "@. c #E5F4F8",
104 | "#. c #E6F4F8",
105 | "$. c #E7F4F8",
106 | "%. c #E6F4F8",
107 | "&. c #E9F6F8",
108 | "*. c #EBF7F9",
109 | "=. c #ECF7F9",
110 | "-. c #EFF7F9",
111 | ";. c #EDF7FA",
112 | ":. c #EEF7FA",
113 | ">. c #E9F6F9",
114 | ",. c #E9F9FB",
115 | "<. c #EBF8FB",
116 | "1. c #EFF9FB",
117 | "2. c #EFFBFC",
118 | "3. c #EFFCFE",
119 | "4. c #EFF8F9",
120 | "5. c #F2F7F7",
121 | "6. c #F3F7F7",
122 | "7. c #F1F7F9",
123 | "8. c #F0F8FA",
124 | "9. c #F2F8FA",
125 | "0. c #F2F9FA",
126 | "q. c #F2F9FB",
127 | "w. c #F3FAFB",
128 | "e. c #F6F8F8",
129 | "r. c #F5FAFB",
130 | "t. c #F6FAFB",
131 | "y. c #F7FAFB",
132 | "u. c #F3FBFC",
133 | "i. c #F5F9FC",
134 | "p. c #F6FBFC",
135 | "a. c #F7FBFD",
136 | "s. c #F3FCFE",
137 | "d. c #F6FCFD",
138 | "f. c #F7FDFD",
139 | "g. c #F4FDFE",
140 | "h. c #F6FFFF",
141 | "j. c #F5FAFB",
142 | "k. c #F9FBFB",
143 | "l. c #F9FBFC",
144 | "z. c #F8FCFD",
145 | "x. c #F9FCFD",
146 | "c. c #FAFCFD",
147 | "v. c #FAFDFD",
148 | "b. c #FBFDFD",
149 | "n. c #F8FDFE",
150 | "m. c #F8FEFE",
151 | "M. c #F9FFFF",
152 | "N. c #FAFEFF",
153 | "B. c #FCFDFD",
154 | "V. c #FCFDFE",
155 | "C. c #FCFEFE",
156 | "Z. c #FDFEFE",
157 | "A. c #FCFFFF",
158 | "S. c #FEFEFE",
159 | "D. c #FEFEFF",
160 | "F. c #FEFFFF",
161 | "G. c white",
162 | "H. c #FBFDFD",
163 | /* pixels */
164 | " ",
165 | " ",
166 | " * G ",
167 | " % b ~ S ",
168 | " # g W { B ",
169 | " # 9 I .z.m ",
170 | " o 1 P | Z.X.G ",
171 | " o > L [ Z.0.| P s ",
172 | " # * G ' Z.r.O.O.) k ",
173 | " % C ) z.z.#.#.O.' C ",
174 | " # V ( g.z.#.#.#.O.| S ",
175 | " o m ^ 3.Z.#.#.#.#.O.X.~ d ",
176 | " X l ~ ,.Z.#.#.#.#.#.#.O.) l ",
177 | " @ g W @.Z.*.#.#.#.#.#.#.O.[ C ",
178 | " o u I .Z.:.#.#.#.#.#.#.#.O.| G ",
179 | " $ 8 P | Z.0.#.#.#.#.#.#.#.#.O.X.~ j ",
180 | " < P [ z.a.#.#.#.#.#.#.#.#.#.#.O.' y ",
181 | " - G ' z.a.#.#.#.#.#.#.#.#.#.#.#.O.} S ",
182 | " & G ) g.z.#.#.#.#.#.#.#.#.#.#.#.#.#.| J ",
183 | " & C ( u.z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.W l ",
184 | " # m ^ 1.Z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.) t ",
185 | " + l ~ *.Z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.| F ",
186 | " o s ~ #.Z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.| K 6 ",
187 | " o 9 I .Z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.( c ",
188 | " o 4 I .Z.:.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.' l ",
189 | " & < P | Z.0.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.{ V ",
190 | " > G [ z.a.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.O.O.O.0.r.c ",
191 | " * G ) g.z.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.O.O.O.:.r.Z.r.+.` Y ",
192 | " % F ( s.Z.#.#.#.#.#.#.#.#.#.#.#.#.#.O.O.O.&.0.z.l.5...! T Y H S ",
193 | " O C ^ 2.Z.#.#.#.#.#.#.#.#.#.#.#.#.#.X.&.k.Z.r.o.` E Y Y H N h f ",
194 | " & m ~ ,.Z.*.#.#.#.#.#.#.#.#.#.#.#.#.O.^ / ..! E Y H A n g e i f ",
195 | " O l ~ #.Z.:.#.#.#.#.O.O.O.O.:.#.#.#.#.| B v Y H N h i w q ",
196 | " @ u I O.Z.:.#.#.#.O.O.=.r.g.z.#.#.#.#.O.' 6 h f w w r ",
197 | " $ 8 I | Z.1.O.O.+.=.z.z.r.o.Z.0.#.#.#.#.O.G , w ",
198 | " < P } Z.=.+.r.Z.z.=.] ! _ 7.Z.*.#.#.#.O.{ y ",
199 | " = J [ Z.z.z.5.../ E Y H E { z.r.#.#.#.#.O.W 3 ",
200 | " & G ' k.+.] ! Y Y H A c D / O.Z.*.#.#.#.O.| c ",
201 | " % C ^ / E Y U S m h e 7 Z Y ] k.g.#.O.O.O.7.=.x ",
202 | " + m R Y H C n f w w < 2 z D Q o.Z.+.&.7.z.k.=.] ",
203 | " o n G m g e w q - 5 M U _ 7.z.Z.r..._ E Y Y ",
204 | " . p f w w : a A E o.+.] ! T Y K A n ",
205 | " # w w ; 3 v H ! E Y Y H N h e w ",
206 | " ; 0 Z Y Y A h f w w f ",
207 | " : 2 c m h e w w ",
208 | " - e e w i ",
209 | " e ",
210 | " ",
211 | " "
212 | };
213 |
--------------------------------------------------------------------------------
/icon_mac.icns:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isaacrobinson2000/CursorCreate/248a0863a4ef69cf32d608a661f1d97cd59afe32/icon_mac.icns
--------------------------------------------------------------------------------
/icon_windows.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isaacrobinson2000/CursorCreate/248a0863a4ef69cf32d608a661f1d97cd59afe32/icon_windows.ico
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = [
3 | "setuptools>=42",
4 | "wheel"
5 | ]
6 | build-backend = "setuptools.build_meta"
7 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | black
2 | click
3 | numpy
4 | Pillow
5 | PySide6
6 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 | from setuptools import setup
3 |
4 | readme_file = Path(__file__).parent / "README.md"
5 | with readme_file.open("r") as f:
6 | text = f.read()
7 |
8 | setup(
9 | name="CursorCreate",
10 | version="1.4.0",
11 | packages=["CursorCreate", "CursorCreate.gui", "CursorCreate.lib"],
12 | url="https://github.com/isaacrobinson2000/CursorCreate",
13 | license="GPLv3",
14 | author="Isaac Robinson",
15 | download_url="https://github.com/isaacrobinson2000/CursorCreate/archive/v1.3.1.tar.gz",
16 | author_email="awesomeisaac2000@gmail.com",
17 | description="A Multi-platform Cursor Theme Building Program",
18 | long_description=text,
19 | long_description_content_type="text/markdown",
20 | entry_points={
21 | "console_scripts": [
22 | "CursorCreate = CursorCreate.cursorcreate:main"
23 | ],
24 | },
25 | install_requires=[
26 | "PySide6",
27 | "Pillow",
28 | "numpy"
29 | ]
30 | )
31 |
--------------------------------------------------------------------------------