Debian Codegraph @

DisplayCAL/wx_version.py

raw
1 # ----------------------------------------------------------------------
2 # Name: wx_version
3 # Purpose: Allows a wxPython program to search for alternate
4 # installations of the wxPython packages and modify sys.path
5 # so they will be found when "import wx" is done.
6 #
7 # Author: Robin Dunn
8 #
9 # Created: 24-Sept-2004
10 # RCS-ID: $Id$
11 # Copyright: (c) 2004 by Total Control Software
12 # Licence: wxWindows license
13 #
14 # 2019-05 Updated to find Phoenix versions and never override first
15 # entry in sys.path (usually current dir) - fhoech
16 # ----------------------------------------------------------------------
17
18 """Utility module for wxPython to allow multiple versions to be installed.
19
20 If you have more than one version of wxPython installed this module
21 allows your application to choose which version of wxPython will be
22 imported when it does 'import wx'. The main function of this module
23 is `select` and you use it like this::
24
25 import wx_version
26 wx_version.select('2.4')
27 import wx
28
29 Or additional build options can also be selected, although they will
30 not be required if they are not installed, like this::
31
32 import wx_version
33 wx_version.select('2.5.3-unicode')
34 import wx
35
36 Or you can require an exact match on the build options like this::
37
38 import wx_version
39 wx_version.select('2.5.3-unicode', options_required=True)
40 import wx
41
42 Finally you can also specify a collection of versions that are allowed
43 by your application, like this::
44
45 import wx_version
46 wx_version.select(['2.5.4', '2.5.5', '2.6'])
47 import wx
48
49
50 Of course the default wxPython version can also be controlled by
51 setting PYTHONPATH or by editing the wx.pth path configuration file,
52 but using wx_version will allow an application to manage the version
53 selection itself rather than depend on the user to setup the
54 environment correctly.
55
56 It works by searching the sys.path for directories matching wx-* and
57 then comparing them to what was passed to the select function. If a
58 match is found then that path is inserted into sys.path.
59
60 NOTE: If you are making a 'bundle' of your application with a tool
61 like py2exe then you should *not* use the wx_version module since it
62 looks at the filesystem for the directories on sys.path, it will fail
63 in a bundled environment. Instead you should simply ensure that the
64 version of wxPython that you want is found by default on the sys.path
65 when making the bundled version by setting PYTHONPATH. Then that
66 version will be included in your bundle and your app will work as
67 expected. Py2exe and the others usually have a way to tell at runtime
68 if they are running from a bundle or running raw, so you can check
69 that and only use wx_version if needed. For example, for py2exe::
70
71 if not hasattr(sys, 'frozen'):
72 import wx_version
73 wx_version.select('2.5')
74 import wx
75
76 More documentation on wx_version and multi-version installs can be
77 found at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls
78
79 """
80
81 from __future__ import annotations
82
83 import fnmatch
84 import glob
85 import os
86 import re
87 import sys
88
89 _SELECTED = None
90 _EM_DEBUG = 0
91 UPDATE_URL = "https://wxPython.org/"
92 _WX_VERSION_PATTERN = "wx-[0-9].*"
93 _WX_VERSION_PATTERN_PHOENIX = "wxPython-[0-9].*.egg"
94
95
96 class VersionError(Exception):
97 """Exception raised when a requested wxPython version is not found."""
98
99
100 class AlreadyImportedError(VersionError):
101 """Exception raised when wxPython has already been imported."""
102
103
104 def select(versions: str | list[str], options_required: bool = False) -> None:
105 """Search for a wxPython installation that matches version.
106
107 If one is found then sys.path is modified so that version will be imported
108 with a 'import wx', otherwise a VersionError exception is raised. This
109 function should only be called once at the beginning of the application
110 before wxPython is imported.
111
112 Args:
113 versions (Union[str, list[str]]): Specifies the version to look for,
114 it can either be a string or a list of strings. Each string is
115 compared to the installed wxPythons and the best match is inserted
116 into the sys.path, allowing an 'import wx' to find that version.
117
118 The version string is composed of the dotted version number (at
119 least 2 of the 4 components) optionally followed by hyphen ('-')
120 separated options (wx port, unicode/ansi, flavour, etc.) A match is
121 determined by how much of the installed version matches what is
122 given in the version parameter. If the version number components
123 don't match then the score is zero, otherwise the score is
124 increased for every specified optional component that is specified
125 and that matches.
126
127 Please note, however, that it is possible for a match to be
128 selected that doesn't exactly match the versions requested. The
129 only component that is required to be matched is the version
130 number. If you need to require a match on the other components as
131 well, then please use the optional ``options_required`` parameter
132 described next.
133
134 options_required: Allows you to specify that the other components of
135 the version string (such as the port name or character type) are
136 also required to be present for an installed version to be
137 considered a match. Using this parameter allows you to change the
138 selection from a soft, as close as possible match to a hard, exact
139 match.
140 """
141 if isinstance(versions, str):
142 versions = [versions]
143
144 global _SELECTED
145 if _SELECTED is not None:
146 # A version was previously selected, ensure that it matches
147 # this new request
148 for ver in versions:
149 if _SELECTED.score(WxPackageInfo(ver), options_required) > 0:
150 return
151 # otherwise, raise an exception
152 raise VersionError(
153 "A previously selected wx version does not match the new request."
154 )
155
156 # If we get here then this is the first time wx_version is used,
157 # ensure that wxPython hasn't been imported yet.
158 check_already_imported()
159
160 # Look for a matching version and manipulate the sys.path as
161 # needed to allow it to be imported.
162 installed = _find_installed(True)
163 best_match = _get_best_match(installed, versions, options_required)
164
165 if best_match is None:
166 raise VersionError("Requested version of wxPython not found")
167
168 if best_match.pathname not in sys.path:
169 sys.path.insert(1, best_match.pathname)
170 # q.v. Bug #1409256
171 path64 = re.sub("/lib/", "/lib64/", best_match.pathname)
172 if path64 != best_match.pathname and os.path.isdir(path64):
173 sys.path.insert(1, path64)
174 _SELECTED = best_match
175
176
177 def ensure_minimal(min_version: str, options_required: bool = False) -> None:
178 """Ensure the default wxPython version is >= `minVersion`.
179
180 If not, attempt to find an installed version >= `minVersion`. If none are
181 found, prompt the user to download a compatible version and exit the
182 application.
183
184 Args:
185 min_version (str): The minimum required version of wxPython.
186 options_required (bool): If True, require exact match on options.
187
188 Raises:
189 AlreadyImportedError: If wxPython has already been imported.
190 VersionError: If no matching version is found and the user declines to
191 download.
192 """
193 if not isinstance(min_version, str):
194 raise TypeError("min_version must be a string")
195
196 # ensure that wxPython hasn't been imported yet.
197 check_already_imported()
198
199 best_match = None
200 minv = WxPackageInfo(min_version)
201
202 # check the default version first
203 default_path = _find_default()
204 if default_path:
205 defv = WxPackageInfo(default_path, True)
206 if defv >= minv and minv.check_options(defv, options_required):
207 best_match = defv
208
209 # if still no match then check look at all installed versions
210 if best_match is None:
211 installed = _find_installed()
212 # The list is in reverse sorted order, so find the first
213 # one that is big enough and optionally matches the
214 # options
215 for inst in installed:
216 if inst >= minv and minv.check_options(inst, options_required):
217 best_match = inst
218 break
219
220 # if still no match then prompt the user
221 if best_match is None:
222 if _EM_DEBUG: # We'll do it this way just for the test code below
223 raise VersionError("Requested version of wxPython not found")
224
225 import webbrowser
226
227 import wx
228
229 versions = "\n".join([" " + ver for ver in get_installed()])
230 app = wx.App()
231 result = wx.MessageBox(
232 "This application requires a version of wxPython "
233 f"greater than or equal to {min_version}, but a matching version "
234 "was not found.\n\n"
235 f"You currently have these version(s) installed:\n{versions}\n\n"
236 "Would you like to download a new version of wxPython?\n",
237 "wxPython Upgrade Needed",
238 style=wx.YES_NO,
239 )
240 if result == wx.YES:
241 webbrowser.open(UPDATE_URL)
242 app.MainLoop()
243 sys.exit()
244
245 if best_match.pathname not in sys.path:
246 sys.path.insert(1, best_match.pathname)
247 # q.v. Bug #1409256
248 path64 = re.sub("/lib/", "/lib64/", best_match.pathname)
249 if path64 != best_match.pathname and os.path.isdir(path64):
250 sys.path.insert(1, path64)
251 global _SELECTED
252 _SELECTED = best_match
253
254
255 def check_already_imported() -> None:
256 """Check if wxPython has already been imported.
257
258 Raises:
259 AlreadyImportedError: If wxPython has already been imported.
260 """
261 # ensure that wxPython hasn't been imported yet.
262 if "wx" in sys.modules or "wxPython" in sys.modules:
263 raise AlreadyImportedError(
264 "wx_version.ensureMinimal() must be called before wxPython is imported"
265 )
266
267
268 def check_installed(versions: list[str], options_required: bool = False) -> bool:
269 """Check if a version of wxPython installed that matches one of the versions given.
270
271 This can be used to determine if calling `select` will succeed or not.
272
273 Args:
274 versions (list[str]): Same as in `select`, either a string or a list
275 of strings specifying the version(s) to check for.
276 options_required (bool): Same as in `select`.
277
278 Returns:
279 bool: True if a matching version is found, False otherwise.
280 """
281 if isinstance(versions, str):
282 versions = [versions]
283 installed = _find_installed()
284 best_match = _get_best_match(installed, versions, options_required)
285 return best_match is not None
286
287
288 def get_installed() -> list[str]:
289 """Return a list of installed wxPython versions as strings.
290
291 Returns:
292 list[str]: A list of installed wxPython versions in the format
293 "wx-<version>".
294 """
295 installed = _find_installed()
296 return [p.base.split("-", 1).pop() for p in installed]
297
298
299 def _get_best_match(
300 installed: list[WxPackageInfo], versions: list[str], options_required: bool
301 ) -> None | WxPackageInfo:
302 """Find the best match for the given versions in the installed wxPython packages.
303
304 Args:
305 installed (list[WxPackageInfo]): List of installed wxPython packages.
306 versions (list[str]): List of version strings to match against.
307 options_required (bool): Whether options are required for a match.
308
309 Returns:
310 WxPackageInfo: The best matching wxPython package, or None if no match
311 is found.
312 """
313 best_match = None
314 best_score = 0
315 for pkg in installed:
316 for ver in versions:
317 score = pkg.score(WxPackageInfo(ver), options_required)
318 if score > best_score:
319 best_match = pkg
320 best_score = score
321 return best_match
322
323
324 def _find_installed(remove_existing: bool = False) -> list[WxPackageInfo]:
325 """Scan sys.path for wxPython packages and return a list of them.
326
327 Args:
328 remove_existing (bool): If True, remove existing wxPython paths from
329 sys.path.
330
331 Returns:
332 list[WxPackageInfo]: A list of installed wxPython packages.
333 """
334 installed = []
335 to_remove = []
336 for pth in sys.path:
337 # empty means to look in the current dir
338 if not pth:
339 pth = "."
340
341 # skip it if it's not a package dir
342 if not os.path.isdir(pth):
343 continue
344
345 base = os.path.basename(pth)
346
347 # if it's a wx path that's already in the sys.path then mark
348 # it for removal and then skip it
349 if fnmatch.fnmatchcase(base, _WX_VERSION_PATTERN) or fnmatch.fnmatchcase(
350 base, _WX_VERSION_PATTERN_PHOENIX
351 ):
352 to_remove.append(pth)
353 continue
354
355 # now look in the dir for matching subdirs
356 for name in glob.glob(os.path.join(pth, _WX_VERSION_PATTERN)) + glob.glob(
357 os.path.join(pth, _WX_VERSION_PATTERN_PHOENIX)
358 ):
359 # make sure it's a directory
360 if not os.path.isdir(name):
361 continue
362 # and has a wx subdir
363 if not os.path.exists(os.path.join(name, "wx")):
364 continue
365 installed.append(WxPackageInfo(name, True))
366
367 # Phoenix
368 name = os.path.join(pth, "wx")
369 phoenix_version_py = os.path.join(name, "__version__.py")
370 if os.path.isfile(phoenix_version_py):
371 version_info = {}
372 with open(phoenix_version_py, "rb") as f:
373 phoenix_version = f.read()
374 exec( # noqa: S102
375 compile(phoenix_version, phoenix_version_py, "exec"),
376 {},
377 version_info,
378 )
379 if version_info["VERSION"] >= (4,):
380 pinfo = WxPackageInfo(
381 "{}-{}".format(name, version_info["VERSION_STRING"]), True
382 )
383 pinfo.pathname = pth
384 installed.append(pinfo)
385
386 if remove_existing:
387 for rem in to_remove:
388 del sys.path[sys.path.index(rem)]
389
390 installed.sort()
391 installed.reverse()
392 return installed
393
394
395 def _find_default() -> None | str:
396 """Scan sys.path for a directory matching _pattern or a wx.pth file.
397
398 Returns:
399 None | str: The path to the wxPython installation if found,
400 otherwise None.
401 """
402 for pth in sys.path:
403 # empty means to look in the current dir
404 if not pth:
405 pth = "."
406
407 # skip it if it's not a package dir
408 if not os.path.isdir(pth):
409 continue
410
411 # does it match the pattern?
412 base = os.path.basename(pth)
413 if fnmatch.fnmatchcase(base, _WX_VERSION_PATTERN) or fnmatch.fnmatchcase(
414 base, _WX_VERSION_PATTERN_PHOENIX
415 ):
416 return pth
417
418 for pth in sys.path:
419 if not pth:
420 pth = "."
421 if not os.path.isdir(pth):
422 continue
423 if os.path.exists(os.path.join(pth, "wx.pth")):
424 with open(os.path.join(pth, "wx.pth")) as f:
425 base = f.read()
426 return os.path.join(pth, base)
427
428 return None
429
430
431 class WxPackageInfo:
432 """A class to hold information about a wxPython package.
433
434 Args:
435 pathname (str): The path to the wxPython package.
436 strip_first (bool): If True, strip the first component of the
437 version string.
438 """
439
440 def __init__(self, pathname: str, strip_first: bool = False) -> None:
441 self.pathname = pathname
442 self.base = os.path.basename(pathname)
443 segments = self.base.split("-")
444 if strip_first:
445 segments = segments[1:]
446 self.version = tuple(segments[0].split("."))
447 self.options = segments[1:]
448
449 def score(self, other: WxPackageInfo, options_required: bool) -> int:
450 """Calculate a score for this package against another.
451
452 The score is based on how many components of the version and
453 options match. The more components that match, the higher the
454 score.
455
456 Args:
457 other (WxPackageInfo): The other package to compare against.
458 options_required (bool): If True, require exact match on options.
459
460 Returns:
461 int: The score for this package against the other.
462 """
463 score = 0
464
465 # whatever number of version components given in other must
466 # match exactly
467 minlen = min(len(self.version), len(other.version))
468 if self.version[:minlen] != other.version[:minlen]:
469 return 0
470 score += 1
471
472 # check for matching options, if options_required then the
473 # options are not optional ;-)
474 for opt in other.options:
475 if opt in self.options:
476 score += 1
477 elif options_required:
478 return 0
479
480 return score
481
482 def check_options(self, other: WxPackageInfo, options_required: bool) -> bool:
483 """Check if the options of this package match those of another.
484
485 Args:
486 other (WxPackageInfo): The other package to compare against.
487 options_required (bool): If True, require exact match on options.
488
489 Returns:
490 bool: True if the options match, False otherwise.
491 """
492 # if options are not required then this always succeeds
493 if not options_required:
494 return True
495 # otherwise, if we have any option not present in other, then
496 # the match fails.
497 return all(opt in other.options for opt in self.options)
498
499 def __lt__(self, other: WxPackageInfo) -> bool:
500 """Check if this package is less than another.
501
502 Args:
503 other (WxPackageInfo): The other package to compare against.
504
505 Returns:
506 bool: True if this package is less than the other,
507 False otherwise.
508 """
509 return self.version < other.version or (
510 self.version == other.version and self.options < other.options
511 )
512
513 def __le__(self, other: WxPackageInfo) -> bool:
514 """Check if this package is less than or equal to another.
515
516 Args:
517 other (WxPackageInfo): The other package to compare against.
518
519 Returns:
520 bool: True if this package is less than or equal to the other,
521 False otherwise.
522 """
523 return self.version <= other.version or (
524 self.version == other.version and self.options <= other.options
525 )
526
527 def __gt__(self, other: WxPackageInfo) -> bool:
528 """Check if this package is greater than another.
529
530 Args:
531 other (WxPackageInfo): The other package to compare against.
532
533 Returns:
534 bool: True if this package is greater than the other,
535 False otherwise.
536 """
537 return self.version > other.version or (
538 self.version == other.version and self.options > other.options
539 )
540
541 def __ge__(self, other: WxPackageInfo) -> bool:
542 """Check if this package is greater than or equal to another.
543
544 Args:
545 other (WxPackageInfo): The other package to compare against.
546
547 Returns:
548 bool: True if this package is greater than or equal to the other,
549 False otherwise.
550 """
551 return self.version >= other.version or (
552 self.version == other.version and self.options >= other.options
553 )
554
555 def __eq__(self, other: WxPackageInfo) -> bool:
556 """Check if this package is equal to another.
557
558 Args:
559 other (WxPackageInfo): The other package to compare against.
560
561 Returns:
562 bool: True if the packages are equal, False otherwise.
563 """
564 return (
565 isinstance(other, WxPackageInfo)
566 and self.version == other.version
567 and self.options == other.options
568 )