id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,500 | unpair.py | pwr-Solaar_Solaar/lib/solaar/cli/unpair.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
def run(receivers, args, find_receiver, find_device):
assert receivers
assert args.device
device_name = args.device.lower()
dev = next(find_device(receivers, device_name), None)
if not dev:
raise Exception(f"no device found matching '{device_name}'")
if not dev.receiver.may_unpair:
print(
"Receiver with USB id %s for %s [%s:%s] does not unpair, but attempting anyway."
% (dev.receiver.product_id, dev.name, dev.wpid, dev.serial)
)
try:
# query these now, it's last chance to get them
number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial
dev.receiver._unpair_device(number, True) # force an unpair
print(f"Unpaired {int(number)}: {dev.name} ({codename}) [{wpid}:{serial}]")
except Exception as e:
raise e
| 1,619 | Python | .py | 34 | 42.970588 | 92 | 0.700822 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,501 | probe.py | pwr-Solaar_Solaar/lib/solaar/cli/probe.py | ## Copyright (C) 2020
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from logitech_receiver import base
from logitech_receiver import hidpp10_constants
from logitech_receiver.common import strhex
from logitech_receiver.hidpp10_constants import Registers
from solaar.cli.show import _print_device
from solaar.cli.show import _print_receiver
def run(receivers, args, find_receiver, _ignore):
assert receivers
if args.receiver:
receiver_name = args.receiver.lower()
receiver = find_receiver(receivers, receiver_name)
if not receiver:
raise Exception(f"no receiver found matching '{receiver_name}'")
else:
receiver = receivers[0]
assert receiver is not None
if receiver.isDevice:
_print_device(receiver, 1)
return
_print_receiver(receiver)
print("")
print(" Register Dump")
rgst = receiver.read_register(Registers.NOTIFICATIONS)
print(" Notifications %#04x: %s" % (Registers.NOTIFICATIONS % 0x100, "0x" + strhex(rgst) if rgst else "None"))
rgst = receiver.read_register(Registers.RECEIVER_CONNECTION)
print(
" Connection State %#04x: %s"
% (Registers.RECEIVER_CONNECTION % 0x100, "0x" + strhex(rgst) if rgst else "None")
)
rgst = receiver.read_register(Registers.DEVICES_ACTIVITY)
print(
" Device Activity %#04x: %s" % (Registers.DEVICES_ACTIVITY % 0x100, "0x" + strhex(rgst) if rgst else "None")
)
for sub_reg in range(0, 16):
rgst = receiver.read_register(Registers.RECEIVER_INFO, sub_reg)
print(
" Pairing Register %#04x %#04x: %s"
% (Registers.RECEIVER_INFO % 0x100, sub_reg, "0x" + strhex(rgst) if rgst else "None")
)
for device in range(0, 7):
for sub_reg in [0x10, 0x20, 0x30, 0x50]:
rgst = receiver.read_register(Registers.RECEIVER_INFO, sub_reg + device)
print(
" Pairing Register %#04x %#04x: %s"
% (Registers.RECEIVER_INFO % 0x100, sub_reg + device, "0x" + strhex(rgst) if rgst else "None")
)
rgst = receiver.read_register(Registers.RECEIVER_INFO, 0x40 + device)
print(
" Pairing Name %#04x %#02x: %s"
% (Registers.RECEIVER_INFO % 0x100, 0x40 + device, rgst[2 : 2 + ord(rgst[1:2])] if rgst else "None")
)
for part in range(1, 4):
rgst = receiver.read_register(Registers.RECEIVER_INFO, 0x60 + device, part)
print(
" Pairing Name %#04x %#02x %#02x: %2d %s"
% (
Registers.RECEIVER_INFO % 0x100,
0x60 + device,
part,
ord(rgst[2:3]) if rgst else 0,
rgst[3 : 3 + ord(rgst[2:3])] if rgst else "None",
)
)
for sub_reg in range(0, 5):
rgst = receiver.read_register(Registers.FIRMWARE, sub_reg)
print(
" Firmware %#04x %#04x: %s"
% (Registers.FIRMWARE % 0x100, sub_reg, "0x" + strhex(rgst) if rgst is not None else "None")
)
print("")
for reg in range(0, 0xFF):
last = None
for sub in range(0, 0xFF):
rgst = base.request(receiver.handle, 0xFF, 0x8100 | reg, sub, return_error=True)
if isinstance(rgst, int) and rgst == hidpp10_constants.ERROR.invalid_address:
break
elif isinstance(rgst, int) and rgst == hidpp10_constants.ERROR.invalid_value:
continue
else:
if not isinstance(last, bytes) or not isinstance(rgst, bytes) or last != rgst:
print(
" Register Short %#04x %#04x: %s"
% (reg, sub, "0x" + strhex(rgst) if isinstance(rgst, bytes) else str(rgst))
)
last = rgst
last = None
for sub in range(0, 0xFF):
rgst = base.request(receiver.handle, 0xFF, 0x8100 | (0x200 + reg), sub, return_error=True)
if isinstance(rgst, int) and rgst == hidpp10_constants.ERROR.invalid_address:
break
elif isinstance(rgst, int) and rgst == hidpp10_constants.ERROR.invalid_value:
continue
else:
if not isinstance(last, bytes) or not isinstance(rgst, bytes) or last != rgst:
print(
" Register Long %#04x %#04x: %s"
% (reg, sub, "0x" + strhex(rgst) if isinstance(rgst, bytes) else str(rgst))
)
last = rgst
| 5,341 | Python | .py | 114 | 36.947368 | 125 | 0.592216 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,502 | __init__.py | pwr-Solaar_Solaar/lib/solaar/cli/__init__.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse
import logging
import sys
from importlib import import_module
from traceback import extract_tb
from traceback import format_exc
from logitech_receiver import base
from logitech_receiver import device
from logitech_receiver import receiver
from solaar import NAME
logger = logging.getLogger(__name__)
def _create_parser():
parser = argparse.ArgumentParser(
prog=NAME.lower(),
add_help=False,
epilog=f"For details on individual actions, run `{NAME.lower()} <action> --help`.",
)
subparsers = parser.add_subparsers(title="actions", help="command-line action to perform")
sp = subparsers.add_parser("show", help="show information about devices")
sp.add_argument(
"device",
nargs="?",
default="all",
help="device to show information about; may be a device number (1..6), a serial number, "
'a substring of a device\'s name, or "all" (the default)',
)
sp.set_defaults(action="show")
sp = subparsers.add_parser("probe", help="probe a receiver (debugging use only)")
sp.add_argument(
"receiver", nargs="?", help="select receiver by name substring or serial number when more than one is present"
)
sp.set_defaults(action="probe")
sp = subparsers.add_parser(
"profiles",
help="read or write onboard profiles",
epilog="Only works on active devices.",
)
sp.add_argument(
"device",
help="device to read or write profiles of; may be a device number (1..6), a serial number, "
"a substring of a device's name",
)
sp.add_argument("profiles", nargs="?", help="file containing YAML dump of profiles")
sp.set_defaults(action="profiles")
sp = subparsers.add_parser(
"config",
help="read/write device-specific settings",
epilog="Please note that configuration only works on active devices.",
)
sp.add_argument(
"device",
help=(
"device to configure; may be a device number (1..6), a serial number, ",
"or a substring of a device's name",
),
)
sp.add_argument("setting", nargs="?", help="device-specific setting; leave empty to list available settings")
sp.add_argument("value_key", nargs="?", help="new value for the setting or key for keyed settings")
sp.add_argument("extra_subkey", nargs="?", help="value for keyed or subkey for subkeyed settings")
sp.add_argument("extra2", nargs="?", help="value for subkeyed settings")
sp.set_defaults(action="config")
sp = subparsers.add_parser(
"pair",
help="pair a new device",
epilog="The Logitech Unifying Receiver supports up to 6 paired devices at the same time.",
)
sp.add_argument(
"receiver", nargs="?", help="select receiver by name substring or serial number when more than one is present"
)
sp.set_defaults(action="pair")
sp = subparsers.add_parser("unpair", help="unpair a device")
sp.add_argument(
"device",
help="device to unpair; may be a device number (1..6), a serial number, " "or a substring of a device's name.",
)
sp.set_defaults(action="unpair")
return parser, subparsers.choices
_cli_parser, actions = _create_parser()
print_help = _cli_parser.print_help
def _receivers(dev_path=None):
for dev_info in base.receivers():
if dev_path is not None and dev_path != dev_info.path:
continue
try:
r = receiver.create_receiver(base, dev_info)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("[%s] => %s", dev_info.path, r)
if r:
yield r
except Exception as e:
logger.exception("opening " + str(dev_info))
sys.exit(f"{NAME.lower()}: error: {str(e)}")
def _receivers_and_devices(dev_path=None):
for dev_info in base.receivers_and_devices():
if dev_path is not None and dev_path != dev_info.path:
continue
try:
if dev_info.isDevice:
d = device.create_device(base, dev_info)
else:
d = receiver.create_receiver(base, dev_info)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("[%s] => %s", dev_info.path, d)
if d is not None:
yield d
except Exception as e:
logger.exception("opening " + str(dev_info))
sys.exit(f"{NAME.lower()}: error: {str(e)}")
def _find_receiver(receivers, name):
assert receivers
assert name
for r in receivers:
if name in r.name.lower() or (r.serial is not None and name == r.serial.lower()):
return r
def _find_device(receivers, name):
assert receivers
assert name
number = None
if len(name) == 1:
try:
number = int(name)
except Exception:
pass
else:
assert not (number < 0)
if number > 6:
number = None
for r in receivers:
if not r.isDevice: # look for nth device of receiver
if number:
dev = r[number]
if dev:
yield dev
count = r.count()
else: # wired device, make a device list from it
r.ping()
r = [r]
count = 1
for dev in r:
if (
name == dev.serial.lower()
or name == dev.codename.lower()
or name == str(dev.kind).lower()
or name in dev.name.lower()
):
yield dev
count -= 1
if not count:
break
def run(cli_args=None, hidraw_path=None):
if cli_args:
action = cli_args[0]
args = _cli_parser.parse_args(cli_args)
else:
args = _cli_parser.parse_args()
# Python 3 has an undocumented 'feature' that breaks parsing empty args
# http://bugs.python.org/issue16308
if "cmd" not in args:
_cli_parser.print_usage(sys.stderr)
sys.stderr.write(f"{NAME.lower()}: error: too few arguments\n")
sys.exit(2)
action = args.action
assert action in actions
try:
if action == "show" or action == "probe" or action == "config" or action == "profiles":
c = list(_receivers_and_devices(hidraw_path))
else:
c = list(_receivers(hidraw_path))
if not c:
raise Exception(
'No supported device found. Use "lsusb" and "bluetoothctl devices Connected" to list connected devices.'
)
m = import_module("." + action, package=__name__)
m.run(c, args, _find_receiver, _find_device)
except AssertionError:
tb_last = extract_tb(sys.exc_info()[2])[-1]
sys.exit(f"{NAME.lower()}: assertion failed: {tb_last[0]} line {int(tb_last[1])}")
except Exception:
sys.exit(f"{NAME.lower()}: error: {format_exc()}")
| 7,794 | Python | .py | 194 | 32.020619 | 120 | 0.614561 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,503 | profiles.py | pwr-Solaar_Solaar/lib/solaar/cli/profiles.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import traceback
import yaml
from logitech_receiver.hidpp20 import OnboardProfiles
from logitech_receiver.hidpp20 import OnboardProfilesVersion
def run(receivers, args, find_receiver, find_device):
assert receivers
assert args.device
device_name = args.device.lower()
profiles_file = args.profiles
dev = None
for dev in find_device(receivers, device_name):
if dev.ping():
break
dev = None
if not dev:
raise Exception(f"no online device found matching '{device_name}'")
if not (dev.online and dev.profiles):
print(f"Device {dev.name} is either offline or has no onboard profiles")
elif not profiles_file:
print(f"#Dumping profiles from {dev.name}")
print(yaml.dump(dev.profiles))
else:
try:
with open(profiles_file, "r") as f:
print(f"Reading profiles from {profiles_file}")
profiles = yaml.safe_load(f)
if not isinstance(profiles, OnboardProfiles):
print("Profiles file does not contain current onboard profiles")
elif getattr(profiles, "version", None) != OnboardProfilesVersion:
version = getattr(profiles, "version", None)
print(f"Missing or incorrect profile version {version} in loaded profile")
elif getattr(profiles, "name", None) != dev.name:
name = getattr(profiles, "name", None)
print(f"Different device name {name} in loaded profile")
else:
print(f"Loading profiles into {dev.name}")
written = profiles.write(dev)
print(f"Wrote {written} sectors to {dev.name}")
except Exception as exc:
print("Profiles not written:", exc)
print(traceback.format_exc())
| 2,643 | Python | .py | 56 | 38.75 | 94 | 0.658262 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,504 | hidconsole.py | pwr-Solaar_Solaar/lib/hidapi/hidconsole.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse
import os
import os.path
import platform
import readline
import sys
import time
from binascii import hexlify
from binascii import unhexlify
from select import select
from threading import Lock
from threading import Thread
if platform.system() == "Linux":
import hidapi.udev_impl as hidapi
else:
import hidapi.hidapi_impl as hidapi
LOGITECH_VENDOR_ID = 0x046D
interactive = os.isatty(0)
prompt = "?? Input: " if interactive else ""
start_time = time.time()
def strhex(d):
return hexlify(d).decode("ascii").upper()
print_lock = Lock()
def _print(marker, data, scroll=False):
t = time.time() - start_time
if isinstance(data, str):
s = marker + " " + data
else:
hexs = strhex(data)
s = "%s (% 8.3f) [%s %s %s %s] %s" % (marker, t, hexs[0:2], hexs[2:4], hexs[4:8], hexs[8:], repr(data))
with print_lock:
# allow only one thread at a time to write to the console, otherwise
# the output gets garbled, especially with ANSI codes.
if interactive and scroll:
# scroll the entire screen above the current line up by 1 line
sys.stdout.write(
"\033[s" # save cursor position
"\033[S" # scroll up
"\033[A" # cursor up
"\033[L" # insert 1 line
"\033[G"
) # move cursor to column 1
sys.stdout.write(s)
if interactive and scroll:
# restore cursor position
sys.stdout.write("\033[u")
else:
sys.stdout.write("\n")
# flush stdout manually...
# because trying to open stdin/out unbuffered programmatically
# works much too differently in Python 2/3
sys.stdout.flush()
def _error(text, scroll=False):
_print("!!", text, scroll)
def _continuous_read(handle, timeout=2000):
while True:
try:
reply = hidapi.read(handle, 128, timeout)
except OSError as e:
_error("Read failed, aborting: " + str(e), True)
break
assert reply is not None
if reply:
_print(">>", reply, True)
def _validate_input(line, hidpp=False):
try:
data = unhexlify(line.encode("ascii"))
except Exception as e:
_error("Invalid input: " + str(e))
return None
if hidpp:
if len(data) < 4:
_error("Invalid HID++ request: need at least 4 bytes")
return None
if data[:1] not in b"\x10\x11":
_error("Invalid HID++ request: first byte must be 0x10 or 0x11")
return None
if data[1:2] not in b"\xff\x00\x01\x02\x03\x04\x05\x06\x07":
_error("Invalid HID++ request: second byte must be 0xFF or one of 0x00..0x07")
return None
if data[:1] == b"\x10":
if len(data) > 7:
_error("Invalid HID++ request: maximum length of a 0x10 request is 7 bytes")
return None
while len(data) < 7:
data = (data + b"\x00" * 7)[:7]
elif data[:1] == b"\x11":
if len(data) > 20:
_error("Invalid HID++ request: maximum length of a 0x11 request is 20 bytes")
return None
while len(data) < 20:
data = (data + b"\x00" * 20)[:20]
return data
def _open(args):
def matchfn(bid, vid, pid, _a, _b):
if vid == LOGITECH_VENDOR_ID:
return {"vid": vid}
device = args.device
if args.hidpp and not device:
for d in hidapi.enumerate(matchfn):
if d.driver == "logitech-djreceiver":
device = d.path
break
if not device:
sys.exit("!! No HID++ receiver found.")
if not device:
sys.exit("!! Device path required.")
print(".. Opening device", device)
handle = hidapi.open_path(device)
if not handle:
sys.exit(f"!! Failed to open {device}, aborting.")
print(
".. Opened handle %r, vendor %r product %r serial %r."
% (handle, hidapi.get_manufacturer(handle), hidapi.get_product(handle), hidapi.get_serial(handle))
)
if args.hidpp:
if hidapi.get_manufacturer(handle) is not None and hidapi.get_manufacturer(handle) != b"Logitech":
sys.exit("!! Only Logitech devices support the HID++ protocol.")
print(".. HID++ validation enabled.")
else:
if hidapi.get_manufacturer(handle) == b"Logitech" and b"Receiver" in hidapi.get_product(handle):
args.hidpp = True
print(".. Logitech receiver detected, HID++ validation enabled.")
return handle
def _parse_arguments():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--history", help="history file (default ~/.hidconsole-history)")
arg_parser.add_argument("--hidpp", action="store_true", help="ensure input data is a valid HID++ request")
arg_parser.add_argument(
"device",
nargs="?",
help="linux device to connect to (/dev/hidrawX); "
"may be omitted if --hidpp is given, in which case it looks for the first Logitech receiver",
)
return arg_parser.parse_args()
def main():
args = _parse_arguments()
handle = _open(args)
if interactive:
print(".. Press ^C/^D to exit, or type hex bytes to write to the device.")
if args.history is None:
args.history = os.path.join(os.path.expanduser("~"), ".hidconsole-history")
try:
readline.read_history_file(args.history)
except Exception:
# file may not exist yet
pass
try:
t = Thread(target=_continuous_read, args=(handle,))
t.daemon = True
t.start()
if interactive:
# move the cursor at the bottom of the screen
sys.stdout.write("\033[300B") # move cusor at most 300 lines down, don't scroll
while t.is_alive():
line = input(prompt)
line = line.strip().replace(" ", "")
# print ("line", line)
if not line:
continue
data = _validate_input(line, args.hidpp)
if data is None:
continue
_print("<<", data)
hidapi.write(handle, data)
# wait for some kind of reply
if args.hidpp and not interactive:
rlist, wlist, xlist = select([handle], [], [], 1)
if data[1:2] == b"\xff":
# the receiver will reply very fast, in a few milliseconds
time.sleep(0.010)
else:
# the devices might reply quite slow
time.sleep(0.700)
except EOFError:
if interactive:
print("")
else:
time.sleep(1)
finally:
print(f".. Closing handle {handle!r}")
hidapi.close(handle)
if interactive:
readline.write_history_file(args.history)
if __name__ == "__main__":
main()
| 7,817 | Python | .py | 201 | 30.303483 | 111 | 0.593267 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,505 | hidapi_impl.py | pwr-Solaar_Solaar/lib/hidapi/hidapi_impl.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Generic Human Interface Device API.
This provides a python interface to libusb's hidapi library which,
unlike udev, is available for non-linux platforms.
See https://github.com/libusb/hidapi for how to obtain binaries.
Parts of this code are adapted from https://github.com/apmorton/pyhidapi
which is MIT licensed.
"""
from __future__ import annotations
import atexit
import ctypes
import logging
import platform
import typing
from threading import Thread
from time import sleep
from typing import Any
from typing import Callable
from hidapi.common import DeviceInfo
if typing.TYPE_CHECKING:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import GLib # NOQA: E402
logger = logging.getLogger(__name__)
ACTION_ADD = "add"
ACTION_REMOVE = "remove"
# Global handle to hidapi
_hidapi = None
# hidapi binary names for various platforms
_library_paths = (
"libhidapi-hidraw.so",
"libhidapi-hidraw.so.0",
"libhidapi-libusb.so",
"libhidapi-libusb.so.0",
"libhidapi-iohidmanager.so",
"libhidapi-iohidmanager.so.0",
"libhidapi.dylib",
"hidapi.dll",
"libhidapi-0.dll",
)
for lib in _library_paths:
try:
_hidapi = ctypes.cdll.LoadLibrary(lib)
break
except OSError:
pass
else:
raise ImportError(f"Unable to load hidapi library, tried: {' '.join(_library_paths)}")
# Retrieve version of hdiapi library
class _cHidApiVersion(ctypes.Structure):
_fields_ = [
("major", ctypes.c_int),
("minor", ctypes.c_int),
("patch", ctypes.c_int),
]
_hidapi.hid_version.argtypes = []
_hidapi.hid_version.restype = ctypes.POINTER(_cHidApiVersion)
_hid_version = _hidapi.hid_version()
# Construct device info struct based on API version
class _cDeviceInfo(ctypes.Structure):
def as_dict(self):
return {name: getattr(self, name) for name, _t in self._fields_ if name != "next"}
# Low level hdiapi device info struct
# See https://github.com/libusb/hidapi/blob/master/hidapi/hidapi.h#L143
_cDeviceInfo_fields = [
("path", ctypes.c_char_p),
("vendor_id", ctypes.c_ushort),
("product_id", ctypes.c_ushort),
("serial_number", ctypes.c_wchar_p),
("release_number", ctypes.c_ushort),
("manufacturer_string", ctypes.c_wchar_p),
("product_string", ctypes.c_wchar_p),
("usage_page", ctypes.c_ushort),
("usage", ctypes.c_ushort),
("interface_number", ctypes.c_int),
("next", ctypes.POINTER(_cDeviceInfo)),
]
if _hid_version.contents.major >= 0 and _hid_version.contents.minor >= 13:
_cDeviceInfo_fields.append(("bus_type", ctypes.c_int))
_cDeviceInfo._fields_ = _cDeviceInfo_fields
# Set up hidapi functions
_hidapi.hid_init.argtypes = []
_hidapi.hid_init.restype = ctypes.c_int
_hidapi.hid_exit.argtypes = []
_hidapi.hid_exit.restype = ctypes.c_int
_hidapi.hid_enumerate.argtypes = [ctypes.c_ushort, ctypes.c_ushort]
_hidapi.hid_enumerate.restype = ctypes.POINTER(_cDeviceInfo)
_hidapi.hid_free_enumeration.argtypes = [ctypes.POINTER(_cDeviceInfo)]
_hidapi.hid_free_enumeration.restype = None
_hidapi.hid_open.argtypes = [ctypes.c_ushort, ctypes.c_ushort, ctypes.c_wchar_p]
_hidapi.hid_open.restype = ctypes.c_void_p
_hidapi.hid_open_path.argtypes = [ctypes.c_char_p]
_hidapi.hid_open_path.restype = ctypes.c_void_p
_hidapi.hid_write.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
_hidapi.hid_write.restype = ctypes.c_int
_hidapi.hid_read_timeout.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_int]
_hidapi.hid_read_timeout.restype = ctypes.c_int
_hidapi.hid_read.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
_hidapi.hid_read.restype = ctypes.c_int
_hidapi.hid_get_input_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
_hidapi.hid_get_input_report.restype = ctypes.c_int
_hidapi.hid_set_nonblocking.argtypes = [ctypes.c_void_p, ctypes.c_int]
_hidapi.hid_set_nonblocking.restype = ctypes.c_int
_hidapi.hid_send_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
_hidapi.hid_send_feature_report.restype = ctypes.c_int
_hidapi.hid_get_feature_report.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
_hidapi.hid_get_feature_report.restype = ctypes.c_int
_hidapi.hid_close.argtypes = [ctypes.c_void_p]
_hidapi.hid_close.restype = None
_hidapi.hid_get_manufacturer_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
_hidapi.hid_get_manufacturer_string.restype = ctypes.c_int
_hidapi.hid_get_product_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
_hidapi.hid_get_product_string.restype = ctypes.c_int
_hidapi.hid_get_serial_number_string.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_size_t]
_hidapi.hid_get_serial_number_string.restype = ctypes.c_int
_hidapi.hid_get_indexed_string.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p, ctypes.c_size_t]
_hidapi.hid_get_indexed_string.restype = ctypes.c_int
_hidapi.hid_error.argtypes = [ctypes.c_void_p]
_hidapi.hid_error.restype = ctypes.c_wchar_p
# Initialize hidapi
_hidapi.hid_init()
atexit.register(_hidapi.hid_exit)
# Solaar opens the same device more than once which will fail unless we
# allow non-exclusive opening. On windows opening with shared access is
# the default, for macOS we need to set it explicitly.
if platform.system() == "Darwin":
_hidapi.hid_darwin_set_open_exclusive.argtypes = [ctypes.c_int]
_hidapi.hid_darwin_set_open_exclusive.restype = None
_hidapi.hid_darwin_set_open_exclusive(0)
class HIDError(Exception):
pass
def _enumerate_devices():
"""Returns all HID devices which are potentially useful to us"""
devices = []
c_devices = _hidapi.hid_enumerate(0, 0)
p = c_devices
while p:
devices.append(p.contents.as_dict())
p = p.contents.next
_hidapi.hid_free_enumeration(c_devices)
keyboard_or_mouse = {d["path"] for d in devices if d["usage_page"] == 1 and d["usage"] in (6, 2)}
unique_devices = {}
for device in devices:
# On macOS we cannot access keyboard or mouse devices without special permissions. Since
# we don't need them anyway we remove them so opening them doesn't cause errors later.
if device["path"] in keyboard_or_mouse:
# print(f"Ignoring keyboard or mouse device: {device}")
continue
# hidapi returns separate entries for each usage page of a device.
# Deduplicate by path to only keep one device entry.
if device["path"] not in unique_devices:
unique_devices[device["path"]] = device
unique_devices = unique_devices.values()
# print("Unique devices:\n" + '\n'.join([f"{dev}" for dev in unique_devices]))
return unique_devices
# Use a separate thread to check if devices have been removed or connected
class _DeviceMonitor(Thread):
def __init__(self, device_callback, polling_delay=5.0):
self.device_callback = device_callback
self.polling_delay = polling_delay
self.prev_devices = None
# daemon threads are automatically killed when main thread exits
super().__init__(daemon=True)
def run(self):
# Populate initial set of devices so startup doesn't cause any callbacks
self.prev_devices = {tuple(dev.items()): dev for dev in _enumerate_devices()}
# Continously enumerate devices and raise callback for changes
while True:
current_devices = {tuple(dev.items()): dev for dev in _enumerate_devices()}
for key, device in self.prev_devices.items():
if key not in current_devices:
self.device_callback(ACTION_REMOVE, device)
for key, device in current_devices.items():
if key not in self.prev_devices:
self.device_callback(ACTION_ADD, device)
self.prev_devices = current_devices
sleep(self.polling_delay)
def _match(
action: str,
device,
filter_func: Callable[[int, int, int, bool, bool], dict[str, Any]],
):
"""
The filter_func is used to determine whether this is a device of
interest to Solaar. It is given the bus id, vendor id, and product
id and returns a dictionary with the required hid_driver and
usb_interface and whether this is a receiver or device.
"""
vid = device["vendor_id"]
pid = device["product_id"]
# Translate hidapi bus_type to the bus_id values Solaar expects
if device.get("bus_type") == 0x01:
bus_id = 0x03 # USB
elif device.get("bus_type") == 0x02:
bus_id = 0x05 # Bluetooth
else:
bus_id = None
# Check for hidpp support
device["hidpp_short"] = False
device["hidpp_long"] = False
device_handle = None
try:
device_handle = open_path(device["path"])
report = _get_input_report(device_handle, 0x10, 32)
if len(report) == 1 + 6 and report[0] == 0x10:
device["hidpp_short"] = True
report = _get_input_report(device_handle, 0x11, 32)
if len(report) == 1 + 19 and report[0] == 0x11:
device["hidpp_long"] = True
except HIDError as e: # noqa: F841
if logger.isEnabledFor(logging.INFO):
logger.info(f"Error opening device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}") # noqa
finally:
if device_handle:
close(device_handle)
if logger.isEnabledFor(logging.INFO):
logger.info(
"Found device BID %s VID %04X PID %04X HID++ %s %s",
bus_id,
vid,
pid,
device["hidpp_short"],
device["hidpp_long"],
)
if not device["hidpp_short"] and not device["hidpp_long"]:
return None
filtered_result = filter_func(bus_id, vid, pid, device["hidpp_short"], device["hidpp_long"])
if not filtered_result:
return
is_device = filtered_result.get("isDevice")
if action == ACTION_ADD:
d_info = DeviceInfo(
path=device["path"].decode(),
bus_id=bus_id,
vendor_id=f"{vid:04X}", # noqa
product_id=f"{pid:04X}", # noqa
interface=None,
driver=None,
manufacturer=device["manufacturer_string"],
product=device["product_string"],
serial=device["serial_number"],
release=device["release_number"],
isDevice=is_device,
hidpp_short=device["hidpp_short"],
hidpp_long=device["hidpp_long"],
)
return d_info
elif action == ACTION_REMOVE:
d_info = DeviceInfo(
path=device["path"].decode(),
bus_id=None,
vendor_id=f"{vid:04X}", # noqa
product_id=f"{pid:04X}", # noqa
interface=None,
driver=None,
manufacturer=None,
product=None,
serial=None,
release=None,
isDevice=is_device,
hidpp_short=None,
hidpp_long=None,
)
return d_info
def find_paired_node(receiver_path: str, index: int, timeout: int):
"""Find the node of a device paired with a receiver"""
return None
def find_paired_node_wpid(receiver_path: str, index: int):
"""Find the node of a device paired with a receiver, get wpid from udev"""
return None
def monitor_glib(
glib: GLib,
callback: Callable,
filter_func: Callable[[int, int, int, bool, bool], dict[str, Any]],
) -> None:
"""Monitor GLib.
Parameters
----------
glib
GLib instance.
callback
Called when device found.
filter_func
Filter devices callback.
"""
def device_callback(action: str, device):
if action == ACTION_ADD:
d_info = _match(action, device, filter_func)
if d_info:
glib.idle_add(callback, action, d_info)
elif action == ACTION_REMOVE:
# Removed devices will be detected by Solaar directly
pass
monitor = _DeviceMonitor(device_callback=device_callback)
monitor.start()
def enumerate(filter_func) -> DeviceInfo:
"""Enumerate the HID Devices.
List all the HID devices attached to the system, optionally filtering by
vendor_id, product_id, and/or interface_number.
:returns: a list of matching ``DeviceInfo`` tuples.
"""
for device in _enumerate_devices():
d_info = _match(ACTION_ADD, device, filter_func)
if d_info:
yield d_info
def open(vendor_id, product_id, serial=None):
"""Open a HID device by its Vendor ID, Product ID and optional serial number.
If no serial is provided, the first device with the specified IDs is opened.
:returns: an opaque device handle, or ``None``.
"""
if serial is not None:
serial = ctypes.create_unicode_buffer(serial)
device_handle = _hidapi.hid_open(vendor_id, product_id, serial)
if device_handle is None:
raise HIDError(_hidapi.hid_error(None))
return device_handle
def open_path(device_path) -> Any:
"""Open a HID device by its path name.
:param device_path: the path of a ``DeviceInfo`` tuple returned by enumerate().
:returns: an opaque device handle, or ``None``.
"""
if not isinstance(device_path, bytes):
device_path = device_path.encode()
device_handle = _hidapi.hid_open_path(device_path)
if device_handle is None:
raise HIDError(_hidapi.hid_error(None))
return device_handle
def close(device_handle) -> None:
"""Close a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
assert device_handle
_hidapi.hid_close(device_handle)
def write(device_handle: int, data: bytes) -> int:
"""Write an Output report to a HID device.
:param device_handle: a device handle returned by open() or open_path().
:param data: the data bytes to send including the report number as the
first byte.
The first byte of data[] must contain the Report ID. For
devices which only support a single report, this must be set
to 0x0. The remaining bytes contain the report data. Since
the Report ID is mandatory, calls to hid_write() will always
contain one more byte than the report contains. For example,
if a hid report is 16 bytes long, 17 bytes must be passed to
hid_write(), the Report ID (or 0x0, for devices with a
single report), followed by the report data (16 bytes). In
this example, the length passed in would be 17.
write() will send the data on the first OUT endpoint, if
one exists. If it does not, it will send the data through
the Control Endpoint (Endpoint 0).
"""
assert device_handle
assert data
assert isinstance(data, bytes), (repr(data), type(data))
bytes_written = _hidapi.hid_write(device_handle, data, len(data))
if bytes_written < 0:
raise HIDError(_hidapi.hid_error(device_handle))
return bytes_written
def read(device_handle, bytes_count, timeout_ms=None):
"""Read an Input report from a HID device.
:param device_handle: a device handle returned by open() or open_path().
:param bytes_count: maximum number of bytes to read.
:param timeout_ms: can be -1 (default) to wait for data indefinitely, 0 to
read whatever is in the device's input buffer, or a positive integer to
wait that many milliseconds.
Input reports are returned to the host through the INTERRUPT IN endpoint.
The first byte will contain the Report number if the device uses numbered
reports.
:returns: the data packet read, an empty bytes string if a timeout was
reached, or None if there was an error while reading.
"""
assert device_handle
data = ctypes.create_string_buffer(bytes_count)
if timeout_ms is None or timeout_ms < 0:
bytes_read = _hidapi.hid_read(device_handle, data, bytes_count)
else:
bytes_read = _hidapi.hid_read_timeout(device_handle, data, bytes_count, timeout_ms)
if bytes_read < 0:
raise HIDError(_hidapi.hid_error(device_handle))
return data.raw[:bytes_read]
def _get_input_report(device_handle, report_id, size):
assert device_handle
data = ctypes.create_string_buffer(size)
data[0] = bytearray((report_id,))
size = _hidapi.hid_get_input_report(device_handle, data, size)
if size < 0:
raise HIDError(_hidapi.hid_error(device_handle))
return data.raw[:size]
def _readstring(device_handle, func, max_length=255):
assert device_handle
buf = ctypes.create_unicode_buffer(max_length)
ret = func(device_handle, buf, max_length)
if ret < 0:
raise HIDError("Error reading device property")
return buf.value
def get_manufacturer(device_handle):
"""Get the Manufacturer String from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
return _readstring(device_handle, _hidapi.get_manufacturer_string)
def get_product(device_handle):
"""Get the Product String from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
return _readstring(device_handle, _hidapi.get_product_string)
def get_serial(device_handle):
"""Get the serial number from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
return _readstring(device_handle, _hidapi.get_serial_number_string)
| 18,269 | Python | .py | 424 | 37.365566 | 125 | 0.682482 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,506 | common.py | pwr-Solaar_Solaar/lib/hidapi/common.py | from __future__ import annotations
import dataclasses
@dataclasses.dataclass
class DeviceInfo:
path: str
bus_id: str | None
vendor_id: str
product_id: str
interface: str | None
driver: str | None
manufacturer: str | None
product: str | None
serial: str | None
release: str | None
isDevice: bool
hidpp_short: str | None
hidpp_long: str | None
| 397 | Python | .py | 17 | 19.117647 | 34 | 0.676393 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,507 | udev_impl.py | pwr-Solaar_Solaar/lib/hidapi/udev_impl.py | ## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Generic Human Interface Device API.
It is currently a partial pure-Python implementation of the native HID API
implemented by signal11 (https://github.com/signal11/hidapi), and requires
``pyudev``.
The docstrings are mostly copied from the hidapi API header, with changes where
necessary.
"""
from __future__ import annotations
import errno
import logging
import os
import typing
import warnings
# the tuple object we'll expose when enumerating devices
from select import select
from time import sleep
from time import time
from typing import Callable
import pyudev
from hidapi.common import DeviceInfo
if typing.TYPE_CHECKING:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import GLib # NOQA: E402
logger = logging.getLogger(__name__)
fileopen = open
ACTION_ADD = "add"
ACTION_REMOVE = "remove"
#
# exposed API
# docstrings mostly copied from hidapi.h
#
def init():
"""This function is a no-op, and exists only to match the native hidapi
implementation.
:returns: ``True``.
"""
return True
def exit():
"""This function is a no-op, and exists only to match the native hidapi
implementation.
:returns: ``True``.
"""
return True
def _match(action: str, device, filter_func: typing.Callable[[int, int, int, bool, bool], dict[str, typing.Any]]):
"""
The filter_func is used to determine whether this is a device of
interest to Solaar. It is given the bus id, vendor id, and product
id and returns a dictionary with the required hid_driver and
usb_interface and whether this is a receiver or device."""
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"Dbus event {action} {device}")
hid_device = device.find_parent("hid")
if hid_device is None: # only HID devices are of interest to Solaar
return
hid_id = hid_device.properties.get("HID_ID")
if not hid_id:
return # there are reports that sometimes the id isn't set up right so be defensive
bid, vid, pid = hid_id.split(":")
hid_hid_device = hid_device.find_parent("hid")
if hid_hid_device is not None:
return # these are devices connected through a receiver so don't pick them up here
try: # if report descriptor does not indicate HID++ capabilities then this device is not of interest to Solaar
from hid_parser import ReportDescriptor
hidpp_short = hidpp_long = False
devfile = "/sys" + hid_device.properties.get("DEVPATH") + "/report_descriptor"
with fileopen(devfile, "rb") as fd:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
rd = ReportDescriptor(fd.read())
hidpp_short = 0x10 in rd.input_report_ids and 6 * 8 == int(rd.get_input_report_size(0x10))
# and _Usage(0xFF00, 0x0001) in rd.get_input_items(0x10)[0].usages # be more permissive
hidpp_long = 0x11 in rd.input_report_ids and 19 * 8 == int(rd.get_input_report_size(0x11))
# and _Usage(0xFF00, 0x0002) in rd.get_input_items(0x11)[0].usages # be more permissive
if not hidpp_short and not hidpp_long:
return
except Exception as e: # if can't process report descriptor fall back to old scheme
hidpp_short = None
hidpp_long = None
logger.info(
"Report Descriptor not processed for DEVICE %s BID %s VID %s PID %s: %s",
device.device_node,
bid,
vid,
pid,
e,
)
filtered_result = filter_func(int(bid, 16), int(vid, 16), int(pid, 16), hidpp_short, hidpp_long)
if not filtered_result:
return
interface_number = filtered_result.get("usb_interface")
isDevice = filtered_result.get("isDevice")
if action == ACTION_ADD:
hid_driver_name = hid_device.properties.get("DRIVER")
intf_device = device.find_parent("usb", "usb_interface")
usb_interface = None if intf_device is None else intf_device.attributes.asint("bInterfaceNumber")
# print('*** usb interface', action, device, 'usb_interface:', intf_device, usb_interface, interface_number)
if logger.isEnabledFor(logging.INFO):
logger.info(
"Found device %s BID %s VID %s PID %s HID++ %s %s USB %s %s",
device.device_node,
bid,
vid,
pid,
hidpp_short,
hidpp_long,
usb_interface,
interface_number,
)
if not (hidpp_short or hidpp_long or interface_number is None or interface_number == usb_interface):
return
attrs = intf_device.attributes if intf_device is not None else None
d_info = DeviceInfo(
path=device.device_node,
bus_id=int(bid, 16),
vendor_id=vid[-4:],
product_id=pid[-4:],
interface=usb_interface,
driver=hid_driver_name,
manufacturer=attrs.get("manufacturer") if attrs else None,
product=attrs.get("product") if attrs else None,
serial=hid_device.properties.get("HID_UNIQ"),
release=attrs.get("bcdDevice") if attrs else None,
isDevice=isDevice,
hidpp_short=hidpp_short,
hidpp_long=hidpp_long,
)
return d_info
elif action == ACTION_REMOVE:
d_info = DeviceInfo(
path=device.device_node,
bus_id=None,
vendor_id=vid[-4:],
product_id=pid[-4:],
interface=None,
driver=None,
manufacturer=None,
product=None,
serial=None,
release=None,
isDevice=isDevice,
hidpp_short=None,
hidpp_long=None,
)
return d_info
def find_paired_node(receiver_path: str, index: int, timeout: int):
"""Find the node of a device paired with a receiver"""
context = pyudev.Context()
receiver_phys = pyudev.Devices.from_device_file(context, receiver_path).find_parent("hid").get("HID_PHYS")
if not receiver_phys:
return None
phys = f"{receiver_phys}:{index}" # noqa: E231
timeout += time()
delta = time()
while delta < timeout:
for dev in context.list_devices(subsystem="hidraw"):
dev_phys = dev.find_parent("hid").get("HID_PHYS")
if dev_phys and dev_phys == phys:
return dev.device_node
delta = time()
return None
def find_paired_node_wpid(receiver_path: str, index: int):
"""Find the node of a device paired with a receiver, get wpid from udev"""
context = pyudev.Context()
receiver_phys = pyudev.Devices.from_device_file(context, receiver_path).find_parent("hid").get("HID_PHYS")
if not receiver_phys:
return None
phys = f"{receiver_phys}:{index}" # noqa: E231
for dev in context.list_devices(subsystem="hidraw"):
dev_phys = dev.find_parent("hid").get("HID_PHYS")
if dev_phys and dev_phys == phys:
# get hid id like 0003:0000046D:00000065
hid_id = dev.find_parent("hid").get("HID_ID")
# get wpid - last 4 symbols
udev_wpid = hid_id[-4:]
return udev_wpid
return None
def monitor_glib(glib: GLib, callback: Callable, filter_func: Callable):
"""Monitor GLib.
Parameters
----------
glib
GLib instance.
"""
c = pyudev.Context()
m = pyudev.Monitor.from_netlink(c)
m.filter_by(subsystem="hidraw")
def _process_udev_event(monitor, condition, cb, filter_func):
if condition == glib.IO_IN:
event = monitor.receive_device()
if event:
action, device = event
# print ("***", action, device)
if action == ACTION_ADD:
d_info = _match(action, device, filter_func)
if d_info:
glib.idle_add(cb, action, d_info)
elif action == ACTION_REMOVE:
# the GLib notification does _not_ match!
pass
return True
try:
# io_add_watch_full may not be available...
glib.io_add_watch_full(m, glib.PRIORITY_LOW, glib.IO_IN, _process_udev_event, callback, filter_func)
except AttributeError:
try:
# and the priority parameter appeared later in the API
glib.io_add_watch(m, glib.PRIORITY_LOW, glib.IO_IN, _process_udev_event, callback, filter_func)
except Exception:
glib.io_add_watch(m, glib.IO_IN, _process_udev_event, callback, filter_func)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Starting dbus monitoring")
m.start()
def enumerate(filter_func: typing.Callable[[int, int, int, bool, bool], dict[str, typing.Any]]):
"""Enumerate the HID Devices.
List all the HID devices attached to the system, optionally filtering by
vendor_id, product_id, and/or interface_number.
:returns: a list of matching ``DeviceInfo`` tuples.
"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Starting dbus enumeration")
for dev in pyudev.Context().list_devices(subsystem="hidraw"):
dev_info = _match(ACTION_ADD, dev, filter_func)
if dev_info:
yield dev_info
def open(vendor_id, product_id, serial=None):
"""Open a HID device by its Vendor ID, Product ID and optional serial number.
If no serial is provided, the first device with the specified IDs is opened.
:returns: an opaque device handle, or ``None``.
"""
def matchfn(bid, vid, pid):
return vid == vendor_id and pid == product_id
for device in enumerate(matchfn):
if serial is None or serial == device.serial:
return open_path(device.path)
def open_path(device_path):
"""Open a HID device by its path name.
:param device_path: the path of a ``DeviceInfo`` tuple returned by enumerate().
:returns: an opaque device handle, or ``None``.
"""
assert device_path
assert device_path.startswith("/dev/hidraw")
logger.info("OPEN PATH %s", device_path)
retrycount = 0
while retrycount < 3:
retrycount += 1
try:
return os.open(device_path, os.O_RDWR | os.O_SYNC)
except OSError as e:
logger.info("OPEN PATH FAILED %s ERROR %s %s", device_path, e.errno, e)
if e.errno == errno.EACCES:
sleep(0.1)
else:
raise
def close(device_handle) -> None:
"""Close a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
assert device_handle
os.close(device_handle)
def write(device_handle, data):
"""Write an Output report to a HID device.
:param device_handle: a device handle returned by open() or open_path().
:param data: the data bytes to send including the report number as the
first byte.
The first byte of data[] must contain the Report ID. For
devices which only support a single report, this must be set
to 0x0. The remaining bytes contain the report data. Since
the Report ID is mandatory, calls to hid_write() will always
contain one more byte than the report contains. For example,
if a hid report is 16 bytes long, 17 bytes must be passed to
hid_write(), the Report ID (or 0x0, for devices with a
single report), followed by the report data (16 bytes). In
this example, the length passed in would be 17.
write() will send the data on the first OUT endpoint, if
one exists. If it does not, it will send the data through
the Control Endpoint (Endpoint 0).
"""
assert device_handle
assert data
assert isinstance(data, bytes), (repr(data), type(data))
retrycount = 0
bytes_written = 0
while retrycount < 3:
try:
retrycount += 1
bytes_written = os.write(device_handle, data)
except OSError as e:
if e.errno == errno.EPIPE:
sleep(0.1)
else:
break
if bytes_written != len(data):
raise OSError(errno.EIO, f"written {int(bytes_written)} bytes out of expected {len(data)}")
def read(device_handle, bytes_count, timeout_ms=-1):
"""Read an Input report from a HID device.
:param device_handle: a device handle returned by open() or open_path().
:param bytes_count: maximum number of bytes to read.
:param timeout_ms: can be -1 (default) to wait for data indefinitely, 0 to
read whatever is in the device's input buffer, or a positive integer to
wait that many milliseconds.
Input reports are returned to the host through the INTERRUPT IN endpoint.
The first byte will contain the Report number if the device uses numbered
reports.
:returns: the data packet read, an empty bytes string if a timeout was
reached, or None if there was an error while reading.
"""
assert device_handle
timeout = None if timeout_ms < 0 else timeout_ms / 1000.0
rlist, wlist, xlist = select([device_handle], [], [device_handle], timeout)
if xlist:
assert xlist == [device_handle]
raise OSError(errno.EIO, f"exception on file descriptor {int(device_handle)}")
if rlist:
assert rlist == [device_handle]
data = os.read(device_handle, bytes_count)
assert data is not None
assert isinstance(data, bytes), (repr(data), type(data))
return data
else:
return b""
_DEVICE_STRINGS = {
0: "manufacturer",
1: "product",
2: "serial",
}
def get_manufacturer(device_handle):
"""Get the Manufacturer String from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
return get_indexed_string(device_handle, 0)
def get_product(device_handle):
"""Get the Product String from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
return get_indexed_string(device_handle, 1)
def get_serial(device_handle):
"""Get the serial number from a HID device.
:param device_handle: a device handle returned by open() or open_path().
"""
serial = get_indexed_string(device_handle, 2)
return serial
def get_indexed_string(device_handle, index):
"""Get a string from a HID device, based on its string index.
Note: currently not working in the ``hidraw`` native implementation.
:param device_handle: a device handle returned by open() or open_path().
:param index: the index of the string to get.
:returns: the value corresponding to index, or None if no value found
:rtype: bytes or NoneType
"""
try:
key = _DEVICE_STRINGS[index]
except KeyError:
return None
assert device_handle
stat = os.fstat(device_handle)
try:
dev = pyudev.Devices.from_device_number(pyudev.Context(), "char", stat.st_rdev)
except (pyudev.DeviceNotFoundError, ValueError):
return None
hid_dev = dev.find_parent("hid")
if hid_dev:
assert "HID_ID" in hid_dev
bus, _ignore, _ignore = hid_dev["HID_ID"].split(":")
if bus == "0003": # USB
usb_dev = dev.find_parent("usb", "usb_device")
assert usb_dev
return usb_dev.attributes.get(key)
elif bus == "0005": # BLUETOOTH
# TODO
pass
| 16,249 | Python | .py | 386 | 34.559585 | 116 | 0.645358 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,508 | generate.py | pwr-Solaar_Solaar/lib/keysyms/generate.py | #!/usr/bin/env python3
"""Extract key symbol encodings from X11 header files."""
from pathlib import Path
from pprint import pprint
from re import findall
from subprocess import run
from tempfile import TemporaryDirectory
repo = "https://gitlab.freedesktop.org/xorg/proto/xorgproto.git"
pattern = r"#define XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?"
xf86pattern = r"#define XF86XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?"
def main():
keysymdef = {}
keysym_files = [
("include/X11/keysymdef.h", pattern, ""),
("include/X11/XF86keysym.h", xf86pattern, "XF86_"),
]
with TemporaryDirectory() as temp:
run(["git", "clone", repo, "."], cwd=temp)
for filename, extraction_pattern, prefix in keysym_files:
text = Path(temp, filename).read_text()
for name, sym, _ in findall(extraction_pattern, text):
sym = int(sym, 16)
if keysymdef.get(f"{prefix}{name}", None):
print(f"KEY DUP {prefix}{name}")
keysymdef[f"{prefix}{name}"] = sym
with open("keysymdef.py", "w") as f:
f.write("# flake8: noqa\nkey_symbols = \\\n")
pprint(keysymdef, f)
if __name__ == "__main__":
main()
| 1,231 | Python | .py | 30 | 34.266667 | 69 | 0.594799 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,509 | keysymdef.py | pwr-Solaar_Solaar/lib/keysyms/keysymdef.py | # flake8: noqa
key_symbols = {
"0": 48,
"1": 49,
"2": 50,
"3": 51,
"3270_AltCursor": 64784,
"3270_Attn": 64782,
"3270_BackTab": 64773,
"3270_ChangeScreen": 64793,
"3270_Copy": 64789,
"3270_CursorBlink": 64783,
"3270_CursorSelect": 64796,
"3270_DeleteWord": 64794,
"3270_Duplicate": 64769,
"3270_Enter": 64798,
"3270_EraseEOF": 64774,
"3270_EraseInput": 64775,
"3270_ExSelect": 64795,
"3270_FieldMark": 64770,
"3270_Ident": 64787,
"3270_Jump": 64786,
"3270_KeyClick": 64785,
"3270_Left2": 64772,
"3270_PA1": 64778,
"3270_PA2": 64779,
"3270_PA3": 64780,
"3270_Play": 64790,
"3270_PrintScreen": 64797,
"3270_Quit": 64777,
"3270_Record": 64792,
"3270_Reset": 64776,
"3270_Right2": 64771,
"3270_Rule": 64788,
"3270_Setup": 64791,
"3270_Test": 64781,
"4": 52,
"5": 53,
"6": 54,
"7": 55,
"8": 56,
"9": 57,
"A": 65,
"AE": 198,
"Aacute": 193,
"Abelowdot": 16785056,
"Abreve": 451,
"Abreveacute": 16785070,
"Abrevebelowdot": 16785078,
"Abrevegrave": 16785072,
"Abrevehook": 16785074,
"Abrevetilde": 16785076,
"AccessX_Enable": 65136,
"AccessX_Feedback_Enable": 65137,
"Acircumflex": 194,
"Acircumflexacute": 16785060,
"Acircumflexbelowdot": 16785068,
"Acircumflexgrave": 16785062,
"Acircumflexhook": 16785064,
"Acircumflextilde": 16785066,
"Adiaeresis": 196,
"Agrave": 192,
"Ahook": 16785058,
"Alt_L": 65513,
"Alt_R": 65514,
"Amacron": 960,
"Aogonek": 417,
"Arabic_0": 16778848,
"Arabic_1": 16778849,
"Arabic_2": 16778850,
"Arabic_3": 16778851,
"Arabic_4": 16778852,
"Arabic_5": 16778853,
"Arabic_6": 16778854,
"Arabic_7": 16778855,
"Arabic_8": 16778856,
"Arabic_9": 16778857,
"Arabic_ain": 1497,
"Arabic_alef": 1479,
"Arabic_alefmaksura": 1513,
"Arabic_beh": 1480,
"Arabic_comma": 1452,
"Arabic_dad": 1494,
"Arabic_dal": 1487,
"Arabic_damma": 1519,
"Arabic_dammatan": 1516,
"Arabic_ddal": 16778888,
"Arabic_farsi_yeh": 16778956,
"Arabic_fatha": 1518,
"Arabic_fathatan": 1515,
"Arabic_feh": 1505,
"Arabic_fullstop": 16778964,
"Arabic_gaf": 16778927,
"Arabic_ghain": 1498,
"Arabic_ha": 1511,
"Arabic_hah": 1485,
"Arabic_hamza": 1473,
"Arabic_hamza_above": 16778836,
"Arabic_hamza_below": 16778837,
"Arabic_hamzaonalef": 1475,
"Arabic_hamzaonwaw": 1476,
"Arabic_hamzaonyeh": 1478,
"Arabic_hamzaunderalef": 1477,
"Arabic_heh": 1511,
"Arabic_heh_doachashmee": 16778942,
"Arabic_heh_goal": 16778945,
"Arabic_jeem": 1484,
"Arabic_jeh": 16778904,
"Arabic_kaf": 1507,
"Arabic_kasra": 1520,
"Arabic_kasratan": 1517,
"Arabic_keheh": 16778921,
"Arabic_khah": 1486,
"Arabic_lam": 1508,
"Arabic_madda_above": 16778835,
"Arabic_maddaonalef": 1474,
"Arabic_meem": 1509,
"Arabic_noon": 1510,
"Arabic_noon_ghunna": 16778938,
"Arabic_peh": 16778878,
"Arabic_percent": 16778858,
"Arabic_qaf": 1506,
"Arabic_question_mark": 1471,
"Arabic_ra": 1489,
"Arabic_rreh": 16778897,
"Arabic_sad": 1493,
"Arabic_seen": 1491,
"Arabic_semicolon": 1467,
"Arabic_shadda": 1521,
"Arabic_sheen": 1492,
"Arabic_sukun": 1522,
"Arabic_superscript_alef": 16778864,
"Arabic_switch": 65406,
"Arabic_tah": 1495,
"Arabic_tatweel": 1504,
"Arabic_tcheh": 16778886,
"Arabic_teh": 1482,
"Arabic_tehmarbuta": 1481,
"Arabic_thal": 1488,
"Arabic_theh": 1483,
"Arabic_tteh": 16778873,
"Arabic_veh": 16778916,
"Arabic_waw": 1512,
"Arabic_yeh": 1514,
"Arabic_yeh_baree": 16778962,
"Arabic_zah": 1496,
"Arabic_zain": 1490,
"Aring": 197,
"Armenian_AT": 16778552,
"Armenian_AYB": 16778545,
"Armenian_BEN": 16778546,
"Armenian_CHA": 16778569,
"Armenian_DA": 16778548,
"Armenian_DZA": 16778561,
"Armenian_E": 16778551,
"Armenian_FE": 16778582,
"Armenian_GHAT": 16778562,
"Armenian_GIM": 16778547,
"Armenian_HI": 16778565,
"Armenian_HO": 16778560,
"Armenian_INI": 16778555,
"Armenian_JE": 16778571,
"Armenian_KE": 16778580,
"Armenian_KEN": 16778559,
"Armenian_KHE": 16778557,
"Armenian_LYUN": 16778556,
"Armenian_MEN": 16778564,
"Armenian_NU": 16778566,
"Armenian_O": 16778581,
"Armenian_PE": 16778570,
"Armenian_PYUR": 16778579,
"Armenian_RA": 16778572,
"Armenian_RE": 16778576,
"Armenian_SE": 16778573,
"Armenian_SHA": 16778567,
"Armenian_TCHE": 16778563,
"Armenian_TO": 16778553,
"Armenian_TSA": 16778558,
"Armenian_TSO": 16778577,
"Armenian_TYUN": 16778575,
"Armenian_VEV": 16778574,
"Armenian_VO": 16778568,
"Armenian_VYUN": 16778578,
"Armenian_YECH": 16778549,
"Armenian_ZA": 16778550,
"Armenian_ZHE": 16778554,
"Armenian_accent": 16778587,
"Armenian_amanak": 16778588,
"Armenian_apostrophe": 16778586,
"Armenian_at": 16778600,
"Armenian_ayb": 16778593,
"Armenian_ben": 16778594,
"Armenian_but": 16778589,
"Armenian_cha": 16778617,
"Armenian_da": 16778596,
"Armenian_dza": 16778609,
"Armenian_e": 16778599,
"Armenian_exclam": 16778588,
"Armenian_fe": 16778630,
"Armenian_full_stop": 16778633,
"Armenian_ghat": 16778610,
"Armenian_gim": 16778595,
"Armenian_hi": 16778613,
"Armenian_ho": 16778608,
"Armenian_hyphen": 16778634,
"Armenian_ini": 16778603,
"Armenian_je": 16778619,
"Armenian_ke": 16778628,
"Armenian_ken": 16778607,
"Armenian_khe": 16778605,
"Armenian_ligature_ew": 16778631,
"Armenian_lyun": 16778604,
"Armenian_men": 16778612,
"Armenian_nu": 16778614,
"Armenian_o": 16778629,
"Armenian_paruyk": 16778590,
"Armenian_pe": 16778618,
"Armenian_pyur": 16778627,
"Armenian_question": 16778590,
"Armenian_ra": 16778620,
"Armenian_re": 16778624,
"Armenian_se": 16778621,
"Armenian_separation_mark": 16778589,
"Armenian_sha": 16778615,
"Armenian_shesht": 16778587,
"Armenian_tche": 16778611,
"Armenian_to": 16778601,
"Armenian_tsa": 16778606,
"Armenian_tso": 16778625,
"Armenian_tyun": 16778623,
"Armenian_verjaket": 16778633,
"Armenian_vev": 16778622,
"Armenian_vo": 16778616,
"Armenian_vyun": 16778626,
"Armenian_yech": 16778597,
"Armenian_yentamna": 16778634,
"Armenian_za": 16778598,
"Armenian_zhe": 16778602,
"Atilde": 195,
"AudibleBell_Enable": 65146,
"B": 66,
"Babovedot": 16784898,
"BackSpace": 65288,
"Begin": 65368,
"BounceKeys_Enable": 65140,
"Break": 65387,
"Byelorussian_SHORTU": 1726,
"Byelorussian_shortu": 1710,
"C": 67,
"CH": 65186,
"C_H": 65189,
"C_h": 65188,
"Cabovedot": 709,
"Cacute": 454,
"Cancel": 65385,
"Caps_Lock": 65509,
"Ccaron": 456,
"Ccedilla": 199,
"Ccircumflex": 710,
"Ch": 65185,
"Clear": 65291,
"Codeinput": 65335,
"ColonSign": 16785569,
"Control_L": 65507,
"Control_R": 65508,
"CruzeiroSign": 16785570,
"Cyrillic_A": 1761,
"Cyrillic_BE": 1762,
"Cyrillic_CHE": 1790,
"Cyrillic_CHE_descender": 16778422,
"Cyrillic_CHE_vertstroke": 16778424,
"Cyrillic_DE": 1764,
"Cyrillic_DZHE": 1727,
"Cyrillic_E": 1788,
"Cyrillic_EF": 1766,
"Cyrillic_EL": 1772,
"Cyrillic_EM": 1773,
"Cyrillic_EN": 1774,
"Cyrillic_EN_descender": 16778402,
"Cyrillic_ER": 1778,
"Cyrillic_ES": 1779,
"Cyrillic_GHE": 1767,
"Cyrillic_GHE_bar": 16778386,
"Cyrillic_HA": 1768,
"Cyrillic_HARDSIGN": 1791,
"Cyrillic_HA_descender": 16778418,
"Cyrillic_I": 1769,
"Cyrillic_IE": 1765,
"Cyrillic_IO": 1715,
"Cyrillic_I_macron": 16778466,
"Cyrillic_JE": 1720,
"Cyrillic_KA": 1771,
"Cyrillic_KA_descender": 16778394,
"Cyrillic_KA_vertstroke": 16778396,
"Cyrillic_LJE": 1721,
"Cyrillic_NJE": 1722,
"Cyrillic_O": 1775,
"Cyrillic_O_bar": 16778472,
"Cyrillic_PE": 1776,
"Cyrillic_SCHWA": 16778456,
"Cyrillic_SHA": 1787,
"Cyrillic_SHCHA": 1789,
"Cyrillic_SHHA": 16778426,
"Cyrillic_SHORTI": 1770,
"Cyrillic_SOFTSIGN": 1784,
"Cyrillic_TE": 1780,
"Cyrillic_TSE": 1763,
"Cyrillic_U": 1781,
"Cyrillic_U_macron": 16778478,
"Cyrillic_U_straight": 16778414,
"Cyrillic_U_straight_bar": 16778416,
"Cyrillic_VE": 1783,
"Cyrillic_YA": 1777,
"Cyrillic_YERU": 1785,
"Cyrillic_YU": 1760,
"Cyrillic_ZE": 1786,
"Cyrillic_ZHE": 1782,
"Cyrillic_ZHE_descender": 16778390,
"Cyrillic_a": 1729,
"Cyrillic_be": 1730,
"Cyrillic_che": 1758,
"Cyrillic_che_descender": 16778423,
"Cyrillic_che_vertstroke": 16778425,
"Cyrillic_de": 1732,
"Cyrillic_dzhe": 1711,
"Cyrillic_e": 1756,
"Cyrillic_ef": 1734,
"Cyrillic_el": 1740,
"Cyrillic_em": 1741,
"Cyrillic_en": 1742,
"Cyrillic_en_descender": 16778403,
"Cyrillic_er": 1746,
"Cyrillic_es": 1747,
"Cyrillic_ghe": 1735,
"Cyrillic_ghe_bar": 16778387,
"Cyrillic_ha": 1736,
"Cyrillic_ha_descender": 16778419,
"Cyrillic_hardsign": 1759,
"Cyrillic_i": 1737,
"Cyrillic_i_macron": 16778467,
"Cyrillic_ie": 1733,
"Cyrillic_io": 1699,
"Cyrillic_je": 1704,
"Cyrillic_ka": 1739,
"Cyrillic_ka_descender": 16778395,
"Cyrillic_ka_vertstroke": 16778397,
"Cyrillic_lje": 1705,
"Cyrillic_nje": 1706,
"Cyrillic_o": 1743,
"Cyrillic_o_bar": 16778473,
"Cyrillic_pe": 1744,
"Cyrillic_schwa": 16778457,
"Cyrillic_sha": 1755,
"Cyrillic_shcha": 1757,
"Cyrillic_shha": 16778427,
"Cyrillic_shorti": 1738,
"Cyrillic_softsign": 1752,
"Cyrillic_te": 1748,
"Cyrillic_tse": 1731,
"Cyrillic_u": 1749,
"Cyrillic_u_macron": 16778479,
"Cyrillic_u_straight": 16778415,
"Cyrillic_u_straight_bar": 16778417,
"Cyrillic_ve": 1751,
"Cyrillic_ya": 1745,
"Cyrillic_yeru": 1753,
"Cyrillic_yu": 1728,
"Cyrillic_ze": 1754,
"Cyrillic_zhe": 1750,
"Cyrillic_zhe_descender": 16778391,
"D": 68,
"Dabovedot": 16784906,
"Dcaron": 463,
"Delete": 65535,
"DongSign": 16785579,
"Down": 65364,
"Dstroke": 464,
"E": 69,
"ENG": 957,
"ETH": 208,
"EZH": 16777655,
"Eabovedot": 972,
"Eacute": 201,
"Ebelowdot": 16785080,
"Ecaron": 460,
"Ecircumflex": 202,
"Ecircumflexacute": 16785086,
"Ecircumflexbelowdot": 16785094,
"Ecircumflexgrave": 16785088,
"Ecircumflexhook": 16785090,
"Ecircumflextilde": 16785092,
"EcuSign": 16785568,
"Ediaeresis": 203,
"Egrave": 200,
"Ehook": 16785082,
"Eisu_Shift": 65327,
"Eisu_toggle": 65328,
"Emacron": 938,
"End": 65367,
"Eogonek": 458,
"Escape": 65307,
"Eth": 208,
"Etilde": 16785084,
"EuroSign": 8364,
"Execute": 65378,
"F": 70,
"F1": 65470,
"F10": 65479,
"F11": 65480,
"F12": 65481,
"F13": 65482,
"F14": 65483,
"F15": 65484,
"F16": 65485,
"F17": 65486,
"F18": 65487,
"F19": 65488,
"F2": 65471,
"F20": 65489,
"F21": 65490,
"F22": 65491,
"F23": 65492,
"F24": 65493,
"F25": 65494,
"F26": 65495,
"F27": 65496,
"F28": 65497,
"F29": 65498,
"F3": 65472,
"F30": 65499,
"F31": 65500,
"F32": 65501,
"F33": 65502,
"F34": 65503,
"F35": 65504,
"F4": 65473,
"F5": 65474,
"F6": 65475,
"F7": 65476,
"F8": 65477,
"F9": 65478,
"FFrancSign": 16785571,
"Fabovedot": 16784926,
"Farsi_0": 16778992,
"Farsi_1": 16778993,
"Farsi_2": 16778994,
"Farsi_3": 16778995,
"Farsi_4": 16778996,
"Farsi_5": 16778997,
"Farsi_6": 16778998,
"Farsi_7": 16778999,
"Farsi_8": 16779000,
"Farsi_9": 16779001,
"Farsi_yeh": 16778956,
"Find": 65384,
"First_Virtual_Screen": 65232,
"G": 71,
"Gabovedot": 725,
"Gbreve": 683,
"Gcaron": 16777702,
"Gcedilla": 939,
"Gcircumflex": 728,
"Georgian_an": 16781520,
"Georgian_ban": 16781521,
"Georgian_can": 16781546,
"Georgian_char": 16781549,
"Georgian_chin": 16781545,
"Georgian_cil": 16781548,
"Georgian_don": 16781523,
"Georgian_en": 16781524,
"Georgian_fi": 16781558,
"Georgian_gan": 16781522,
"Georgian_ghan": 16781542,
"Georgian_hae": 16781552,
"Georgian_har": 16781556,
"Georgian_he": 16781553,
"Georgian_hie": 16781554,
"Georgian_hoe": 16781557,
"Georgian_in": 16781528,
"Georgian_jhan": 16781551,
"Georgian_jil": 16781547,
"Georgian_kan": 16781529,
"Georgian_khar": 16781541,
"Georgian_las": 16781530,
"Georgian_man": 16781531,
"Georgian_nar": 16781532,
"Georgian_on": 16781533,
"Georgian_par": 16781534,
"Georgian_phar": 16781540,
"Georgian_qar": 16781543,
"Georgian_rae": 16781536,
"Georgian_san": 16781537,
"Georgian_shin": 16781544,
"Georgian_tan": 16781527,
"Georgian_tar": 16781538,
"Georgian_un": 16781539,
"Georgian_vin": 16781525,
"Georgian_we": 16781555,
"Georgian_xan": 16781550,
"Georgian_zen": 16781526,
"Georgian_zhar": 16781535,
"Greek_ALPHA": 1985,
"Greek_ALPHAaccent": 1953,
"Greek_BETA": 1986,
"Greek_CHI": 2007,
"Greek_DELTA": 1988,
"Greek_EPSILON": 1989,
"Greek_EPSILONaccent": 1954,
"Greek_ETA": 1991,
"Greek_ETAaccent": 1955,
"Greek_GAMMA": 1987,
"Greek_IOTA": 1993,
"Greek_IOTAaccent": 1956,
"Greek_IOTAdiaeresis": 1957,
"Greek_IOTAdieresis": 1957,
"Greek_KAPPA": 1994,
"Greek_LAMBDA": 1995,
"Greek_LAMDA": 1995,
"Greek_MU": 1996,
"Greek_NU": 1997,
"Greek_OMEGA": 2009,
"Greek_OMEGAaccent": 1963,
"Greek_OMICRON": 1999,
"Greek_OMICRONaccent": 1959,
"Greek_PHI": 2006,
"Greek_PI": 2000,
"Greek_PSI": 2008,
"Greek_RHO": 2001,
"Greek_SIGMA": 2002,
"Greek_TAU": 2004,
"Greek_THETA": 1992,
"Greek_UPSILON": 2005,
"Greek_UPSILONaccent": 1960,
"Greek_UPSILONdieresis": 1961,
"Greek_XI": 1998,
"Greek_ZETA": 1990,
"Greek_accentdieresis": 1966,
"Greek_alpha": 2017,
"Greek_alphaaccent": 1969,
"Greek_beta": 2018,
"Greek_chi": 2039,
"Greek_delta": 2020,
"Greek_epsilon": 2021,
"Greek_epsilonaccent": 1970,
"Greek_eta": 2023,
"Greek_etaaccent": 1971,
"Greek_finalsmallsigma": 2035,
"Greek_gamma": 2019,
"Greek_horizbar": 1967,
"Greek_iota": 2025,
"Greek_iotaaccent": 1972,
"Greek_iotaaccentdieresis": 1974,
"Greek_iotadieresis": 1973,
"Greek_kappa": 2026,
"Greek_lambda": 2027,
"Greek_lamda": 2027,
"Greek_mu": 2028,
"Greek_nu": 2029,
"Greek_omega": 2041,
"Greek_omegaaccent": 1979,
"Greek_omicron": 2031,
"Greek_omicronaccent": 1975,
"Greek_phi": 2038,
"Greek_pi": 2032,
"Greek_psi": 2040,
"Greek_rho": 2033,
"Greek_sigma": 2034,
"Greek_switch": 65406,
"Greek_tau": 2036,
"Greek_theta": 2024,
"Greek_upsilon": 2037,
"Greek_upsilonaccent": 1976,
"Greek_upsilonaccentdieresis": 1978,
"Greek_upsilondieresis": 1977,
"Greek_xi": 2030,
"Greek_zeta": 2022,
"H": 72,
"Hangul": 65329,
"Hangul_A": 3775,
"Hangul_AE": 3776,
"Hangul_AraeA": 3830,
"Hangul_AraeAE": 3831,
"Hangul_Banja": 65337,
"Hangul_Cieuc": 3770,
"Hangul_Codeinput": 65335,
"Hangul_Dikeud": 3751,
"Hangul_E": 3780,
"Hangul_EO": 3779,
"Hangul_EU": 3793,
"Hangul_End": 65331,
"Hangul_Hanja": 65332,
"Hangul_Hieuh": 3774,
"Hangul_I": 3795,
"Hangul_Ieung": 3767,
"Hangul_J_Cieuc": 3818,
"Hangul_J_Dikeud": 3802,
"Hangul_J_Hieuh": 3822,
"Hangul_J_Ieung": 3816,
"Hangul_J_Jieuj": 3817,
"Hangul_J_Khieuq": 3819,
"Hangul_J_Kiyeog": 3796,
"Hangul_J_KiyeogSios": 3798,
"Hangul_J_KkogjiDalrinIeung": 3833,
"Hangul_J_Mieum": 3811,
"Hangul_J_Nieun": 3799,
"Hangul_J_NieunHieuh": 3801,
"Hangul_J_NieunJieuj": 3800,
"Hangul_J_PanSios": 3832,
"Hangul_J_Phieuf": 3821,
"Hangul_J_Pieub": 3812,
"Hangul_J_PieubSios": 3813,
"Hangul_J_Rieul": 3803,
"Hangul_J_RieulHieuh": 3810,
"Hangul_J_RieulKiyeog": 3804,
"Hangul_J_RieulMieum": 3805,
"Hangul_J_RieulPhieuf": 3809,
"Hangul_J_RieulPieub": 3806,
"Hangul_J_RieulSios": 3807,
"Hangul_J_RieulTieut": 3808,
"Hangul_J_Sios": 3814,
"Hangul_J_SsangKiyeog": 3797,
"Hangul_J_SsangSios": 3815,
"Hangul_J_Tieut": 3820,
"Hangul_J_YeorinHieuh": 3834,
"Hangul_Jamo": 65333,
"Hangul_Jeonja": 65336,
"Hangul_Jieuj": 3768,
"Hangul_Khieuq": 3771,
"Hangul_Kiyeog": 3745,
"Hangul_KiyeogSios": 3747,
"Hangul_KkogjiDalrinIeung": 3827,
"Hangul_Mieum": 3761,
"Hangul_MultipleCandidate": 65341,
"Hangul_Nieun": 3748,
"Hangul_NieunHieuh": 3750,
"Hangul_NieunJieuj": 3749,
"Hangul_O": 3783,
"Hangul_OE": 3786,
"Hangul_PanSios": 3826,
"Hangul_Phieuf": 3773,
"Hangul_Pieub": 3762,
"Hangul_PieubSios": 3764,
"Hangul_PostHanja": 65339,
"Hangul_PreHanja": 65338,
"Hangul_PreviousCandidate": 65342,
"Hangul_Rieul": 3753,
"Hangul_RieulHieuh": 3760,
"Hangul_RieulKiyeog": 3754,
"Hangul_RieulMieum": 3755,
"Hangul_RieulPhieuf": 3759,
"Hangul_RieulPieub": 3756,
"Hangul_RieulSios": 3757,
"Hangul_RieulTieut": 3758,
"Hangul_RieulYeorinHieuh": 3823,
"Hangul_Romaja": 65334,
"Hangul_SingleCandidate": 65340,
"Hangul_Sios": 3765,
"Hangul_Special": 65343,
"Hangul_SsangDikeud": 3752,
"Hangul_SsangJieuj": 3769,
"Hangul_SsangKiyeog": 3746,
"Hangul_SsangPieub": 3763,
"Hangul_SsangSios": 3766,
"Hangul_Start": 65330,
"Hangul_SunkyeongeumMieum": 3824,
"Hangul_SunkyeongeumPhieuf": 3828,
"Hangul_SunkyeongeumPieub": 3825,
"Hangul_Tieut": 3772,
"Hangul_U": 3788,
"Hangul_WA": 3784,
"Hangul_WAE": 3785,
"Hangul_WE": 3790,
"Hangul_WEO": 3789,
"Hangul_WI": 3791,
"Hangul_YA": 3777,
"Hangul_YAE": 3778,
"Hangul_YE": 3782,
"Hangul_YEO": 3781,
"Hangul_YI": 3794,
"Hangul_YO": 3787,
"Hangul_YU": 3792,
"Hangul_YeorinHieuh": 3829,
"Hangul_switch": 65406,
"Hankaku": 65321,
"Hcircumflex": 678,
"Hebrew_switch": 65406,
"Help": 65386,
"Henkan": 65315,
"Henkan_Mode": 65315,
"Hiragana": 65317,
"Hiragana_Katakana": 65319,
"Home": 65360,
"Hstroke": 673,
"Hyper_L": 65517,
"Hyper_R": 65518,
"I": 73,
"ISO_Center_Object": 65075,
"ISO_Continuous_Underline": 65072,
"ISO_Discontinuous_Underline": 65073,
"ISO_Emphasize": 65074,
"ISO_Enter": 65076,
"ISO_Fast_Cursor_Down": 65071,
"ISO_Fast_Cursor_Left": 65068,
"ISO_Fast_Cursor_Right": 65069,
"ISO_Fast_Cursor_Up": 65070,
"ISO_First_Group": 65036,
"ISO_First_Group_Lock": 65037,
"ISO_Group_Latch": 65030,
"ISO_Group_Lock": 65031,
"ISO_Group_Shift": 65406,
"ISO_Last_Group": 65038,
"ISO_Last_Group_Lock": 65039,
"ISO_Left_Tab": 65056,
"ISO_Level2_Latch": 65026,
"ISO_Level3_Latch": 65028,
"ISO_Level3_Lock": 65029,
"ISO_Level3_Shift": 65027,
"ISO_Level5_Latch": 65042,
"ISO_Level5_Lock": 65043,
"ISO_Level5_Shift": 65041,
"ISO_Lock": 65025,
"ISO_Move_Line_Down": 65058,
"ISO_Move_Line_Up": 65057,
"ISO_Next_Group": 65032,
"ISO_Next_Group_Lock": 65033,
"ISO_Partial_Line_Down": 65060,
"ISO_Partial_Line_Up": 65059,
"ISO_Partial_Space_Left": 65061,
"ISO_Partial_Space_Right": 65062,
"ISO_Prev_Group": 65034,
"ISO_Prev_Group_Lock": 65035,
"ISO_Release_Both_Margins": 65067,
"ISO_Release_Margin_Left": 65065,
"ISO_Release_Margin_Right": 65066,
"ISO_Set_Margin_Left": 65063,
"ISO_Set_Margin_Right": 65064,
"Iabovedot": 681,
"Iacute": 205,
"Ibelowdot": 16785098,
"Ibreve": 16777516,
"Icircumflex": 206,
"Idiaeresis": 207,
"Igrave": 204,
"Ihook": 16785096,
"Imacron": 975,
"Insert": 65379,
"Iogonek": 967,
"Itilde": 933,
"J": 74,
"Jcircumflex": 684,
"K": 75,
"KP_0": 65456,
"KP_1": 65457,
"KP_2": 65458,
"KP_3": 65459,
"KP_4": 65460,
"KP_5": 65461,
"KP_6": 65462,
"KP_7": 65463,
"KP_8": 65464,
"KP_9": 65465,
"KP_Add": 65451,
"KP_Begin": 65437,
"KP_Decimal": 65454,
"KP_Delete": 65439,
"KP_Divide": 65455,
"KP_Down": 65433,
"KP_End": 65436,
"KP_Enter": 65421,
"KP_Equal": 65469,
"KP_F1": 65425,
"KP_F2": 65426,
"KP_F3": 65427,
"KP_F4": 65428,
"KP_Home": 65429,
"KP_Insert": 65438,
"KP_Left": 65430,
"KP_Multiply": 65450,
"KP_Next": 65435,
"KP_Page_Down": 65435,
"KP_Page_Up": 65434,
"KP_Prior": 65434,
"KP_Right": 65432,
"KP_Separator": 65452,
"KP_Space": 65408,
"KP_Subtract": 65453,
"KP_Tab": 65417,
"KP_Up": 65431,
"Kana_Lock": 65325,
"Kana_Shift": 65326,
"Kanji": 65313,
"Kanji_Bangou": 65335,
"Katakana": 65318,
"Kcedilla": 979,
"Korean_Won": 3839,
"L": 76,
"L1": 65480,
"L10": 65489,
"L2": 65481,
"L3": 65482,
"L4": 65483,
"L5": 65484,
"L6": 65485,
"L7": 65486,
"L8": 65487,
"L9": 65488,
"Lacute": 453,
"Last_Virtual_Screen": 65236,
"Lbelowdot": 16784950,
"Lcaron": 421,
"Lcedilla": 934,
"Left": 65361,
"Linefeed": 65290,
"LiraSign": 16785572,
"Lstroke": 419,
"M": 77,
"Mabovedot": 16784960,
"Macedonia_DSE": 1717,
"Macedonia_GJE": 1714,
"Macedonia_KJE": 1724,
"Macedonia_dse": 1701,
"Macedonia_gje": 1698,
"Macedonia_kje": 1708,
"Mae_Koho": 65342,
"Massyo": 65324,
"Menu": 65383,
"Meta_L": 65511,
"Meta_R": 65512,
"MillSign": 16785573,
"Mode_switch": 65406,
"MouseKeys_Accel_Enable": 65143,
"MouseKeys_Enable": 65142,
"Muhenkan": 65314,
"Multi_key": 65312,
"MultipleCandidate": 65341,
"N": 78,
"Nacute": 465,
"NairaSign": 16785574,
"Ncaron": 466,
"Ncedilla": 977,
"NewSheqelSign": 16785578,
"Next": 65366,
"Next_Virtual_Screen": 65234,
"Ntilde": 209,
"Num_Lock": 65407,
"O": 79,
"OE": 5052,
"Oacute": 211,
"Obarred": 16777631,
"Obelowdot": 16785100,
"Ocaron": 16777681,
"Ocircumflex": 212,
"Ocircumflexacute": 16785104,
"Ocircumflexbelowdot": 16785112,
"Ocircumflexgrave": 16785106,
"Ocircumflexhook": 16785108,
"Ocircumflextilde": 16785110,
"Odiaeresis": 214,
"Odoubleacute": 469,
"Ograve": 210,
"Ohook": 16785102,
"Ohorn": 16777632,
"Ohornacute": 16785114,
"Ohornbelowdot": 16785122,
"Ohorngrave": 16785116,
"Ohornhook": 16785118,
"Ohorntilde": 16785120,
"Omacron": 978,
"Ooblique": 216,
"Oslash": 216,
"Otilde": 213,
"Overlay1_Enable": 65144,
"Overlay2_Enable": 65145,
"P": 80,
"Pabovedot": 16784982,
"Page_Down": 65366,
"Page_Up": 65365,
"Pause": 65299,
"PesetaSign": 16785575,
"Pointer_Accelerate": 65274,
"Pointer_Button1": 65257,
"Pointer_Button2": 65258,
"Pointer_Button3": 65259,
"Pointer_Button4": 65260,
"Pointer_Button5": 65261,
"Pointer_Button_Dflt": 65256,
"Pointer_DblClick1": 65263,
"Pointer_DblClick2": 65264,
"Pointer_DblClick3": 65265,
"Pointer_DblClick4": 65266,
"Pointer_DblClick5": 65267,
"Pointer_DblClick_Dflt": 65262,
"Pointer_DfltBtnNext": 65275,
"Pointer_DfltBtnPrev": 65276,
"Pointer_Down": 65251,
"Pointer_DownLeft": 65254,
"Pointer_DownRight": 65255,
"Pointer_Drag1": 65269,
"Pointer_Drag2": 65270,
"Pointer_Drag3": 65271,
"Pointer_Drag4": 65272,
"Pointer_Drag5": 65277,
"Pointer_Drag_Dflt": 65268,
"Pointer_EnableKeys": 65273,
"Pointer_Left": 65248,
"Pointer_Right": 65249,
"Pointer_Up": 65250,
"Pointer_UpLeft": 65252,
"Pointer_UpRight": 65253,
"Prev_Virtual_Screen": 65233,
"PreviousCandidate": 65342,
"Print": 65377,
"Prior": 65365,
"Q": 81,
"R": 82,
"R1": 65490,
"R10": 65499,
"R11": 65500,
"R12": 65501,
"R13": 65502,
"R14": 65503,
"R15": 65504,
"R2": 65491,
"R3": 65492,
"R4": 65493,
"R5": 65494,
"R6": 65495,
"R7": 65496,
"R8": 65497,
"R9": 65498,
"Racute": 448,
"Rcaron": 472,
"Rcedilla": 931,
"Redo": 65382,
"RepeatKeys_Enable": 65138,
"Return": 65293,
"Right": 65363,
"Romaji": 65316,
"RupeeSign": 16785576,
"S": 83,
"SCHWA": 16777615,
"Sabovedot": 16784992,
"Sacute": 422,
"Scaron": 425,
"Scedilla": 426,
"Scircumflex": 734,
"Scroll_Lock": 65300,
"Select": 65376,
"Serbian_DJE": 1713,
"Serbian_DZE": 1727,
"Serbian_JE": 1720,
"Serbian_LJE": 1721,
"Serbian_NJE": 1722,
"Serbian_TSHE": 1723,
"Serbian_dje": 1697,
"Serbian_dze": 1711,
"Serbian_je": 1704,
"Serbian_lje": 1705,
"Serbian_nje": 1706,
"Serbian_tshe": 1707,
"Shift_L": 65505,
"Shift_Lock": 65510,
"Shift_R": 65506,
"SingleCandidate": 65340,
"Sinh_a": 16780677,
"Sinh_aa": 16780678,
"Sinh_aa2": 16780751,
"Sinh_ae": 16780679,
"Sinh_ae2": 16780752,
"Sinh_aee": 16780680,
"Sinh_aee2": 16780753,
"Sinh_ai": 16780691,
"Sinh_ai2": 16780763,
"Sinh_al": 16780746,
"Sinh_au": 16780694,
"Sinh_au2": 16780766,
"Sinh_ba": 16780726,
"Sinh_bha": 16780727,
"Sinh_ca": 16780704,
"Sinh_cha": 16780705,
"Sinh_dda": 16780713,
"Sinh_ddha": 16780714,
"Sinh_dha": 16780719,
"Sinh_dhha": 16780720,
"Sinh_e": 16780689,
"Sinh_e2": 16780761,
"Sinh_ee": 16780690,
"Sinh_ee2": 16780762,
"Sinh_fa": 16780742,
"Sinh_ga": 16780700,
"Sinh_gha": 16780701,
"Sinh_h2": 16780675,
"Sinh_ha": 16780740,
"Sinh_i": 16780681,
"Sinh_i2": 16780754,
"Sinh_ii": 16780682,
"Sinh_ii2": 16780755,
"Sinh_ja": 16780706,
"Sinh_jha": 16780707,
"Sinh_jnya": 16780709,
"Sinh_ka": 16780698,
"Sinh_kha": 16780699,
"Sinh_kunddaliya": 16780788,
"Sinh_la": 16780733,
"Sinh_lla": 16780741,
"Sinh_lu": 16780687,
"Sinh_lu2": 16780767,
"Sinh_luu": 16780688,
"Sinh_luu2": 16780787,
"Sinh_ma": 16780728,
"Sinh_mba": 16780729,
"Sinh_na": 16780721,
"Sinh_ndda": 16780716,
"Sinh_ndha": 16780723,
"Sinh_ng": 16780674,
"Sinh_ng2": 16780702,
"Sinh_nga": 16780703,
"Sinh_nja": 16780710,
"Sinh_nna": 16780715,
"Sinh_nya": 16780708,
"Sinh_o": 16780692,
"Sinh_o2": 16780764,
"Sinh_oo": 16780693,
"Sinh_oo2": 16780765,
"Sinh_pa": 16780724,
"Sinh_pha": 16780725,
"Sinh_ra": 16780731,
"Sinh_ri": 16780685,
"Sinh_rii": 16780686,
"Sinh_ru2": 16780760,
"Sinh_ruu2": 16780786,
"Sinh_sa": 16780739,
"Sinh_sha": 16780737,
"Sinh_ssha": 16780738,
"Sinh_tha": 16780717,
"Sinh_thha": 16780718,
"Sinh_tta": 16780711,
"Sinh_ttha": 16780712,
"Sinh_u": 16780683,
"Sinh_u2": 16780756,
"Sinh_uu": 16780684,
"Sinh_uu2": 16780758,
"Sinh_va": 16780736,
"Sinh_ya": 16780730,
"SlowKeys_Enable": 65139,
"StickyKeys_Enable": 65141,
"Super_L": 65515,
"Super_R": 65516,
"Sys_Req": 65301,
"T": 84,
"THORN": 222,
"Tab": 65289,
"Tabovedot": 16785002,
"Tcaron": 427,
"Tcedilla": 478,
"Terminate_Server": 65237,
"Thai_baht": 3551,
"Thai_bobaimai": 3514,
"Thai_chochan": 3496,
"Thai_chochang": 3498,
"Thai_choching": 3497,
"Thai_chochoe": 3500,
"Thai_dochada": 3502,
"Thai_dodek": 3508,
"Thai_fofa": 3517,
"Thai_fofan": 3519,
"Thai_hohip": 3531,
"Thai_honokhuk": 3534,
"Thai_khokhai": 3490,
"Thai_khokhon": 3493,
"Thai_khokhuat": 3491,
"Thai_khokhwai": 3492,
"Thai_khorakhang": 3494,
"Thai_kokai": 3489,
"Thai_lakkhangyao": 3557,
"Thai_lekchet": 3575,
"Thai_lekha": 3573,
"Thai_lekhok": 3574,
"Thai_lekkao": 3577,
"Thai_leknung": 3569,
"Thai_lekpaet": 3576,
"Thai_leksam": 3571,
"Thai_leksi": 3572,
"Thai_leksong": 3570,
"Thai_leksun": 3568,
"Thai_lochula": 3532,
"Thai_loling": 3525,
"Thai_lu": 3526,
"Thai_maichattawa": 3563,
"Thai_maiek": 3560,
"Thai_maihanakat": 3537,
"Thai_maihanakat_maitho": 3550,
"Thai_maitaikhu": 3559,
"Thai_maitho": 3561,
"Thai_maitri": 3562,
"Thai_maiyamok": 3558,
"Thai_moma": 3521,
"Thai_ngongu": 3495,
"Thai_nikhahit": 3565,
"Thai_nonen": 3507,
"Thai_nonu": 3513,
"Thai_oang": 3533,
"Thai_paiyannoi": 3535,
"Thai_phinthu": 3546,
"Thai_phophan": 3518,
"Thai_phophung": 3516,
"Thai_phosamphao": 3520,
"Thai_popla": 3515,
"Thai_rorua": 3523,
"Thai_ru": 3524,
"Thai_saraa": 3536,
"Thai_saraaa": 3538,
"Thai_saraae": 3553,
"Thai_saraaimaimalai": 3556,
"Thai_saraaimaimuan": 3555,
"Thai_saraam": 3539,
"Thai_sarae": 3552,
"Thai_sarai": 3540,
"Thai_saraii": 3541,
"Thai_sarao": 3554,
"Thai_sarau": 3544,
"Thai_saraue": 3542,
"Thai_sarauee": 3543,
"Thai_sarauu": 3545,
"Thai_sorusi": 3529,
"Thai_sosala": 3528,
"Thai_soso": 3499,
"Thai_sosua": 3530,
"Thai_thanthakhat": 3564,
"Thai_thonangmontho": 3505,
"Thai_thophuthao": 3506,
"Thai_thothahan": 3511,
"Thai_thothan": 3504,
"Thai_thothong": 3512,
"Thai_thothung": 3510,
"Thai_topatak": 3503,
"Thai_totao": 3509,
"Thai_wowaen": 3527,
"Thai_yoyak": 3522,
"Thai_yoying": 3501,
"Thorn": 222,
"Touroku": 65323,
"Tslash": 940,
"U": 85,
"Uacute": 218,
"Ubelowdot": 16785124,
"Ubreve": 733,
"Ucircumflex": 219,
"Udiaeresis": 220,
"Udoubleacute": 475,
"Ugrave": 217,
"Uhook": 16785126,
"Uhorn": 16777647,
"Uhornacute": 16785128,
"Uhornbelowdot": 16785136,
"Uhorngrave": 16785130,
"Uhornhook": 16785132,
"Uhorntilde": 16785134,
"Ukrainian_GHE_WITH_UPTURN": 1725,
"Ukrainian_I": 1718,
"Ukrainian_IE": 1716,
"Ukrainian_YI": 1719,
"Ukrainian_ghe_with_upturn": 1709,
"Ukrainian_i": 1702,
"Ukrainian_ie": 1700,
"Ukrainian_yi": 1703,
"Ukranian_I": 1718,
"Ukranian_JE": 1716,
"Ukranian_YI": 1719,
"Ukranian_i": 1702,
"Ukranian_je": 1700,
"Ukranian_yi": 1703,
"Umacron": 990,
"Undo": 65381,
"Uogonek": 985,
"Up": 65362,
"Uring": 473,
"Utilde": 989,
"V": 86,
"VoidSymbol": 16777215,
"W": 87,
"Wacute": 16785026,
"Wcircumflex": 16777588,
"Wdiaeresis": 16785028,
"Wgrave": 16785024,
"WonSign": 16785577,
"X": 88,
"XF86_AddFavorite": 269025081,
"XF86_ApplicationLeft": 269025104,
"XF86_ApplicationRight": 269025105,
"XF86_AudioCycleTrack": 269025179,
"XF86_AudioForward": 269025175,
"XF86_AudioLowerVolume": 269025041,
"XF86_AudioMedia": 269025074,
"XF86_AudioMicMute": 269025202,
"XF86_AudioMute": 269025042,
"XF86_AudioNext": 269025047,
"XF86_AudioPause": 269025073,
"XF86_AudioPlay": 269025044,
"XF86_AudioPreset": 269025206,
"XF86_AudioPrev": 269025046,
"XF86_AudioRaiseVolume": 269025043,
"XF86_AudioRandomPlay": 269025177,
"XF86_AudioRecord": 269025052,
"XF86_AudioRepeat": 269025176,
"XF86_AudioRewind": 269025086,
"XF86_AudioStop": 269025045,
"XF86_Away": 269025165,
"XF86_Back": 269025062,
"XF86_BackForward": 269025087,
"XF86_Battery": 269025171,
"XF86_Blue": 269025190,
"XF86_Bluetooth": 269025172,
"XF86_Book": 269025106,
"XF86_BrightnessAdjust": 269025083,
"XF86_CD": 269025107,
"XF86_Calculater": 269025108,
"XF86_Calculator": 269025053,
"XF86_Calendar": 269025056,
"XF86_Clear": 269025109,
"XF86_ClearGrab": 269024801,
"XF86_Close": 269025110,
"XF86_Community": 269025085,
"XF86_ContrastAdjust": 269025058,
"XF86_Copy": 269025111,
"XF86_Cut": 269025112,
"XF86_CycleAngle": 269025180,
"XF86_DOS": 269025114,
"XF86_Display": 269025113,
"XF86_Documents": 269025115,
"XF86_Eject": 269025068,
"XF86_Excel": 269025116,
"XF86_Explorer": 269025117,
"XF86_Favorites": 269025072,
"XF86_Finance": 269025084,
"XF86_Forward": 269025063,
"XF86_FrameBack": 269025181,
"XF86_FrameForward": 269025182,
"XF86_FullScreen": 269025208,
"XF86_Game": 269025118,
"XF86_Go": 269025119,
"XF86_Green": 269025188,
"XF86_Hibernate": 269025192,
"XF86_History": 269025079,
"XF86_HomePage": 269025048,
"XF86_HotLinks": 269025082,
"XF86_KbdBrightnessDown": 269025030,
"XF86_KbdBrightnessUp": 269025029,
"XF86_KbdLightOnOff": 269025028,
"XF86_Keyboard": 269025203,
"XF86_Launch0": 269025088,
"XF86_Launch1": 269025089,
"XF86_Launch2": 269025090,
"XF86_Launch3": 269025091,
"XF86_Launch4": 269025092,
"XF86_Launch5": 269025093,
"XF86_Launch6": 269025094,
"XF86_Launch7": 269025095,
"XF86_Launch8": 269025096,
"XF86_Launch9": 269025097,
"XF86_LaunchA": 269025098,
"XF86_LaunchB": 269025099,
"XF86_LaunchC": 269025100,
"XF86_LaunchD": 269025101,
"XF86_LaunchE": 269025102,
"XF86_LaunchF": 269025103,
"XF86_LightBulb": 269025077,
"XF86_LogGrabInfo": 269024805,
"XF86_LogOff": 269025121,
"XF86_LogWindowTree": 269024804,
"XF86_MacroRecordStart": 268964528,
"XF86_Mail": 269025049,
"XF86_MailForward": 269025168,
"XF86_Market": 269025122,
"XF86_Meeting": 269025123,
"XF86_Memo": 269025054,
"XF86_MenuKB": 269025125,
"XF86_MenuPB": 269025126,
"XF86_Messenger": 269025166,
"XF86_ModeLock": 269025025,
"XF86_MonBrightnessCycle": 269025031,
"XF86_MonBrightnessDown": 269025027,
"XF86_MonBrightnessUp": 269025026,
"XF86_Music": 269025170,
"XF86_MyComputer": 269025075,
"XF86_MySites": 269025127,
"XF86_New": 269025128,
"XF86_News": 269025129,
"XF86_Next_VMode": 269024802,
"XF86_OfficeHome": 269025130,
"XF86_Open": 269025131,
"XF86_OpenURL": 269025080,
"XF86_Option": 269025132,
"XF86_Paste": 269025133,
"XF86_Phone": 269025134,
"XF86_Pictures": 269025169,
"XF86_PowerDown": 269025057,
"XF86_PowerOff": 269025066,
"XF86_Prev_VMode": 269024803,
"XF86_Q": 269025136,
"XF86_RFKill": 269025205,
"XF86_Red": 269025187,
"XF86_Refresh": 269025065,
"XF86_Reload": 269025139,
"XF86_Reply": 269025138,
"XF86_RockerDown": 269025060,
"XF86_RockerEnter": 269025061,
"XF86_RockerUp": 269025059,
"XF86_RotateWindows": 269025140,
"XF86_RotationKB": 269025142,
"XF86_RotationLockToggle": 269025207,
"XF86_RotationPB": 269025141,
"XF86_Save": 269025143,
"XF86_ScreenSaver": 269025069,
"XF86_ScrollClick": 269025146,
"XF86_ScrollDown": 269025145,
"XF86_ScrollUp": 269025144,
"XF86_Search": 269025051,
"XF86_Select": 269025184,
"XF86_Send": 269025147,
"XF86_Shop": 269025078,
"XF86_Sleep": 269025071,
"XF86_Spell": 269025148,
"XF86_SplitScreen": 269025149,
"XF86_Standby": 269025040,
"XF86_Start": 269025050,
"XF86_Stop": 269025064,
"XF86_Subtitle": 269025178,
"XF86_Support": 269025150,
"XF86_Suspend": 269025191,
"XF86_Switch_VT_1": 269024769,
"XF86_Switch_VT_10": 269024778,
"XF86_Switch_VT_11": 269024779,
"XF86_Switch_VT_12": 269024780,
"XF86_Switch_VT_2": 269024770,
"XF86_Switch_VT_3": 269024771,
"XF86_Switch_VT_4": 269024772,
"XF86_Switch_VT_5": 269024773,
"XF86_Switch_VT_6": 269024774,
"XF86_Switch_VT_7": 269024775,
"XF86_Switch_VT_8": 269024776,
"XF86_Switch_VT_9": 269024777,
"XF86_TaskPane": 269025151,
"XF86_Terminal": 269025152,
"XF86_Time": 269025183,
"XF86_ToDoList": 269025055,
"XF86_Tools": 269025153,
"XF86_TopMenu": 269025186,
"XF86_TouchpadOff": 269025201,
"XF86_TouchpadOn": 269025200,
"XF86_TouchpadToggle": 269025193,
"XF86_Travel": 269025154,
"XF86_UWB": 269025174,
"XF86_Ungrab": 269024800,
"XF86_User1KB": 269025157,
"XF86_User2KB": 269025158,
"XF86_UserPB": 269025156,
"XF86_VendorHome": 269025076,
"XF86_Video": 269025159,
"XF86_View": 269025185,
"XF86_WLAN": 269025173,
"XF86_WWAN": 269025204,
"XF86_WWW": 269025070,
"XF86_WakeUp": 269025067,
"XF86_WebCam": 269025167,
"XF86_WheelButton": 269025160,
"XF86_Word": 269025161,
"XF86_Xfer": 269025162,
"XF86_Yellow": 269025189,
"XF86_ZoomIn": 269025163,
"XF86_ZoomOut": 269025164,
"XF86_iTouch": 269025120,
"Xabovedot": 16785034,
"Y": 89,
"Yacute": 221,
"Ybelowdot": 16785140,
"Ycircumflex": 16777590,
"Ydiaeresis": 5054,
"Ygrave": 16785138,
"Yhook": 16785142,
"Ytilde": 16785144,
"Z": 90,
"Zabovedot": 431,
"Zacute": 428,
"Zcaron": 430,
"Zen_Koho": 65341,
"Zenkaku": 65320,
"Zenkaku_Hankaku": 65322,
"Zstroke": 16777653,
"a": 97,
"aacute": 225,
"abelowdot": 16785057,
"abovedot": 511,
"abreve": 483,
"abreveacute": 16785071,
"abrevebelowdot": 16785079,
"abrevegrave": 16785073,
"abrevehook": 16785075,
"abrevetilde": 16785077,
"acircumflex": 226,
"acircumflexacute": 16785061,
"acircumflexbelowdot": 16785069,
"acircumflexgrave": 16785063,
"acircumflexhook": 16785065,
"acircumflextilde": 16785067,
"acute": 180,
"adiaeresis": 228,
"ae": 230,
"agrave": 224,
"ahook": 16785059,
"amacron": 992,
"ampersand": 38,
"aogonek": 433,
"apostrophe": 39,
"approxeq": 16785992,
"approximate": 2248,
"aring": 229,
"asciicircum": 94,
"asciitilde": 126,
"asterisk": 42,
"at": 64,
"atilde": 227,
"b": 98,
"babovedot": 16784899,
"backslash": 92,
"ballotcross": 2804,
"bar": 124,
"because": 16785973,
"blank": 2527,
"botintegral": 2213,
"botleftparens": 2220,
"botleftsqbracket": 2216,
"botleftsummation": 2226,
"botrightparens": 2222,
"botrightsqbracket": 2218,
"botrightsummation": 2230,
"bott": 2550,
"botvertsummationconnector": 2228,
"braceleft": 123,
"braceright": 125,
"bracketleft": 91,
"bracketright": 93,
"braille_blank": 16787456,
"braille_dot_1": 65521,
"braille_dot_10": 65530,
"braille_dot_2": 65522,
"braille_dot_3": 65523,
"braille_dot_4": 65524,
"braille_dot_5": 65525,
"braille_dot_6": 65526,
"braille_dot_7": 65527,
"braille_dot_8": 65528,
"braille_dot_9": 65529,
"braille_dots_1": 16787457,
"braille_dots_12": 16787459,
"braille_dots_123": 16787463,
"braille_dots_1234": 16787471,
"braille_dots_12345": 16787487,
"braille_dots_123456": 16787519,
"braille_dots_1234567": 16787583,
"braille_dots_12345678": 16787711,
"braille_dots_1234568": 16787647,
"braille_dots_123457": 16787551,
"braille_dots_1234578": 16787679,
"braille_dots_123458": 16787615,
"braille_dots_12346": 16787503,
"braille_dots_123467": 16787567,
"braille_dots_1234678": 16787695,
"braille_dots_123468": 16787631,
"braille_dots_12347": 16787535,
"braille_dots_123478": 16787663,
"braille_dots_12348": 16787599,
"braille_dots_1235": 16787479,
"braille_dots_12356": 16787511,
"braille_dots_123567": 16787575,
"braille_dots_1235678": 16787703,
"braille_dots_123568": 16787639,
"braille_dots_12357": 16787543,
"braille_dots_123578": 16787671,
"braille_dots_12358": 16787607,
"braille_dots_1236": 16787495,
"braille_dots_12367": 16787559,
"braille_dots_123678": 16787687,
"braille_dots_12368": 16787623,
"braille_dots_1237": 16787527,
"braille_dots_12378": 16787655,
"braille_dots_1238": 16787591,
"braille_dots_124": 16787467,
"braille_dots_1245": 16787483,
"braille_dots_12456": 16787515,
"braille_dots_124567": 16787579,
"braille_dots_1245678": 16787707,
"braille_dots_124568": 16787643,
"braille_dots_12457": 16787547,
"braille_dots_124578": 16787675,
"braille_dots_12458": 16787611,
"braille_dots_1246": 16787499,
"braille_dots_12467": 16787563,
"braille_dots_124678": 16787691,
"braille_dots_12468": 16787627,
"braille_dots_1247": 16787531,
"braille_dots_12478": 16787659,
"braille_dots_1248": 16787595,
"braille_dots_125": 16787475,
"braille_dots_1256": 16787507,
"braille_dots_12567": 16787571,
"braille_dots_125678": 16787699,
"braille_dots_12568": 16787635,
"braille_dots_1257": 16787539,
"braille_dots_12578": 16787667,
"braille_dots_1258": 16787603,
"braille_dots_126": 16787491,
"braille_dots_1267": 16787555,
"braille_dots_12678": 16787683,
"braille_dots_1268": 16787619,
"braille_dots_127": 16787523,
"braille_dots_1278": 16787651,
"braille_dots_128": 16787587,
"braille_dots_13": 16787461,
"braille_dots_134": 16787469,
"braille_dots_1345": 16787485,
"braille_dots_13456": 16787517,
"braille_dots_134567": 16787581,
"braille_dots_1345678": 16787709,
"braille_dots_134568": 16787645,
"braille_dots_13457": 16787549,
"braille_dots_134578": 16787677,
"braille_dots_13458": 16787613,
"braille_dots_1346": 16787501,
"braille_dots_13467": 16787565,
"braille_dots_134678": 16787693,
"braille_dots_13468": 16787629,
"braille_dots_1347": 16787533,
"braille_dots_13478": 16787661,
"braille_dots_1348": 16787597,
"braille_dots_135": 16787477,
"braille_dots_1356": 16787509,
"braille_dots_13567": 16787573,
"braille_dots_135678": 16787701,
"braille_dots_13568": 16787637,
"braille_dots_1357": 16787541,
"braille_dots_13578": 16787669,
"braille_dots_1358": 16787605,
"braille_dots_136": 16787493,
"braille_dots_1367": 16787557,
"braille_dots_13678": 16787685,
"braille_dots_1368": 16787621,
"braille_dots_137": 16787525,
"braille_dots_1378": 16787653,
"braille_dots_138": 16787589,
"braille_dots_14": 16787465,
"braille_dots_145": 16787481,
"braille_dots_1456": 16787513,
"braille_dots_14567": 16787577,
"braille_dots_145678": 16787705,
"braille_dots_14568": 16787641,
"braille_dots_1457": 16787545,
"braille_dots_14578": 16787673,
"braille_dots_1458": 16787609,
"braille_dots_146": 16787497,
"braille_dots_1467": 16787561,
"braille_dots_14678": 16787689,
"braille_dots_1468": 16787625,
"braille_dots_147": 16787529,
"braille_dots_1478": 16787657,
"braille_dots_148": 16787593,
"braille_dots_15": 16787473,
"braille_dots_156": 16787505,
"braille_dots_1567": 16787569,
"braille_dots_15678": 16787697,
"braille_dots_1568": 16787633,
"braille_dots_157": 16787537,
"braille_dots_1578": 16787665,
"braille_dots_158": 16787601,
"braille_dots_16": 16787489,
"braille_dots_167": 16787553,
"braille_dots_1678": 16787681,
"braille_dots_168": 16787617,
"braille_dots_17": 16787521,
"braille_dots_178": 16787649,
"braille_dots_18": 16787585,
"braille_dots_2": 16787458,
"braille_dots_23": 16787462,
"braille_dots_234": 16787470,
"braille_dots_2345": 16787486,
"braille_dots_23456": 16787518,
"braille_dots_234567": 16787582,
"braille_dots_2345678": 16787710,
"braille_dots_234568": 16787646,
"braille_dots_23457": 16787550,
"braille_dots_234578": 16787678,
"braille_dots_23458": 16787614,
"braille_dots_2346": 16787502,
"braille_dots_23467": 16787566,
"braille_dots_234678": 16787694,
"braille_dots_23468": 16787630,
"braille_dots_2347": 16787534,
"braille_dots_23478": 16787662,
"braille_dots_2348": 16787598,
"braille_dots_235": 16787478,
"braille_dots_2356": 16787510,
"braille_dots_23567": 16787574,
"braille_dots_235678": 16787702,
"braille_dots_23568": 16787638,
"braille_dots_2357": 16787542,
"braille_dots_23578": 16787670,
"braille_dots_2358": 16787606,
"braille_dots_236": 16787494,
"braille_dots_2367": 16787558,
"braille_dots_23678": 16787686,
"braille_dots_2368": 16787622,
"braille_dots_237": 16787526,
"braille_dots_2378": 16787654,
"braille_dots_238": 16787590,
"braille_dots_24": 16787466,
"braille_dots_245": 16787482,
"braille_dots_2456": 16787514,
"braille_dots_24567": 16787578,
"braille_dots_245678": 16787706,
"braille_dots_24568": 16787642,
"braille_dots_2457": 16787546,
"braille_dots_24578": 16787674,
"braille_dots_2458": 16787610,
"braille_dots_246": 16787498,
"braille_dots_2467": 16787562,
"braille_dots_24678": 16787690,
"braille_dots_2468": 16787626,
"braille_dots_247": 16787530,
"braille_dots_2478": 16787658,
"braille_dots_248": 16787594,
"braille_dots_25": 16787474,
"braille_dots_256": 16787506,
"braille_dots_2567": 16787570,
"braille_dots_25678": 16787698,
"braille_dots_2568": 16787634,
"braille_dots_257": 16787538,
"braille_dots_2578": 16787666,
"braille_dots_258": 16787602,
"braille_dots_26": 16787490,
"braille_dots_267": 16787554,
"braille_dots_2678": 16787682,
"braille_dots_268": 16787618,
"braille_dots_27": 16787522,
"braille_dots_278": 16787650,
"braille_dots_28": 16787586,
"braille_dots_3": 16787460,
"braille_dots_34": 16787468,
"braille_dots_345": 16787484,
"braille_dots_3456": 16787516,
"braille_dots_34567": 16787580,
"braille_dots_345678": 16787708,
"braille_dots_34568": 16787644,
"braille_dots_3457": 16787548,
"braille_dots_34578": 16787676,
"braille_dots_3458": 16787612,
"braille_dots_346": 16787500,
"braille_dots_3467": 16787564,
"braille_dots_34678": 16787692,
"braille_dots_3468": 16787628,
"braille_dots_347": 16787532,
"braille_dots_3478": 16787660,
"braille_dots_348": 16787596,
"braille_dots_35": 16787476,
"braille_dots_356": 16787508,
"braille_dots_3567": 16787572,
"braille_dots_35678": 16787700,
"braille_dots_3568": 16787636,
"braille_dots_357": 16787540,
"braille_dots_3578": 16787668,
"braille_dots_358": 16787604,
"braille_dots_36": 16787492,
"braille_dots_367": 16787556,
"braille_dots_3678": 16787684,
"braille_dots_368": 16787620,
"braille_dots_37": 16787524,
"braille_dots_378": 16787652,
"braille_dots_38": 16787588,
"braille_dots_4": 16787464,
"braille_dots_45": 16787480,
"braille_dots_456": 16787512,
"braille_dots_4567": 16787576,
"braille_dots_45678": 16787704,
"braille_dots_4568": 16787640,
"braille_dots_457": 16787544,
"braille_dots_4578": 16787672,
"braille_dots_458": 16787608,
"braille_dots_46": 16787496,
"braille_dots_467": 16787560,
"braille_dots_4678": 16787688,
"braille_dots_468": 16787624,
"braille_dots_47": 16787528,
"braille_dots_478": 16787656,
"braille_dots_48": 16787592,
"braille_dots_5": 16787472,
"braille_dots_56": 16787504,
"braille_dots_567": 16787568,
"braille_dots_5678": 16787696,
"braille_dots_568": 16787632,
"braille_dots_57": 16787536,
"braille_dots_578": 16787664,
"braille_dots_58": 16787600,
"braille_dots_6": 16787488,
"braille_dots_67": 16787552,
"braille_dots_678": 16787680,
"braille_dots_68": 16787616,
"braille_dots_7": 16787520,
"braille_dots_78": 16787648,
"braille_dots_8": 16787584,
"breve": 418,
"brokenbar": 166,
"c": 99,
"c_h": 65187,
"cabovedot": 741,
"cacute": 486,
"careof": 2744,
"caret": 2812,
"caron": 439,
"ccaron": 488,
"ccedilla": 231,
"ccircumflex": 742,
"cedilla": 184,
"cent": 162,
"ch": 65184,
"checkerboard": 2529,
"checkmark": 2803,
"circle": 3023,
"club": 2796,
"colon": 58,
"combining_acute": 16777985,
"combining_belowdot": 16778019,
"combining_grave": 16777984,
"combining_hook": 16777993,
"combining_tilde": 16777987,
"comma": 44,
"containsas": 16785931,
"copyright": 169,
"cr": 2532,
"crossinglines": 2542,
"cuberoot": 16785947,
"currency": 164,
"cursor": 2815,
"d": 100,
"dabovedot": 16784907,
"dagger": 2801,
"dcaron": 495,
"dead_A": 65153,
"dead_E": 65155,
"dead_I": 65157,
"dead_O": 65159,
"dead_SCHWA": 65163,
"dead_U": 65161,
"dead_a": 65152,
"dead_abovecomma": 65124,
"dead_abovedot": 65110,
"dead_abovereversedcomma": 65125,
"dead_abovering": 65112,
"dead_acute": 65105,
"dead_belowbreve": 65131,
"dead_belowcircumflex": 65129,
"dead_belowcomma": 65134,
"dead_belowdiaeresis": 65132,
"dead_belowdot": 65120,
"dead_belowmacron": 65128,
"dead_belowring": 65127,
"dead_belowtilde": 65130,
"dead_breve": 65109,
"dead_capital_schwa": 65163,
"dead_caron": 65114,
"dead_cedilla": 65115,
"dead_circumflex": 65106,
"dead_currency": 65135,
"dead_dasia": 65125,
"dead_diaeresis": 65111,
"dead_doubleacute": 65113,
"dead_doublegrave": 65126,
"dead_e": 65154,
"dead_grave": 65104,
"dead_greek": 65164,
"dead_hamza": 65165,
"dead_hook": 65121,
"dead_horn": 65122,
"dead_i": 65156,
"dead_invertedbreve": 65133,
"dead_iota": 65117,
"dead_macron": 65108,
"dead_o": 65158,
"dead_ogonek": 65116,
"dead_perispomeni": 65107,
"dead_psili": 65124,
"dead_schwa": 65162,
"dead_semivoiced_sound": 65119,
"dead_small_schwa": 65162,
"dead_stroke": 65123,
"dead_tilde": 65107,
"dead_u": 65160,
"dead_voiced_sound": 65118,
"decimalpoint": 2749,
"degree": 176,
"diaeresis": 168,
"diamond": 2797,
"digitspace": 2725,
"dintegral": 16785964,
"division": 247,
"dollar": 36,
"doubbaselinedot": 2735,
"doubleacute": 445,
"doubledagger": 2802,
"doublelowquotemark": 2814,
"downarrow": 2302,
"downcaret": 2984,
"downshoe": 3030,
"downstile": 3012,
"downtack": 3010,
"dstroke": 496,
"e": 101,
"eabovedot": 1004,
"eacute": 233,
"ebelowdot": 16785081,
"ecaron": 492,
"ecircumflex": 234,
"ecircumflexacute": 16785087,
"ecircumflexbelowdot": 16785095,
"ecircumflexgrave": 16785089,
"ecircumflexhook": 16785091,
"ecircumflextilde": 16785093,
"ediaeresis": 235,
"egrave": 232,
"ehook": 16785083,
"eightsubscript": 16785544,
"eightsuperior": 16785528,
"elementof": 16785928,
"ellipsis": 2734,
"em3space": 2723,
"em4space": 2724,
"emacron": 954,
"emdash": 2729,
"emfilledcircle": 2782,
"emfilledrect": 2783,
"emopencircle": 2766,
"emopenrectangle": 2767,
"emptyset": 16785925,
"emspace": 2721,
"endash": 2730,
"enfilledcircbullet": 2790,
"enfilledsqbullet": 2791,
"eng": 959,
"enopencircbullet": 2784,
"enopensquarebullet": 2785,
"enspace": 2722,
"eogonek": 490,
"equal": 61,
"eth": 240,
"etilde": 16785085,
"exclam": 33,
"exclamdown": 161,
"ezh": 16777874,
"f": 102,
"fabovedot": 16784927,
"femalesymbol": 2808,
"ff": 2531,
"figdash": 2747,
"filledlefttribullet": 2780,
"filledrectbullet": 2779,
"filledrighttribullet": 2781,
"filledtribulletdown": 2793,
"filledtribulletup": 2792,
"fiveeighths": 2757,
"fivesixths": 2743,
"fivesubscript": 16785541,
"fivesuperior": 16785525,
"fourfifths": 2741,
"foursubscript": 16785540,
"foursuperior": 16785524,
"fourthroot": 16785948,
"function": 2294,
"g": 103,
"gabovedot": 757,
"gbreve": 699,
"gcaron": 16777703,
"gcedilla": 955,
"gcircumflex": 760,
"grave": 96,
"greater": 62,
"greaterthanequal": 2238,
"guillemetleft": 171,
"guillemetright": 187,
"guillemotleft": 171,
"guillemotright": 187,
"h": 104,
"hairspace": 2728,
"hcircumflex": 694,
"heart": 2798,
"hebrew_aleph": 3296,
"hebrew_ayin": 3314,
"hebrew_bet": 3297,
"hebrew_beth": 3297,
"hebrew_chet": 3303,
"hebrew_dalet": 3299,
"hebrew_daleth": 3299,
"hebrew_doublelowline": 3295,
"hebrew_finalkaph": 3306,
"hebrew_finalmem": 3309,
"hebrew_finalnun": 3311,
"hebrew_finalpe": 3315,
"hebrew_finalzade": 3317,
"hebrew_finalzadi": 3317,
"hebrew_gimel": 3298,
"hebrew_gimmel": 3298,
"hebrew_he": 3300,
"hebrew_het": 3303,
"hebrew_kaph": 3307,
"hebrew_kuf": 3319,
"hebrew_lamed": 3308,
"hebrew_mem": 3310,
"hebrew_nun": 3312,
"hebrew_pe": 3316,
"hebrew_qoph": 3319,
"hebrew_resh": 3320,
"hebrew_samech": 3313,
"hebrew_samekh": 3313,
"hebrew_shin": 3321,
"hebrew_taf": 3322,
"hebrew_taw": 3322,
"hebrew_tet": 3304,
"hebrew_teth": 3304,
"hebrew_waw": 3301,
"hebrew_yod": 3305,
"hebrew_zade": 3318,
"hebrew_zadi": 3318,
"hebrew_zain": 3302,
"hebrew_zayin": 3302,
"hexagram": 2778,
"horizconnector": 2211,
"horizlinescan1": 2543,
"horizlinescan3": 2544,
"horizlinescan5": 2545,
"horizlinescan7": 2546,
"horizlinescan9": 2547,
"hstroke": 689,
"ht": 2530,
"hyphen": 173,
"i": 105,
"iacute": 237,
"ibelowdot": 16785099,
"ibreve": 16777517,
"icircumflex": 238,
"identical": 2255,
"idiaeresis": 239,
"idotless": 697,
"ifonlyif": 2253,
"igrave": 236,
"ihook": 16785097,
"imacron": 1007,
"implies": 2254,
"includedin": 2266,
"includes": 2267,
"infinity": 2242,
"integral": 2239,
"intersection": 2268,
"iogonek": 999,
"itilde": 949,
"j": 106,
"jcircumflex": 700,
"jot": 3018,
"k": 107,
"kana_A": 1201,
"kana_CHI": 1217,
"kana_E": 1204,
"kana_FU": 1228,
"kana_HA": 1226,
"kana_HE": 1229,
"kana_HI": 1227,
"kana_HO": 1230,
"kana_HU": 1228,
"kana_I": 1202,
"kana_KA": 1206,
"kana_KE": 1209,
"kana_KI": 1207,
"kana_KO": 1210,
"kana_KU": 1208,
"kana_MA": 1231,
"kana_ME": 1234,
"kana_MI": 1232,
"kana_MO": 1235,
"kana_MU": 1233,
"kana_N": 1245,
"kana_NA": 1221,
"kana_NE": 1224,
"kana_NI": 1222,
"kana_NO": 1225,
"kana_NU": 1223,
"kana_O": 1205,
"kana_RA": 1239,
"kana_RE": 1242,
"kana_RI": 1240,
"kana_RO": 1243,
"kana_RU": 1241,
"kana_SA": 1211,
"kana_SE": 1214,
"kana_SHI": 1212,
"kana_SO": 1215,
"kana_SU": 1213,
"kana_TA": 1216,
"kana_TE": 1219,
"kana_TI": 1217,
"kana_TO": 1220,
"kana_TSU": 1218,
"kana_TU": 1218,
"kana_U": 1203,
"kana_WA": 1244,
"kana_WO": 1190,
"kana_YA": 1236,
"kana_YO": 1238,
"kana_YU": 1237,
"kana_a": 1191,
"kana_closingbracket": 1187,
"kana_comma": 1188,
"kana_conjunctive": 1189,
"kana_e": 1194,
"kana_fullstop": 1185,
"kana_i": 1192,
"kana_middledot": 1189,
"kana_o": 1195,
"kana_openingbracket": 1186,
"kana_switch": 65406,
"kana_tsu": 1199,
"kana_tu": 1199,
"kana_u": 1193,
"kana_ya": 1196,
"kana_yo": 1198,
"kana_yu": 1197,
"kappa": 930,
"kcedilla": 1011,
"kra": 930,
"l": 108,
"lacute": 485,
"latincross": 2777,
"lbelowdot": 16784951,
"lcaron": 437,
"lcedilla": 950,
"leftanglebracket": 2748,
"leftarrow": 2299,
"leftcaret": 2979,
"leftdoublequotemark": 2770,
"leftmiddlecurlybrace": 2223,
"leftopentriangle": 2764,
"leftpointer": 2794,
"leftradical": 2209,
"leftshoe": 3034,
"leftsinglequotemark": 2768,
"leftt": 2548,
"lefttack": 3036,
"less": 60,
"lessthanequal": 2236,
"lf": 2533,
"logicaland": 2270,
"logicalor": 2271,
"lowleftcorner": 2541,
"lowrightcorner": 2538,
"lstroke": 435,
"m": 109,
"mabovedot": 16784961,
"macron": 175,
"malesymbol": 2807,
"maltesecross": 2800,
"marker": 2751,
"masculine": 186,
"minus": 45,
"minutes": 2774,
"mu": 181,
"multiply": 215,
"musicalflat": 2806,
"musicalsharp": 2805,
"n": 110,
"nabla": 2245,
"nacute": 497,
"ncaron": 498,
"ncedilla": 1009,
"ninesubscript": 16785545,
"ninesuperior": 16785529,
"nl": 2536,
"nobreakspace": 160,
"notapproxeq": 16785991,
"notelementof": 16785929,
"notequal": 2237,
"notidentical": 16786018,
"notsign": 172,
"ntilde": 241,
"numbersign": 35,
"numerosign": 1712,
"o": 111,
"oacute": 243,
"obarred": 16777845,
"obelowdot": 16785101,
"ocaron": 16777682,
"ocircumflex": 244,
"ocircumflexacute": 16785105,
"ocircumflexbelowdot": 16785113,
"ocircumflexgrave": 16785107,
"ocircumflexhook": 16785109,
"ocircumflextilde": 16785111,
"odiaeresis": 246,
"odoubleacute": 501,
"oe": 5053,
"ogonek": 434,
"ograve": 242,
"ohook": 16785103,
"ohorn": 16777633,
"ohornacute": 16785115,
"ohornbelowdot": 16785123,
"ohorngrave": 16785117,
"ohornhook": 16785119,
"ohorntilde": 16785121,
"omacron": 1010,
"oneeighth": 2755,
"onefifth": 2738,
"onehalf": 189,
"onequarter": 188,
"onesixth": 2742,
"onesubscript": 16785537,
"onesuperior": 185,
"onethird": 2736,
"ooblique": 248,
"openrectbullet": 2786,
"openstar": 2789,
"opentribulletdown": 2788,
"opentribulletup": 2787,
"ordfeminine": 170,
"ordmasculine": 186,
"oslash": 248,
"otilde": 245,
"overbar": 3008,
"overline": 1150,
"p": 112,
"pabovedot": 16784983,
"paragraph": 182,
"parenleft": 40,
"parenright": 41,
"partdifferential": 16785922,
"partialderivative": 2287,
"percent": 37,
"period": 46,
"periodcentered": 183,
"permille": 2773,
"phonographcopyright": 2811,
"plus": 43,
"plusminus": 177,
"prescription": 2772,
"prolongedsound": 1200,
"punctspace": 2726,
"q": 113,
"quad": 3020,
"question": 63,
"questiondown": 191,
"quotedbl": 34,
"quoteleft": 96,
"quoteright": 39,
"r": 114,
"racute": 480,
"radical": 2262,
"rcaron": 504,
"rcedilla": 947,
"registered": 174,
"rightanglebracket": 2750,
"rightarrow": 2301,
"rightcaret": 2982,
"rightdoublequotemark": 2771,
"rightmiddlecurlybrace": 2224,
"rightmiddlesummation": 2231,
"rightopentriangle": 2765,
"rightpointer": 2795,
"rightshoe": 3032,
"rightsinglequotemark": 2769,
"rightt": 2549,
"righttack": 3068,
"s": 115,
"sabovedot": 16784993,
"sacute": 438,
"scaron": 441,
"scedilla": 442,
"schwa": 16777817,
"scircumflex": 766,
"script_switch": 65406,
"seconds": 2775,
"section": 167,
"semicolon": 59,
"semivoicedsound": 1247,
"seveneighths": 2758,
"sevensubscript": 16785543,
"sevensuperior": 16785527,
"signaturemark": 2762,
"signifblank": 2732,
"similarequal": 2249,
"singlelowquotemark": 2813,
"sixsubscript": 16785542,
"sixsuperior": 16785526,
"slash": 47,
"soliddiamond": 2528,
"space": 32,
"squareroot": 16785946,
"ssharp": 223,
"sterling": 163,
"stricteq": 16786019,
"t": 116,
"tabovedot": 16785003,
"tcaron": 443,
"tcedilla": 510,
"telephone": 2809,
"telephonerecorder": 2810,
"therefore": 2240,
"thinspace": 2727,
"thorn": 254,
"threeeighths": 2756,
"threefifths": 2740,
"threequarters": 190,
"threesubscript": 16785539,
"threesuperior": 179,
"tintegral": 16785965,
"topintegral": 2212,
"topleftparens": 2219,
"topleftradical": 2210,
"topleftsqbracket": 2215,
"topleftsummation": 2225,
"toprightparens": 2221,
"toprightsqbracket": 2217,
"toprightsummation": 2229,
"topt": 2551,
"topvertsummationconnector": 2227,
"trademark": 2761,
"trademarkincircle": 2763,
"tslash": 956,
"twofifths": 2739,
"twosubscript": 16785538,
"twosuperior": 178,
"twothirds": 2737,
"u": 117,
"uacute": 250,
"ubelowdot": 16785125,
"ubreve": 765,
"ucircumflex": 251,
"udiaeresis": 252,
"udoubleacute": 507,
"ugrave": 249,
"uhook": 16785127,
"uhorn": 16777648,
"uhornacute": 16785129,
"uhornbelowdot": 16785137,
"uhorngrave": 16785131,
"uhornhook": 16785133,
"uhorntilde": 16785135,
"umacron": 1022,
"underbar": 3014,
"underscore": 95,
"union": 2269,
"uogonek": 1017,
"uparrow": 2300,
"upcaret": 2985,
"upleftcorner": 2540,
"uprightcorner": 2539,
"upshoe": 3011,
"upstile": 3027,
"uptack": 3022,
"uring": 505,
"utilde": 1021,
"v": 118,
"variation": 2241,
"vertbar": 2552,
"vertconnector": 2214,
"voicedsound": 1246,
"vt": 2537,
"w": 119,
"wacute": 16785027,
"wcircumflex": 16777589,
"wdiaeresis": 16785029,
"wgrave": 16785025,
"x": 120,
"xabovedot": 16785035,
"y": 121,
"yacute": 253,
"ybelowdot": 16785141,
"ycircumflex": 16777591,
"ydiaeresis": 255,
"yen": 165,
"ygrave": 16785139,
"yhook": 16785143,
"ytilde": 16785145,
"z": 122,
"zabovedot": 447,
"zacute": 444,
"zcaron": 446,
"zerosubscript": 16785536,
"zerosuperior": 16785520,
"zstroke": 16777654,
}
| 61,816 | Python | .py | 2,294 | 21.952049 | 41 | 0.620796 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,510 | __init__.py | pwr-Solaar_Solaar/lib/hid_parser/__init__.py | # SPDX-License-Identifier: MIT
from __future__ import annotations # noqa:F407
import functools
import struct
import sys
import textwrap
import typing
import warnings
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Literal
from typing import Optional
from typing import Sequence
from typing import TextIO
from typing import Tuple
from typing import Union
import hid_parser.data
__version__ = "0.0.3"
class HIDWarning(Warning):
pass
class HIDComplianceWarning(HIDWarning):
pass
class HIDReportWarning(HIDWarning):
pass
class HIDUnsupportedWarning(HIDWarning):
pass
class Type:
MAIN = 0
GLOBAL = 1
LOCAL = 2
class TagMain:
INPUT = 0b1000
OUTPUT = 0b1001
FEATURE = 0b1011
COLLECTION = 0b1010
END_COLLECTION = 0b1100
class TagGlobal:
USAGE_PAGE = 0b0000
LOGICAL_MINIMUM = 0b0001
LOGICAL_MAXIMUM = 0b0010
PHYSICAL_MINIMUM = 0b0011
PHYSICAL_MAXIMUM = 0b0100
UNIT_EXPONENT = 0b0101
UNIT = 0b0110
REPORT_SIZE = 0b0111
REPORT_ID = 0b1000
REPORT_COUNT = 0b1001
PUSH = 0b1010
POP = 0b1011
class TagLocal:
USAGE = 0b0000
USAGE_MINIMUM = 0b0001
USAGE_MAXIMUM = 0b0010
DESIGNATOR_INDEX = 0b0011
DESIGNATOR_MINIMUM = 0b0100
DESIGNATOR_MAXIMUM = 0b0101
STRING_INDEX = 0b0111
STRING_MINIMUM = 0b1000
STRING_MAXIMUM = 0b1001
DELIMITER = 0b1010
def _data_bit_shift(data: Sequence[int], offset: int, length: int) -> Sequence[int]:
if not length > 0:
raise ValueError(f"Invalid specified length: {length}")
left_extra = offset % 8
right_extra = 8 - (offset + length) % 8
start_offset = offset // 8
end_offset = (offset + length - 1) // 8
byte_length = (length - 1) // 8 + 1
if not end_offset < len(data):
raise ValueError(f"Invalid data length: {len(data)} (expecting {end_offset + 1})")
shifted = [0] * byte_length
if right_extra == 8:
right_extra = 0
i = end_offset
shifted_offset = byte_length - 1
while shifted_offset >= 0:
shifted[shifted_offset] = data[i] >> right_extra
if i - start_offset >= 0:
shifted[shifted_offset] |= (data[i - 1] & (0xFF >> (8 - right_extra))) << (8 - right_extra)
shifted_offset -= 1
i -= 1
shifted[0] &= 0xFF >> ((left_extra + right_extra) % 8)
if not len(shifted) == byte_length:
raise ValueError("Invalid data")
return shifted
class BitNumber(int):
def __init__(self, value: int):
self._value = value
def __int__(self) -> int:
return self._value
def __eq__(self, other: Any) -> bool:
try:
return self._value == int(other)
except: # noqa: E722
return False
@property
def byte(self) -> int:
"""
Number of bytes
"""
return self._value // 8
@property
def bit(self) -> int:
"""
Number of unaligned bits
n.byte * 8 + n.bits = n
"""
if self.byte == 0:
return self._value
return self._value % (self.byte * 8)
@staticmethod
def _param_repr(value: int, unit: str) -> str:
if value != 1:
unit += "s"
return f"{value}{unit}"
def __repr__(self) -> str:
byte_str = self._param_repr(self.byte, "byte")
bit_str = self._param_repr(self.bit, "bit")
if self.byte == 0 and self.bit == 0:
return bit_str
parts = []
if self.byte != 0:
parts.append(byte_str)
if self.bit != 0:
parts.append(bit_str)
return " ".join(parts)
class Usage:
def __init__(
self, page: Optional[int] = None, usage: Optional[int] = None, *, extended_usage: Optional[int] = None
) -> None:
if extended_usage and page and usage:
raise ValueError("You need to specify either the usage page and usage or the extended usage")
if extended_usage is not None:
self.page = extended_usage >> (2 * 8)
self.usage = extended_usage & 0xFFFF
elif page is not None and usage is not None:
self.page = page
self.usage = usage
else:
raise ValueError("No usage specified")
def __int__(self) -> int:
return self.page << (2 * 8) | self.usage
def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return False
return self.page == other.page and self.usage == other.usage
def __hash__(self) -> int:
return self.usage << (2 * 8) + self.page
def __repr__(self) -> str:
try:
page_str = hid_parser.data.UsagePages.get_description(self.page)
except KeyError:
page_str = f"0x{self.page:04x}"
usage_str = f"0x{self.usage:04x}"
else:
try:
page = hid_parser.data.UsagePages.get_subdata(self.page)
usage_str = page.get_description(self.usage)
except (KeyError, ValueError):
usage_str = f"0x{self.usage:04x}"
return f"Usage(page={page_str}, usage={usage_str})"
@property
def usage_types(self) -> Tuple[hid_parser.data.UsageTypes]:
subdata = hid_parser.data.UsagePages.get_subdata(self.page).get_subdata(self.usage)
if isinstance(subdata, tuple):
types = subdata
else:
types = (subdata,)
for typ in types:
if not isinstance(typ, hid_parser.data.UsageTypes):
raise ValueError(f"Expecting usage type but got '{type(typ)}'")
return typing.cast(Tuple[hid_parser.data.UsageTypes], types)
class UsageValue:
def __init__(self, item: MainItem, value: int):
self._item = item
self._value = value
def __int__(self) -> int:
return self.value
def __repr__(self) -> str:
return repr(self.value)
@property
def value(self) -> Union[int, bool]:
return self._value
@property
def constant(self) -> bool:
return self._item.constant
@property
def data(self) -> bool:
return self._item.data
@property
def relative(self) -> bool:
return self._item.relative
@property
def absolute(self) -> bool:
return self._item.absolute
class VendorUsageValue(UsageValue):
def __init__(
self,
item: MainItem,
*,
value: Optional[int] = None,
value_list: Optional[List[int]] = None,
):
self._item = item
if value:
self._list = [value]
elif value_list:
self._list = value_list
else:
self._list = []
def __int__(self) -> int:
return self.value
def __iter__(self) -> Iterator[int]:
return iter(self.list)
@property
def value(self) -> Union[int, bool]:
return int.from_bytes(self._list, byteorder="little")
@property
def list(self) -> List[int]:
return self._list
class BaseItem:
def __init__(self, offset: int, size: int):
self._offset = BitNumber(offset)
self._size = BitNumber(size)
@property
def offset(self) -> BitNumber:
return self._offset
@property
def size(self) -> BitNumber:
return self._size
def __repr__(self) -> str:
return f"{self.__class__.__name__}(offset={self.offset}, size={self.size})"
class PaddingItem(BaseItem):
pass
class MainItem(BaseItem):
def __init__(
self,
offset: int,
size: int,
flags: int,
logical_min: int,
logical_max: int,
physical_min: Optional[int] = None,
physical_max: Optional[int] = None,
):
super().__init__(offset, size)
self._flags = flags
self._logical_min = logical_min
self._logical_max = logical_max
self._physical_min = physical_min
self._physical_max = physical_max
# TODO: unit
@property
def offset(self) -> BitNumber:
return self._offset
@property
def size(self) -> BitNumber:
return self._size
@property
def logical_min(self) -> int:
return self._logical_min
@property
def logical_max(self) -> int:
return self._logical_max
@property
def physical_min(self) -> Optional[int]:
return self._physical_min
@property
def physical_max(self) -> Optional[int]:
return self._physical_max
# flags
@property
def constant(self) -> bool:
return self._flags & (1 << 0) != 0
@property
def data(self) -> bool:
return self._flags & (1 << 0) == 0
@property
def relative(self) -> bool:
return self._flags & (1 << 2) != 0
@property
def absolute(self) -> bool:
return self._flags & (1 << 2) == 0
class VariableItem(MainItem):
_INCOMPATIBLE_TYPES = (
# array types
hid_parser.data.UsageTypes.SELECTOR,
# collection types
hid_parser.data.UsageTypes.NAMED_ARRAY,
hid_parser.data.UsageTypes.COLLECTION_APPLICATION,
hid_parser.data.UsageTypes.COLLECTION_LOGICAL,
hid_parser.data.UsageTypes.COLLECTION_PHYSICAL,
hid_parser.data.UsageTypes.USAGE_SWITCH,
hid_parser.data.UsageTypes.USAGE_MODIFIER,
)
def __init__(
self,
offset: int,
size: int,
flags: int,
usage: Usage,
logical_min: int,
logical_max: int,
physical_min: Optional[int] = None,
physical_max: Optional[int] = None,
):
super().__init__(offset, size, flags, logical_min, logical_max, physical_min, physical_max)
self._usage = usage
try:
if all(usage_type in self._INCOMPATIBLE_TYPES for usage_type in usage.usage_types):
warnings.warn(HIDComplianceWarning(f"{usage} has no compatible usage types with a variable item")) # noqa
except (KeyError, ValueError):
pass
def __repr__(self) -> str:
return f"VariableItem(offset={self.offset}, size={self.size}, usage={self.usage})"
def parse(self, data: Sequence[int]) -> UsageValue:
data = _data_bit_shift(data, self.offset, self.size)
if hid_parser.data.UsageTypes.LINEAR_CONTROL in self.usage.usage_types or any(
usage_type in hid_parser.data.UsageTypesData and usage_type != hid_parser.data.UsageTypes.SELECTOR
for usage_type in self.usage.usage_types
): # int
value = int.from_bytes(data, byteorder="little")
elif (
hid_parser.data.UsageTypes.ON_OFF_CONTROL in self.usage.usage_types
and not self.preferred_state
and self.logical_min == -1
and self.logical_max == 1
): # bool - -1 is false
value = int.from_bytes(data, byteorder="little") == 1
else: # bool
value = bool.from_bytes(data, byteorder="little")
return UsageValue(self, value)
@property
def usage(self) -> Usage:
return self._usage
# flags (variable only, see HID spec 1.11 page 32)
@property
def wrap(self) -> bool:
return self._flags & (1 << 3) != 0
@property
def linear(self) -> bool:
return self._flags & (1 << 4) != 0
@property
def preferred_state(self) -> bool:
return self._flags & (1 << 5) != 0
@property
def null_state(self) -> bool:
return self._flags & (1 << 6) != 0
@property
def buffered_bytes(self) -> bool:
return self._flags & (1 << 7) != 0
@property
def bitfield(self) -> bool:
return self._flags & (1 << 7) == 0
class ArrayItem(MainItem):
_INCOMPATIBLE_TYPES = (
# variable types
hid_parser.data.UsageTypes.LINEAR_CONTROL,
hid_parser.data.UsageTypes.ON_OFF_CONTROL,
hid_parser.data.UsageTypes.MOMENTARY_CONTROL,
hid_parser.data.UsageTypes.ONE_SHOT_CONTROL,
hid_parser.data.UsageTypes.RE_TRIGGER_CONTROL,
hid_parser.data.UsageTypes.STATIC_VALUE,
hid_parser.data.UsageTypes.STATIC_FLAG,
hid_parser.data.UsageTypes.DYNAMIC_VALUE,
hid_parser.data.UsageTypes.DYNAMIC_FLAG,
# collection types
hid_parser.data.UsageTypes.NAMED_ARRAY,
hid_parser.data.UsageTypes.COLLECTION_APPLICATION,
hid_parser.data.UsageTypes.COLLECTION_LOGICAL,
hid_parser.data.UsageTypes.COLLECTION_PHYSICAL,
hid_parser.data.UsageTypes.USAGE_SWITCH,
hid_parser.data.UsageTypes.USAGE_MODIFIER,
)
_IGNORE_USAGE_VALUES = ((hid_parser.data.UsagePages.KEYBOARD_KEYPAD_PAGE, hid_parser.data.KeyboardKeypad.NO_EVENT),)
def __init__(
self,
offset: int,
size: int,
count: int,
flags: int,
usages: List[Usage],
logical_min: int,
logical_max: int,
physical_min: Optional[int] = None,
physical_max: Optional[int] = None,
):
super().__init__(offset, size, flags, logical_min, logical_max, physical_min, physical_max)
self._count = count
self._usages = usages
self._page = self._usages[0].page if usages else None
for usage in self._usages:
if usage.page != self._page:
raise ValueError(f"Mismatching usage page in usage: {usage} (expecting {self._usages[0]})")
try:
if all(usage_type in self._INCOMPATIBLE_TYPES for usage_type in usage.usage_types):
warnings.warn(HIDComplianceWarning(f"{usage} has no compatible usage types with an array item")) # noqa
except (KeyError, ValueError):
pass
self._ignore_usages: List[Usage] = []
for page, usage_id in self._IGNORE_USAGE_VALUES:
assert isinstance(page, int) and isinstance(usage_id, int)
self._ignore_usages.append(Usage(page, usage_id))
def __repr__(self) -> str:
return (
textwrap.dedent(
"""
ArrayItem(
offset={}, size={}, count={},
usages=[
{},
],
)
"""
)
.strip()
.format(
self.offset,
self.size,
self.count,
",\n ".join(repr(usage) for usage in self.usages),
)
)
def parse(self, data: Sequence[int]) -> Dict[Usage, UsageValue]:
usage_values: Dict[Usage, UsageValue] = {}
for i in range(self.count):
aligned_data = _data_bit_shift(data, self.offset + i * 8, self.size)
usage = Usage(self._page, int.from_bytes(aligned_data, byteorder="little"))
if usage in self._ignore_usages:
continue
# vendor usages don't have usage any standard type - just save the raw data
if usage.page in hid_parser.data.UsagePages.VENDOR_PAGE:
if usage not in usage_values:
usage_values[usage] = VendorUsageValue(
self,
value=int.from_bytes(aligned_data, byteorder="little"),
)
typing.cast(VendorUsageValue, usage_values[usage]).list.append(
int.from_bytes(aligned_data, byteorder="little")
)
continue
not_incompatible_type = all(usage_type not in self._INCOMPATIBLE_TYPES for usage_type in usage.usage_types)
if usage in self._usages and not_incompatible_type:
usage_values[usage] = UsageValue(self, True)
return usage_values
@property
def count(self) -> int:
return self._count
@property
def usages(self) -> List[Usage]:
return self._usages
class InvalidReportDescriptor(Exception):
pass
# report ID (None for no report ID), item list
_ITEM_POOL = Dict[Optional[int], List[BaseItem]]
class ReportDescriptor:
def __init__(self, data: Sequence[int]) -> None:
self._data = data
for byte in data:
if byte < 0 or byte > 255:
raise InvalidReportDescriptor(
f"A report descriptor should be represented by a list of bytes: found value {byte}"
)
self._input: _ITEM_POOL = {}
self._output: _ITEM_POOL = {}
self._feature: _ITEM_POOL = {}
self._parse()
@property
def data(self) -> Sequence[int]:
return self._data
@property
def input_report_ids(self) -> List[Optional[int]]:
return list(self._input.keys())
@property
def output_report_ids(self) -> List[Optional[int]]:
return list(self._output.keys())
@property
def feature_report_ids(self) -> List[Optional[int]]:
return list(self._feature.keys())
def _get_report_size(self, items: List[BaseItem]) -> BitNumber:
size = 0
for item in items:
if isinstance(item, ArrayItem):
size += item.size * item.count
else:
size += item.size
return BitNumber(size)
def get_input_items(self, report_id: Optional[int] = None) -> List[BaseItem]:
return self._input[report_id]
@functools.lru_cache(maxsize=16) # noqa
def get_input_report_size(self, report_id: Optional[int] = None) -> BitNumber:
return self._get_report_size(self.get_input_items(report_id))
def get_output_items(self, report_id: Optional[int] = None) -> List[BaseItem]:
return self._output[report_id]
@functools.lru_cache(maxsize=16) # noqa
def get_output_report_size(self, report_id: Optional[int] = None) -> BitNumber:
return self._get_report_size(self.get_output_items(report_id))
def get_feature_items(self, report_id: Optional[int] = None) -> List[BaseItem]:
return self._feature[report_id]
@functools.lru_cache(maxsize=16) # noqa
def get_feature_report_size(self, report_id: Optional[int] = None) -> BitNumber:
return self._get_report_size(self.get_feature_items(report_id))
def _parse_report_items(self, items: List[BaseItem], data: Sequence[int]) -> Dict[Usage, UsageValue]:
parsed: Dict[Usage, UsageValue] = {}
for item in items:
if isinstance(item, VariableItem):
parsed[item.usage] = item.parse(data)
elif isinstance(item, ArrayItem):
usage_values = item.parse(data)
for usage in usage_values:
if usage in parsed:
warnings.warn(HIDReportWarning(f"Overriding usage: {usage}")) # noqa
parsed.update(usage_values)
elif isinstance(item, PaddingItem):
pass
else:
raise TypeError(f"Unknown item: {item}")
return parsed
def _parse_report(self, item_poll: _ITEM_POOL, data: Sequence[int]) -> Dict[Usage, UsageValue]:
if None in item_poll: # unnumbered reports
return self._parse_report_items(item_poll[None], data)
else: # numbered reports
return self._parse_report_items(item_poll[data[0]], data[1:])
def parse_input_report(self, data: Sequence[int]) -> Dict[Usage, UsageValue]:
return self._parse_report(self._input, data)
def parse_output_report(self, data: Sequence[int]) -> Dict[Usage, UsageValue]:
return self._parse_report(self._output, data)
def parse_feature_report(self, data: Sequence[int]) -> Dict[Usage, UsageValue]:
return self._parse_report(self._feature, data)
def _iterate_raw(self) -> Iterable[Tuple[int, int, Optional[int]]]:
i = 0
while i < len(self.data):
prefix = self.data[i]
tag = (prefix & 0b11110000) >> 4
typ = (prefix & 0b00001100) >> 2
size = prefix & 0b00000011
if size == 3: # 6.2.2.2
size = 4
if size == 0:
data = None
elif size == 1:
if i + 1 >= len(self.data):
raise InvalidReportDescriptor(f"Invalid size: expecting >={i + 1}, got {len(self.data)}")
data = self.data[i + 1]
else:
if i + 1 + size >= len(self.data):
raise InvalidReportDescriptor(f"Invalid size: expecting >={i + 1 + size}, got {len(self.data)}")
if size == 2:
pack_type = "H"
elif size == 4:
pack_type = "L"
else:
raise ValueError(f"Invalid item size: {size}")
data = struct.unpack(f"<{pack_type}", bytes(self.data[i + 1 : i + 1 + size]))[0]
yield typ, tag, data
i += size + 1
def _append_item(
self,
offset_list: Dict[Optional[int], int],
pool: _ITEM_POOL,
report_id: Optional[int],
item: BaseItem,
) -> None:
offset_list[report_id] += item.size
if report_id in pool:
pool[report_id].append(item)
else:
pool[report_id] = [item]
def _append_items(
self,
offset_list: Dict[Optional[int], int],
pool: _ITEM_POOL,
report_id: Optional[int],
report_count: int,
report_size: int,
usages: List[Usage],
flags: int,
data: Dict[str, Any],
) -> None:
item: BaseItem
is_array = flags & (1 << 1) == 0 # otherwise variable
"""
HID 1.11, 6.2.2.9 says reports can be byte aligned by declaring a
main item without usage. A main item can have multiple usages, as I
interpret it, items are only considered padding when they have NO
usages.
"""
if len(usages) == 0 or not usages:
for _ in range(report_count):
item = PaddingItem(offset_list[report_id], report_size)
self._append_item(offset_list, pool, report_id, item)
return
if is_array:
item = ArrayItem(
offset=offset_list[report_id],
size=report_size,
usages=usages,
count=report_count,
flags=flags,
**data,
)
self._append_item(offset_list, pool, report_id, item)
else:
if len(usages) != report_count:
error_str = f"Expecting {report_count} usages but got {len(usages)}"
if len(usages) == 1:
warnings.warn(HIDComplianceWarning(error_str)) # noqa
usages *= report_count
else:
raise InvalidReportDescriptor(error_str)
for usage in usages:
item = VariableItem(
offset=offset_list[report_id],
size=report_size,
usage=usage,
flags=flags,
**data,
)
self._append_item(offset_list, pool, report_id, item)
def _parse(self, level: int = 0, file: TextIO = sys.stdout) -> None: # noqa: C901
offset_input: Dict[Optional[int], int] = {
None: 0,
}
offset_output: Dict[Optional[int], int] = {
None: 0,
}
offset_feature: Dict[Optional[int], int] = {
None: 0,
}
report_id: Optional[int] = None
report_count: Optional[int] = None
report_size: Optional[int] = None
usage_page: Optional[int] = None
usages: List[Usage] = []
usage_min: Optional[int] = None
glob: Dict[str, Any] = {}
local: Dict[str, Any] = {}
for typ, tag, data in self._iterate_raw():
if typ == Type.MAIN:
if tag in (TagMain.COLLECTION, TagMain.END_COLLECTION):
usages = []
# we only care about input, output and features for now
if tag not in (TagMain.INPUT, TagMain.OUTPUT, TagMain.FEATURE):
continue
if report_count is None:
raise InvalidReportDescriptor("Trying to append an item but no report count given")
if report_size is None:
raise InvalidReportDescriptor("Trying to append an item but no report size given")
if tag == TagMain.INPUT:
if data is None:
raise InvalidReportDescriptor("Invalid input item")
self._append_items(
offset_input, self._input, report_id, report_count, report_size, usages, data, {**glob, **local}
)
elif tag == TagMain.OUTPUT:
if data is None:
raise InvalidReportDescriptor("Invalid output item")
self._append_items(
offset_output,
self._output,
report_id,
report_count,
report_size,
usages,
data,
{**glob, **local},
)
elif tag == TagMain.FEATURE:
if data is None:
raise InvalidReportDescriptor("Invalid feature item")
self._append_items(
offset_feature,
self._feature,
report_id,
report_count,
report_size,
usages,
data,
{**glob, **local},
)
# clear local
usages = []
usage_min = None
local = {}
# we don't care about collections for now, maybe in the future...
elif typ == Type.GLOBAL:
if tag == TagGlobal.USAGE_PAGE:
usage_page = data
elif tag == TagGlobal.LOGICAL_MINIMUM:
glob["logical_min"] = data
elif tag == TagGlobal.LOGICAL_MAXIMUM:
glob["logical_max"] = data
elif tag == TagGlobal.PHYSICAL_MINIMUM:
glob["physical_min"] = data
elif tag == TagGlobal.PHYSICAL_MAXIMUM:
glob["physical_max"] = data
elif tag == TagGlobal.REPORT_SIZE:
report_size = data
elif tag == TagGlobal.REPORT_ID:
if not report_id and (self._input or self._output or self._feature):
raise InvalidReportDescriptor("Tried to set a report ID in a report that does not use them")
report_id = data
# initialize the item offset for this report ID
for offset_list in (offset_input, offset_output, offset_feature):
if report_id not in offset_list:
offset_list[report_id] = 0
elif tag in (TagGlobal.UNIT, TagGlobal.UNIT_EXPONENT):
warnings.warn( # noqa
HIDUnsupportedWarning("Data specifies a unit or unit exponent, but we don't support those yet")
)
elif tag in (TagGlobal.PUSH, TagGlobal.POP):
warnings.warn(HIDUnsupportedWarning("Push and pop are not supported yet")) # noqa
elif tag == TagGlobal.REPORT_COUNT:
report_count = data
else:
raise NotImplementedError(f"Unsupported global tag: {bin(tag)}")
elif typ == Type.LOCAL:
if tag == TagLocal.USAGE:
if usage_page is None:
raise InvalidReportDescriptor("Usage field found but no usage page")
usages.append(Usage(usage_page, data))
elif tag == TagLocal.USAGE_MINIMUM:
usage_min = data
elif tag == TagLocal.USAGE_MAXIMUM:
if usage_min is None:
raise InvalidReportDescriptor("Usage maximum set but no usage minimum")
if data is None:
raise InvalidReportDescriptor("Invalid usage maximum value")
for i in range(usage_min, data + 1):
usages.append(Usage(usage_page, i))
usage_min = None
elif tag in (TagLocal.STRING_INDEX, TagLocal.STRING_MINIMUM, TagLocal.STRING_MAXIMUM):
pass # we don't care about this information to parse the reports
else:
raise NotImplementedError(f"Unsupported local tag: {bin(tag)}")
@staticmethod
def _get_main_item_desc(value: int) -> str:
fields = [
"Constant" if value & (1 << 0) else "Data",
"Variable" if value & (1 << 1) else "Array",
"Relative" if value & (1 << 2) else "Absolute",
]
if value & (1 << 1):
# variable only
fields += [
"Wrap" if value & (1 << 3) else "No Wrap",
"Non Linear" if value & (1 << 4) else "Linear",
"No Preferred State" if value & (1 << 5) else "Preferred State",
"Null State" if value & (1 << 6) else "No Null position",
"Buffered Bytes" if value & (1 << 8) else "Bit Field",
]
return ", ".join(fields)
def print(self, level: int = 0, file: TextIO = sys.stdout) -> None: # noqa: C901
def printl(string: str) -> None:
print(" " * level + string, file=file)
usage_data: Union[Literal[False], Optional[hid_parser.data._Data]] = False
for typ, tag, data in self._iterate_raw():
if typ == Type.MAIN:
if tag == TagMain.INPUT:
if data is None:
raise InvalidReportDescriptor("Invalid input item")
printl(f"Input ({self._get_main_item_desc(data)})")
elif tag == TagMain.OUTPUT:
if data is None:
raise InvalidReportDescriptor("Invalid output item")
printl(f"Output ({self._get_main_item_desc(data)})")
elif tag == TagMain.FEATURE:
if data is None:
raise InvalidReportDescriptor("Invalid feature item")
printl(f"Feature ({self._get_main_item_desc(data)})")
elif tag == TagMain.COLLECTION:
printl(f"Collection ({hid_parser.data.Collections.get_description(data)})")
level += 1
elif tag == TagMain.END_COLLECTION:
level -= 1
printl("End Collection")
elif typ == Type.GLOBAL:
if tag == TagGlobal.USAGE_PAGE:
try:
printl(f"Usage Page ({hid_parser.data.UsagePages.get_description(data)})")
try:
usage_data = hid_parser.data.UsagePages.get_subdata(data)
except ValueError:
usage_data = None
except KeyError:
printl(f"Usage Page (Unknown 0x{data:04x})")
elif tag == TagGlobal.LOGICAL_MINIMUM:
printl(f"Logical Minimum ({data})")
elif tag == TagGlobal.LOGICAL_MAXIMUM:
printl(f"Logical Maximum ({data})")
elif tag == TagGlobal.PHYSICAL_MINIMUM:
printl(f"Physical Minimum ({data})")
elif tag == TagGlobal.PHYSICAL_MAXIMUM:
printl(f"Physical Maximum ({data})")
elif tag == TagGlobal.UNIT_EXPONENT:
printl(f"Unit Exponent (0x{data:04x})")
elif tag == TagGlobal.UNIT:
printl(f"Unit (0x{data:04x})")
elif tag == TagGlobal.REPORT_SIZE:
printl(f"Report Size ({data})")
elif tag == TagGlobal.REPORT_ID:
printl(f"Report ID (0x{data:02x})")
elif tag == TagGlobal.REPORT_COUNT:
printl(f"Report Count ({data})")
elif tag == TagGlobal.PUSH:
printl(f"Push ({data})")
elif tag == TagGlobal.POP:
printl(f"Pop ({data})")
elif typ == Type.LOCAL:
if tag == TagLocal.USAGE:
if usage_data is False:
raise InvalidReportDescriptor("Usage field found but no usage page")
if usage_data:
try:
printl(f"Usage ({usage_data.get_description(data)})")
except KeyError:
printl(f"Usage (Unknown, 0x{data:04x})")
else:
printl(f"Usage (0x{data:04x})")
elif tag == TagLocal.USAGE_MINIMUM:
printl(f"Usage Minimum ({data})")
elif tag == TagLocal.USAGE_MAXIMUM:
printl(f"Usage Maximum ({data})")
elif tag == TagLocal.DESIGNATOR_INDEX:
printl(f"Designator Index ({data})")
elif tag == TagLocal.DESIGNATOR_MINIMUM:
printl(f"Designator Minimum ({data})")
elif tag == TagLocal.DESIGNATOR_MAXIMUM:
printl(f"Designator Maximum ({data})")
elif tag == TagLocal.STRING_INDEX:
printl(f"String Index ({data})")
elif tag == TagLocal.STRING_MINIMUM:
printl(f"String Minimum ({data})")
elif tag == TagLocal.STRING_MAXIMUM:
printl(f"String Maximum ({data})")
elif tag == TagLocal.DELIMITER:
printl(f"Delemiter ({data})")
| 34,400 | Python | .py | 840 | 29.190476 | 124 | 0.548729 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,511 | data.py | pwr-Solaar_Solaar/lib/hid_parser/data.py | # SPDX-License-Identifier: MIT
import enum
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
class _DataMeta(type):
"""
This metaclass populates _single and _range, following the structure described bellow
The class should declare data as follows
MY_DATA_VALUE = 0x01, 'Data description'
or, for ranges,
MY_DATA_RANGE = 0x02, ..., 0x06, 'Data range description'
_single and _range will then be populated with
MY_DATA_VALUE = 0x01
_single[0x01] = ('Data description', None)
MY_DATA_RANGE = range(0x02, 0x06+1)
_range.append(tuple(0x02, 0x06, ('Data range description', None)))
As you can see, for single data insertions, the variable will be kept with
the first value of the tuple. Both single and range data insertions will
register the data into the correspondent data holders.
You can also define subdata,
MY_DATA_VALUE = 0x01, 'Data description', OTHER_DATA_TYPE
MY_DATA_RANGE = 0x02, ..., 0x06, 'Data range description', YET_OTHER_DATA_TYPE
Which will result in
MY_DATA_VALUE = 0x01
_single[0x01] = ('Data description', OTHER_DATA_TYPE)
_range.append(tuple(0x02, 0x06, ('Data range description', YET_OTHER_DATA_TYPE)))
This metaclass also does some verification to prevent duplicated data.
"""
def __new__(mcs, name: str, bases: Tuple[Any], dic: Dict[str, Any]): # type: ignore # noqa: C901
dic["_single"] = {}
dic["_range"] = []
# allow constructing data via a data dictionary as opposed to directly in the object body
if "data" in dic:
data = dic.pop("data")
else:
data = dic
for attr in data:
if not attr.startswith("_") and isinstance(data[attr], tuple):
if len(data[attr]) == 2 or len(data[attr]) == 4: # missing sub data
data[attr] = data[attr] + (None,)
if len(data[attr]) == 3: # single
num, desc, sub = data[attr]
if not isinstance(num, int):
raise TypeError(f"First element of '{attr}' should be an int")
if not isinstance(desc, str):
raise TypeError(f"Second element of '{attr}' should be a string")
if num in dic["_single"]:
raise ValueError(f"Duplicated value in '{attr}' ({num})")
for nmin, nmax, _ in dic["_range"]:
if nmin <= num <= nmax:
raise ValueError(f"Duplicated value in '{attr}' ({num})")
dic[attr] = num
dic["_single"][num] = desc, sub
elif len(data[attr]) == 5: # range
nmin, el, nmax, desc, sub = data[attr]
if not el == Ellipsis:
raise TypeError(f"Second element of '{attr}' should be an ellipsis (...)")
if not isinstance(nmin, int):
raise TypeError(f"First element of '{attr}' should be an int")
if not isinstance(nmax, int):
raise TypeError(f"Third element of '{attr}' should be an int")
if not isinstance(desc, str):
raise TypeError(f"Fourth element of '{attr}' should be a string")
for num in dic["_single"]:
if nmin <= num <= nmax:
raise ValueError(f"Duplicated value in '{attr}' ({num})")
dic[attr] = range(nmin, nmax + 1)
dic["_range"].append((nmin, nmax, (desc, sub)))
else:
raise ValueError(f"Invalid field: {attr}")
return super().__new__(mcs, name, bases, dic)
class _Data(metaclass=_DataMeta):
"""
This class provides a get_description method to get data out of _single and _range.
See the _DataMeta documentation for more information.
"""
_DATA = Tuple[str, Optional[Any]]
_single: Dict[int, _DATA]
_range: List[Tuple[int, int, _DATA]]
@classmethod
def _get_data(cls, num: Optional[int]) -> _DATA:
if num is None:
raise KeyError("Data index is not an int")
if num in cls._single:
return cls._single[num]
for nmin, nmax, data in cls._range:
if nmin <= num <= nmax:
return data
raise KeyError(f"Data not found for index 0x{num:02x} in {cls.__name__}")
@classmethod
def get_description(cls, num: Optional[int]) -> str:
return cls._get_data(num)[0]
@classmethod
def get_subdata(cls, num: Optional[int]) -> Any:
subdata = cls._get_data(num)[1]
if not subdata:
raise ValueError("Sub-data not available")
return subdata
class UsageTypes(enum.Enum):
# controls
LINEAR_CONTROL = LC = 0
ON_OFF_CONTROL = OOC = 1
MOMENTARY_CONTROL = MC = 2
ONE_SHOT_CONTROL = OSC = 3
RE_TRIGGER_CONTROL = RTC = 4
# data
SELECTOR = SEL = 5
STATIC_VALUE = SV = 6
STATIC_FLAG = SF = 7
DYNAMIC_FLAG = DF = 8
DYNAMIC_VALUE = DV = 9
# collection
NAMED_ARRAY = NARY = 10
COLLECTION_APPLICATION = CA = 11
COLLECTION_LOGICAL = CL = 12
COLLECTION_PHYSICAL = CP = 13
USAGE_SWITCH = US = 14
USAGE_MODIFIER = UM = 15
UsageTypesControls = (
UsageTypes.LINEAR_CONTROL,
UsageTypes.ON_OFF_CONTROL,
UsageTypes.ONE_SHOT_CONTROL,
UsageTypes.RE_TRIGGER_CONTROL,
)
UsageTypesData = (
UsageTypes.SELECTOR,
UsageTypes.STATIC_VALUE,
UsageTypes.STATIC_FLAG,
UsageTypes.DYNAMIC_VALUE,
UsageTypes.DYNAMIC_FLAG,
)
UsageTypesCollection = (
UsageTypes.NAMED_ARRAY,
UsageTypes.COLLECTION_APPLICATION,
UsageTypes.COLLECTION_LOGICAL,
UsageTypes.COLLECTION_PHYSICAL,
UsageTypes.USAGE_SWITCH,
UsageTypes.USAGE_MODIFIER,
)
class Collections(_Data):
PHYSICAL = 0x00, "Physical"
APPLICATION = 0x01, "Application"
LOGICAL = 0x02, "Logical"
REPORT = 0x03, "Report"
NAMED_ARRAY = 0x04, "Named Array"
USAGE_SWITCH = 0x05, "Usage Switch"
USAGE_MODIFIER = 0x06, "Usage Modifier"
VENDOR = 0x80, ..., 0xFF, "Vendor"
class GenericDesktopControls(_Data):
POINTER = 0x01, "Pointer", UsageTypes.CP
MOUSE = 0x02, "Mouse", UsageTypes.CA
JOYSTICK = 0x04, "Joystick", UsageTypes.CA
GAMEPAD = 0x05, "Game Pad", UsageTypes.CA
KEYBOARD = 0x06, "Keyboard", UsageTypes.CA
KEYPAD = 0x07, "Keypad", UsageTypes.CA
MULTI_AXIS_CONTROLLER = 0x08, "Multi-axis Controller", UsageTypes.CA
TABLET_PC_SYSTEM_CONTROLS = 0x09, "Tablet PC System Controls", UsageTypes.CA
X = 0x30, "X", UsageTypes.DV
Y = 0x31, "Y", UsageTypes.DV
Z = 0x32, "Z", UsageTypes.DV
RX = 0x33, "Rx", UsageTypes.DV
RY = 0x34, "Ry", UsageTypes.DV
RX = 0x35, "Rz", UsageTypes.DV
SLIDER = 0x36, "Slider", UsageTypes.DV
DIAL = 0x37, "Dial", UsageTypes.DV
WHEEL = 0x38, "Wheel", UsageTypes.DV
HAT_SWITCH = 0x39, "Hat switch", UsageTypes.DV
COUNTED_BUFFER = 0x3A, "Counted Buffer", UsageTypes.CL
BYTE_COUNT = 0x3B, "Byte Count", UsageTypes.DV
MOTION_WAKEUP = 0x3C, "Motion Wakeup", UsageTypes.OSC
START = 0x3D, "Start", UsageTypes.OOC
SELECT = 0x3E, "Select", UsageTypes.OOC
VX = 0x40, "Vx", UsageTypes.DV
VY = 0x41, "Vy", UsageTypes.DV
VZ = 0x42, "Vz", UsageTypes.DV
VBRX = 0x43, "Vbrx", UsageTypes.DV
VBRY = 0x44, "Vbry", UsageTypes.DV
VBRZ = 0x45, "Vbrz", UsageTypes.DV
VNO = 0x46, "Vno", UsageTypes.DV
FEATURE_NOTIFICATION = 0x47, "Feature Notification", (UsageTypes.DV, UsageTypes.DF)
RESOLUTION_MULTIPLIER = 0x48, "Resolution Multiplier", UsageTypes.DV
SYSTEM_CONTROL = 0x80, "System Control", UsageTypes.CA
SYSTEM_POWER_CONTROL = 0x81, "System Power Down", UsageTypes.OSC
SYSTEM_SLEEP = 0x82, "System Sleep", UsageTypes.OSC
SYSTEM_WAKE_UP = 0x83, "System Wake Up", UsageTypes.OSC
SYSTEM_CONTEXT_MENU = 0x84, "System Context Menu", UsageTypes.OSC
SYSTEM_MAIN_MENU = 0x85, "System Main Menu", UsageTypes.OSC
SYSTEM_APP_MENU = 0x86, "System App Menu", UsageTypes.OSC
SYSTEM_MENU_HELP = 0x87, "System Menu Help", UsageTypes.OSC
SYSTEM_MENU_EXIT = 0x88, "System Menu Exit", UsageTypes.OSC
SYSTEM_MENU_SELECT = 0x89, "System Menu Select", UsageTypes.OSC
SYSTEM_MENU_RIGHT = 0x8A, "System Menu Right", UsageTypes.RTC
SYSTEM_MENU_LEFT = 0x8B, "System Menu Left", UsageTypes.RTC
SYSTEM_MENU_UP = 0x8C, "System Menu Up", UsageTypes.RTC
SYSTEM_MENU_DOWN = 0x8D, "System Menu Down", UsageTypes.RTC
SYSTEM_COLD_RESTART = 0x8E, "System Cold Restart", UsageTypes.OSC
SYSTEM_WARM_RESTART = 0x8F, "System Warm Restart", UsageTypes.OSC
DPAD_UP = 0x90, "D-pad Up", UsageTypes.OOC
DPAD_DOWN = 0x91, "D-pad Down", UsageTypes.OOC
DPAD_RIGHT = 0x92, "D-pad Right", UsageTypes.OOC
DPAD_LEFT = 0x93, "D-pad Left", UsageTypes.OOC
SYSTEM_DOCK = 0xA0, "System Dock", UsageTypes.OSC
SYSTEM_UNDOCK = 0xA1, "System Undock", UsageTypes.OSC
SYSTEM_SETUP = 0xA2, "System Setup", UsageTypes.OSC
SYSTEM_BREAK = 0xA3, "System Break", UsageTypes.OSC
SYSTEM_DEBBUGER_BREAK = 0xA4, "System Debugger Break", UsageTypes.OSC
APPLICATION_BREAK = 0xA5, "Application Break", UsageTypes.OSC
APPLICATION_DEBBUGER_BREAK = 0xA6, "Application Debugger Break", UsageTypes.OSC
SYSTEM_SPEAKER_MUTE = 0xA7, "System Speaker Mute", UsageTypes.OSC
SYSTEM_HIBERNATE = 0xA8, "System Hibernate", UsageTypes.OSC
SYSTEM_DISPLAY_INVERT = 0xB0, "System Display Invert", UsageTypes.OSC
SYSTEM_DISPLAY_INTERNAL = 0xB1, "System Display Internal", UsageTypes.OSC
SYSTEM_DISPLAY_EXTERNAL = 0xB2, "System Display External", UsageTypes.OSC
SYSTEM_DISPLAY_BOTH = 0xB3, "System Display Both", UsageTypes.OSC
SYSTEM_DISPLAY_DUAL = 0xB4, "System Display Dual", UsageTypes.OSC
SYSTEM_DISPLAY_TOGGLE = 0xB5, "System Display Toggle Int/Ext", UsageTypes.OSC
SYSTEM_DISPLAY_SWAP = 0xB6, "System Display Swap Primary/Secondary", UsageTypes.OSC
SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7, "System Display LCD Autoscale", UsageTypes.OSC
class KeyboardKeypad(_Data):
NO_EVENT = 0x00, "No event indicated", UsageTypes.SEL
KEYBOARD_ERROR_ROLL_OVER = 0x01, "Keyboard ErrorRollOver", UsageTypes.SEL
KEYBOARD_POST = 0x02, "Keyboard POSTFail", UsageTypes.SEL
KEYBOARD_ERROR_UNDEFINED = 0x03, "Keyboard ErrorUndefined", UsageTypes.SEL
KEYBOARD_A = 0x04, "Keyboard a and A", UsageTypes.SEL
KEYBOARD_B = 0x05, "Keyboard b and B", UsageTypes.SEL
KEYBOARD_C = 0x06, "Keyboard c and C", UsageTypes.SEL
KEYBOARD_D = 0x07, "Keyboard d and D", UsageTypes.SEL
KEYBOARD_E = 0x08, "Keyboard e and E", UsageTypes.SEL
KEYBOARD_F = 0x09, "Keyboard f and F", UsageTypes.SEL
KEYBOARD_G = 0x0A, "Keyboard g and G", UsageTypes.SEL
KEYBOARD_H = 0x0B, "Keyboard h and H", UsageTypes.SEL
KEYBOARD_I = 0x0C, "Keyboard i and I", UsageTypes.SEL
KEYBOARD_J = 0x0D, "Keyboard j and J", UsageTypes.SEL
KEYBOARD_K = 0x0E, "Keyboard k and K", UsageTypes.SEL
KEYBOARD_L = 0x0F, "Keyboard l and L", UsageTypes.SEL
KEYBOARD_M = 0x10, "Keyboard m and M", UsageTypes.SEL
KEYBOARD_N = 0x11, "Keyboard n and N", UsageTypes.SEL
KEYBOARD_O = 0x12, "Keyboard o and O", UsageTypes.SEL
KEYBOARD_P = 0x13, "Keyboard p and P", UsageTypes.SEL
KEYBOARD_Q = 0x14, "Keyboard q and Q", UsageTypes.SEL
KEYBOARD_R = 0x15, "Keyboard r and R", UsageTypes.SEL
KEYBOARD_S = 0x16, "Keyboard s and S", UsageTypes.SEL
KEYBOARD_T = 0x17, "Keyboard t and T", UsageTypes.SEL
KEYBOARD_U = 0x18, "Keyboard u and U", UsageTypes.SEL
KEYBOARD_V = 0x19, "Keyboard v and V", UsageTypes.SEL
KEYBOARD_W = 0x1A, "Keyboard w and W", UsageTypes.SEL
KEYBOARD_X = 0x1B, "Keyboard x and X", UsageTypes.SEL
KEYBOARD_Y = 0x1C, "Keyboard y and Y", UsageTypes.SEL
KEYBOARD_Z = 0x1D, "Keyboard z and Z", UsageTypes.SEL
KEYBOARD_1 = 0x1E, "Keyboard 1 and !", UsageTypes.SEL
KEYBOARD_2 = 0x1F, "Keyboard 2 and @", UsageTypes.SEL
KEYBOARD_3 = 0x20, "Keyboard 3 and #", UsageTypes.SEL
KEYBOARD_4 = 0x21, "Keyboard 4 and $", UsageTypes.SEL
KEYBOARD_5 = 0x22, "Keyboard 5 and %", UsageTypes.SEL
KEYBOARD_6 = 0x23, "Keyboard 6 and ^", UsageTypes.SEL
KEYBOARD_7 = 0x24, "Keyboard 7 and &", UsageTypes.SEL
KEYBOARD_8 = 0x25, "Keyboard 8 and *", UsageTypes.SEL
KEYBOARD_9 = 0x26, "Keyboard 9 and (", UsageTypes.SEL
KEYBOARD_0 = 0x27, "Keyboard 0 and )", UsageTypes.SEL
KEYBOARD_ENTER = 0x28, "Keyboard Return (ENTER)", UsageTypes.SEL
KEYBOARD_ESCAPE = 0x29, "Keyboard ESCAPE", UsageTypes.SEL
KEYBOARD_DELETE = 0x2A, "Keyboard DELETE (Backspace)", UsageTypes.SEL
KEYBOARD_TAB = 0x2B, "Keyboard Tab", UsageTypes.SEL
KEYBOARD_SPACEBAR = 0x2C, "Keyboard Spacebar", UsageTypes.SEL
KEYBOARD_MINUS = 0x2D, "Keyboard - and (underscore)", UsageTypes.SEL
KEYBOARD_PLUS = 0x2E, "Keyboard = and +", UsageTypes.SEL
KEYBOARD_LEFT_BRACKET = 0x2F, "Keyboard [ and {", UsageTypes.SEL
KEYBOARD_RIGHT_BRACKET = 0x30, "Keyboard ] and }", UsageTypes.SEL
KEYBOARD_BACKSLASH = 0x31, "Keyboard \\ and |", UsageTypes.SEL
KEYBOARD_CARDINAL = 0x32, "Keyboard Non-US # and ~", UsageTypes.SEL
KEYBOARD_SEMICOLON = 0x33, "Keyboard ; and :", UsageTypes.SEL
KEYBOARD_QUOTE = 0x34, "Keyboard ' and \"", UsageTypes.SEL
KEYBOARD_GRAVE = 0x35, "Keyboard Grave Accent and Tilde", UsageTypes.SEL
KEYBOARD_COMMA = 0x36, "Keyboard , and <", UsageTypes.SEL
KEYBOARD_DOT = 0x37, "Keyboard . and >", UsageTypes.SEL
KEYBOARD_SLASH = 0x38, "Keyboard / and ?", UsageTypes.SEL
KEYBOARD_CAPS_LOCK = 0x39, "Keyboard Caps Lock", UsageTypes.SEL
KEYBOARD_F1 = 0x3A, "Keyboard F1", UsageTypes.SEL
KEYBOARD_F2 = 0x3B, "Keyboard F2", UsageTypes.SEL
KEYBOARD_F3 = 0x3C, "Keyboard F3", UsageTypes.SEL
KEYBOARD_F4 = 0x3D, "Keyboard F4", UsageTypes.SEL
KEYBOARD_F5 = 0x3E, "Keyboard F5", UsageTypes.SEL
KEYBOARD_F6 = 0x3F, "Keyboard F6", UsageTypes.SEL
KEYBOARD_F7 = 0x40, "Keyboard F7", UsageTypes.SEL
KEYBOARD_F8 = 0x41, "Keyboard F8", UsageTypes.SEL
KEYBOARD_F9 = 0x42, "Keyboard F9", UsageTypes.SEL
KEYBOARD_F10 = 0x43, "Keyboard F10", UsageTypes.SEL
KEYBOARD_F11 = 0x44, "Keyboard F11", UsageTypes.SEL
KEYBOARD_F12 = 0x45, "Keyboard F12", UsageTypes.SEL
KEYBOARD_PRINTSCREEN = 0x46, "Keyboard PrintScreen", UsageTypes.SEL
KEYBOARD_SCROLL_LOCK = 0x47, "Keyboard Scroll Lock", UsageTypes.SEL
KEYBOARD_PAUSE = 0x48, "Keyboard Pause", UsageTypes.SEL
KEYBOARD_INSERT = 0x49, "Keyboard Insert", UsageTypes.SEL
KEYBOARD_HOME = 0x4A, "Keyboard Home", UsageTypes.SEL
KEYBOARD_PAGE_UP = 0x4B, "Keyboard PageUp", UsageTypes.SEL
KEYBOARD_DELETE_FORWARD = 0x4C, "Keyboard Delete Forward", UsageTypes.SEL
KEYBOARD_END = 0x4D, "Keyboard End", UsageTypes.SEL
KEYBOARD_PAGE_DOWN = 0x4E, "Keyboard PageDown", UsageTypes.SEL
KEYBOARD_RIGHT_ARROW = 0x4F, "Keyboard RightArrow", UsageTypes.SEL
KEYBOARD_LEFT_ARROW = 0x50, "Keyboard LeftArrow", UsageTypes.SEL
KEYBOARD_UP_ARROW = 0x51, "Keyboard DownArrow", UsageTypes.SEL
KEYBOARD_DOWN_ARROW = 0x52, "Keyboard UpArrow", UsageTypes.SEL
KEYBOARD_NUM_LOCK = 0x53, "Keypad Num Lock and Clear", UsageTypes.SEL
KEYPAD_SLASH = 0x54, "Keypad /", UsageTypes.SEL
KEYPAD_ASTERISK = 0x55, "Keypad *", UsageTypes.SEL
KEYPAD_MINUS = 0x56, "Keypad -", UsageTypes.SEL
KEYPAD_PLUS = 0x57, "Keypad +", UsageTypes.SEL
KEYPAD_ENTER = 0x58, "Keypad ENTER", UsageTypes.SEL
KEYPAD_1 = 0x59, "Keypad 1 and End", UsageTypes.SEL
KEYPAD_2 = 0x5A, "Keypad 2 and Down Arrow", UsageTypes.SEL
KEYPAD_3 = 0x5B, "Keypad 3 and PageDn", UsageTypes.SEL
KEYPAD_4 = 0x5C, "Keypad 4 and Left Arrow", UsageTypes.SEL
KEYPAD_5 = 0x5D, "Keypad 5", UsageTypes.SEL
KEYPAD_6 = 0x5E, "Keypad 6 and Right Arrow", UsageTypes.SEL
KEYPAD_7 = 0x5F, "Keypad 7 and Home", UsageTypes.SEL
KEYPAD_8 = 0x60, "Keypad 8 and Up Arrow", UsageTypes.SEL
KEYPAD_9 = 0x61, "Keypad 9 and PageUp", UsageTypes.SEL
KEYPAD_0 = 0x62, "Keypad 0 and Insert", UsageTypes.SEL
KEYPAD_DOT = 0x63, "Keypad . and Delete", UsageTypes.SEL
KEYPAD_BACKSLASH = 0x64, "Keyboard Non-US \\ and |", UsageTypes.SEL
KEYPAD_APPLICATION = 0x65, "Keyboard Application", UsageTypes.SEL
KEYPAD_POWER = 0x66, "Keyboard Power", UsageTypes.SEL
KEYPAD_EQUALS = 0x67, "Keypad =", UsageTypes.SEL
KEYBOARD_F13 = 0x68, "Keyboard F13", UsageTypes.SEL
KEYBOARD_F14 = 0x69, "Keyboard F14", UsageTypes.SEL
KEYBOARD_F15 = 0x6A, "Keyboard F15", UsageTypes.SEL
KEYBOARD_F16 = 0x6B, "Keyboard F16", UsageTypes.SEL
KEYBOARD_F17 = 0x6C, "Keyboard F17", UsageTypes.SEL
KEYBOARD_F18 = 0x6D, "Keyboard F18", UsageTypes.SEL
KEYBOARD_F19 = 0x6E, "Keyboard F19", UsageTypes.SEL
KEYBOARD_F20 = 0x6F, "Keyboard F20", UsageTypes.SEL
KEYBOARD_F21 = 0x70, "Keyboard F21", UsageTypes.SEL
KEYBOARD_F22 = 0x71, "Keyboard F22", UsageTypes.SEL
KEYBOARD_F23 = 0x72, "Keyboard F23", UsageTypes.SEL
KEYBOARD_F24 = 0x73, "Keyboard F24", UsageTypes.SEL
KEYBOARD_EXECUTE = 0x74, "Keyboard Execute", UsageTypes.SEL
KEYBOARD_HELP = 0x75, "Keyboard Help", UsageTypes.SEL
KEYBOARD_MENU = 0x76, "Keyboard Menu", UsageTypes.SEL
KEYBOARD_SELECT = 0x77, "Keyboard Select", UsageTypes.SEL
KEYBOARD_STOP = 0x78, "Keyboard Stop", UsageTypes.SEL
KEYBOARD_AGAIN = 0x79, "Keyboard Again", UsageTypes.SEL
KEYBOARD_UNDO = 0x7A, "Keyboard Undo", UsageTypes.SEL
KEYBOARD_CUT = 0x7B, "Keyboard Cut", UsageTypes.SEL
KEYBOARD_COPY = 0x7C, "Keyboard Copy", UsageTypes.SEL
KEYBOARD_PASTE = 0x7D, "Keyboard Paste", UsageTypes.SEL
KEYBOARD_FIND = 0x7E, "Keyboard Find", UsageTypes.SEL
KEYBOARD_MUTE = 0x7F, "Keyboard Mute", UsageTypes.SEL
KEYBOARD_VOLUME_UP = 0x80, "Keyboard Volume Up", UsageTypes.SEL
KEYBOARD_VOLUME_DOWN = 0x81, "Keyboard Volume Down", UsageTypes.SEL
KEYBOARD_LOCKING_CAPS_LOCK = 0x82, "Keyboard Locking Caps Lock", UsageTypes.SEL
KEYBOARD_LOCKING_NUM_LOCK = 0x83, "Keyboard Locking Num Lock", UsageTypes.SEL
KEYBOARD_LOCKING_SCROLL_LOCK = 0x84, "Keyboard Locking Scroll Lock", UsageTypes.SEL
KEYPAD_COMMA = 0x85, "Keypad Comma", UsageTypes.SEL
KEYPAD_EQUALS_SIGN = 0x86, "Keypad Equal Sign", UsageTypes.SEL
KEYBOARD_INTERNATIONAL1 = 0x87, "Keyboard International1", UsageTypes.SEL
KEYBOARD_INTERNATIONAL2 = 0x88, "Keyboard International2", UsageTypes.SEL
KEYBOARD_INTERNATIONAL3 = 0x89, "Keyboard International3", UsageTypes.SEL
KEYBOARD_INTERNATIONAL4 = 0x8A, "Keyboard International4", UsageTypes.SEL
KEYBOARD_INTERNATIONAL5 = 0x8B, "Keyboard International5", UsageTypes.SEL
KEYBOARD_INTERNATIONAL6 = 0x8C, "Keyboard International6", UsageTypes.SEL
KEYBOARD_INTERNATIONAL7 = 0x8D, "Keyboard International7", UsageTypes.SEL
KEYBOARD_INTERNATIONAL8 = 0x8E, "Keyboard International8", UsageTypes.SEL
KEYBOARD_INTERNATIONAL9 = 0x8F, "Keyboard International9", UsageTypes.SEL
KEYBOARD_LANG1 = 0x90, "Keyboard LANG1", UsageTypes.SEL
KEYBOARD_LANG2 = 0x91, "Keyboard LANG2", UsageTypes.SEL
KEYBOARD_LANG3 = 0x92, "Keyboard LANG3", UsageTypes.SEL
KEYBOARD_LANG4 = 0x93, "Keyboard LANG4", UsageTypes.SEL
KEYBOARD_LANG5 = 0x94, "Keyboard LANG5", UsageTypes.SEL
KEYBOARD_LANG6 = 0x95, "Keyboard LANG6", UsageTypes.SEL
KEYBOARD_LANG7 = 0x96, "Keyboard LANG7", UsageTypes.SEL
KEYBOARD_LANG8 = 0x97, "Keyboard LANG8", UsageTypes.SEL
KEYBOARD_LANG9 = 0x98, "Keyboard LANG9", UsageTypes.SEL
KEYBOARD_ALTERNATE_ERASE = 0x99, "Keyboard Alternate Erase", UsageTypes.SEL
KEYBOARD_SYSREQ_ATTENTION = 0x9A, "Keyboard SysReq/Attention", UsageTypes.SEL
KEYBOARD_CANCEL = 0x9B, "Keyboard Cancel", UsageTypes.SEL
KEYBOARD_CLEAR = 0x9C, "Keyboard Clear", UsageTypes.SEL
KEYBOARD_PRIOR = 0x9D, "Keyboard Prior", UsageTypes.SEL
KEYBOARD_RETURN = 0x9E, "Keyboard Return", UsageTypes.SEL
KEYBOARD_SEPARATOE = 0x9F, "Keyboard Separator", UsageTypes.SEL
KEYBOARD_OUT = 0xA0, "Keyboard Out", UsageTypes.SEL
KEYBOARD_OPER = 0xA1, "Keyboard Oper", UsageTypes.SEL
KEYBOARD_CLEAR_AGAIN = 0xA2, "Keyboard Clear/Again", UsageTypes.SEL
KEYBOARD_CRSEL_PROPS = 0xA3, "Keyboard CrSel/Props", UsageTypes.SEL
KEYBOARD_EXSELL = 0xA4, "Keyboard ExSel", UsageTypes.SEL
KEYPAD_ZERO_ZERO = 0xB0, "Keypad 00", UsageTypes.SEL
KEYPAD_ZERO_ZERO_ZERO = 0xB1, "Keypad 000", UsageTypes.SEL
THOUSANDS_SEPARATOR = 0xB2, "Thousands Separator", UsageTypes.SEL
DECIMAL_SEPARATOR = 0xB3, "Decimal Separator", UsageTypes.SEL
CURRENCY_UNIT = 0xB4, "Currency Unit", UsageTypes.SEL
CURRENCY_SUBUNIT = 0xB5, "Currency Sub-unit", UsageTypes.SEL
KEYPAD_LEFT_PARENTHESIS = 0xB6, "Keypad (", UsageTypes.SEL
KEYPAD_RIGHT_PARENTHESIS = 0xB7, "Keypad )", UsageTypes.SEL
KEYPAD_LEFT_CURLY_BRACKET = 0xB8, "Keypad {", UsageTypes.SEL
KEYPAD_RIGHT_CURLY_BRACKET = 0xB9, "Keypad }", UsageTypes.SEL
KEYPAD_TAB = 0xBA, "Keypad Tab", UsageTypes.SEL
KEYPAD_BACKSPACE = 0xBB, "Keypad Backspace", UsageTypes.SEL
KEYPAD_A = 0xBC, "Keypad A", UsageTypes.SEL
KEYPAD_B = 0xBD, "Keypad B", UsageTypes.SEL
KEYPAD_C = 0xBE, "Keypad C", UsageTypes.SEL
KEYPAD_D = 0xBF, "Keypad D", UsageTypes.SEL
KEYPAD_E = 0xC0, "Keypad E", UsageTypes.SEL
KEYPAD_F = 0xC1, "Keypad F", UsageTypes.SEL
KEYPAD_XOR = 0xC2, "Keypad XOR", UsageTypes.SEL
KEYPAD_AND = 0xC3, "Keypad ^", UsageTypes.SEL
KEYPAD_PERCENTAGE = 0xC4, "Keypad %", UsageTypes.SEL
KEYPAD_LESS_THAN = 0xC5, "Keypad <", UsageTypes.SEL
KEYPAD_MORE_THAN = 0xC6, "Keypad >", UsageTypes.SEL
KEYPAD_AMPERSAND = 0xC7, "Keypad &", UsageTypes.SEL
KEYPAD_2_AMPERSAND = 0xC8, "Keypad &&", UsageTypes.SEL
KEYPAD_VERTICAL_BAR = 0xC9, "Keypad |", UsageTypes.SEL
KEYPAD_2_VERTICAL_BAR = 0xCA, "Keypad ||", UsageTypes.SEL
KEYPAD_COLON = 0xCB, "Keypad :", UsageTypes.SEL
KEYPAD_CARDINAL = 0xCC, "Keypad #", UsageTypes.SEL
KEYPAD_SPACE = 0xCD, "Keypad Space", UsageTypes.SEL
KEYPAD_AT = 0xCE, "Keypad @", UsageTypes.SEL
KEYPAD_EXCLAMATION = 0xCF, "Keypad !", UsageTypes.SEL
KEYPAD_MEMORY_STORE = 0xD0, "Keypad Memory Store", UsageTypes.SEL
KEYPAD_MEMORY_RECALL = 0xD1, "Keypad Memory Recall", UsageTypes.SEL
KEYPAD_MEMORY_CLEAR = 0xD2, "Keypad Memory Clear", UsageTypes.SEL
KEYPAD_MEMORY_ADD = 0xD3, "Keypad Memory Add", UsageTypes.SEL
KEYPAD_MEMORY_SUBTRACT = 0xD4, "Keypad Memory Subtract", UsageTypes.SEL
KEYPAD_MEMORY_MULTIPLY = 0xD5, "Keypad Memory Multiply", UsageTypes.SEL
KEYPAD_MEMORY_DIVIDE = 0xD6, "Keypad Memory Divide", UsageTypes.SEL
KEYPAD_PLUS_MINUS = 0xD7, "Keypad +/-", UsageTypes.SEL
KEYPAD_CLEAR = 0xD8, "Keypad Clear", UsageTypes.SEL
KEYPAD_CLEAR_ENTRY = 0xD9, "Keypad Clear Entry", UsageTypes.SEL
KEYPAD_BINARY = 0xDA, "Keypad Binary", UsageTypes.SEL
KEYPAD_OCTAL = 0xDB, "Keypad Octal", UsageTypes.SEL
KEYPAD_DECIMAL = 0xDC, "Keypad Decimal", UsageTypes.SEL
KEYPAD_HEXADECIMAL = 0xDD, "Keypad Hexadecimal", UsageTypes.DV
KEYBOARD_LEFT_CONTROL = 0xE0, "Keyboard LeftControl", UsageTypes.DV
KEYBOARD_LEFT_SHIFT = 0xE1, "Keyboard LeftShift", UsageTypes.DV
KEYBOARD_LEFT_ALT = 0xE2, "Keyboard LeftAlt", UsageTypes.DV
KEYBOARD_LEFT_GUI = 0xE3, "Keyboard Left GUI", UsageTypes.DV
KEYBOARD_RIGHT_CONTROL = 0xE4, "Keyboard RightControl", UsageTypes.DV
KEYBOARD_RIGHT_SHIFT = 0xE5, "Keyboard RightShift", UsageTypes.DV
KEYBOARD_RIGHT_ALT = 0xE6, "Keyboard RightAlt", UsageTypes.DV
KEYBOARD_RIGHT_GUI = 0xE7, "Keyboard Right GUI", UsageTypes.DV
class Led(_Data):
NUM_LOCK = 0x01, "Num Lock", UsageTypes.OOC
CAPS_LOCK = 0x02, "Caps Lock", UsageTypes.OOC
SCROLL_LOCK = 0x03, "Scroll Lock", UsageTypes.OOC
COMPOSE = 0x04, "Compose", UsageTypes.OOC
KANA = 0x05, "Kana", UsageTypes.OOC
POWER = 0x06, "Power", UsageTypes.OOC
SHIFT = 0x07, "Shift", UsageTypes.OOC
DO_NOT_DISTURB = 0x08, "Do Not Disturb", UsageTypes.OOC
MUTE = 0x09, "Mute", UsageTypes.OOC
TONE_ENABLE = 0x0A, "Tone Enable", UsageTypes.OOC
HIGH_CUT_FILTER = 0x0B, "High Cut Filter", UsageTypes.OOC
LOW_CUT_FILTER = 0x0C, "Low Cut Filter", UsageTypes.OOC
EQUALIZER_ENABLE = 0x0D, "Equalizer Enable", UsageTypes.OOC
SOUND_FIELD_ON = 0x0E, "Sound Field On", UsageTypes.OOC
SURROUND_ON = 0x0F, "Surround On", UsageTypes.OOC
REPEAR = 0x10, "Repeat", UsageTypes.OOC
STEREO = 0x11, "Stereo", UsageTypes.OOC
SAMPLING_RATE_DETECT = 0x12, "Sampling Rate Detect", UsageTypes.OOC
SPINNING = 0x13, "Spinning", UsageTypes.OOC
CAV = 0x14, "CAV", UsageTypes.OOC
CLV = 0x15, "CLV", UsageTypes.OOC
RECORDING_FORMAT_DETECT = 0x16, "Recording Format Detect", UsageTypes.OOC
OFF_HOOK = 0x17, "Off-Hook", UsageTypes.OOC
RING = 0x18, "Ring", UsageTypes.OOC
MESSAGE_WAITING = 0x19, "Message Waiting", UsageTypes.OOC
DATA_MODE = 0x1A, "Data Mode", UsageTypes.OOC
BATTERY_OPERATION = 0x1B, "Battery Operation", UsageTypes.OOC
BATTERY_OK = 0x1C, "Battery OK", UsageTypes.OOC
BATTERY_LOW = 0x1D, "Battery Low", UsageTypes.OOC
SPEAKER = 0x1E, "Speaker", UsageTypes.OOC
HEAD_SET = 0x1F, "Head Set", UsageTypes.OOC
HOLD = 0x20, "Hold", UsageTypes.OOC
MICROPHONE = 0x21, "Microphone", UsageTypes.OOC
COVERAGE = 0x22, "Coverage", UsageTypes.OOC
NIGHT_MODE = 0x23, "Night Mode", UsageTypes.OOC
SEND_CALLS = 0x24, "Send Calls", UsageTypes.OOC
CALL_PICKUP = 0x25, "Call Pickup", UsageTypes.OOC
CONFERENCE = 0x26, "Conference", UsageTypes.OOC
STAND_BY = 0x27, "Stand-by", UsageTypes.OOC
CAMERA_ON = 0x28, "Camera On", UsageTypes.OOC
CAMERA_OFF = 0x29, "Camera Off", UsageTypes.OOC
ON_LINE = 0x2A, "On-Line", UsageTypes.OOC
OFF_LINE = 0x2B, "Off-Line", UsageTypes.OOC
BUSY = 0x2C, "Busy", UsageTypes.OOC
READY = 0x2D, "Ready", UsageTypes.OOC
PAPER_OUT = 0x2E, "Paper-Out", UsageTypes.OOC
PAPER_JAM = 0x2F, "Paper-Jam", UsageTypes.OOC
REMOTE = 0x30, "Remote", UsageTypes.OOC
FORWARD = 0x31, "Forward", UsageTypes.OOC
REVERSE = 0x32, "Reverse", UsageTypes.OOC
STOP = 0x33, "Stop", UsageTypes.OOC
REWIND = 0x34, "Rewind", UsageTypes.OOC
FAST_FORWARD = 0x35, "Fast Forward", UsageTypes.OOC
PLAY = 0x36, "Play", UsageTypes.OOC
PAUSE = 0x37, "Pause", UsageTypes.OOC
RECORD = 0x38, "Record", UsageTypes.OOC
ERROR = 0x39, "Error", UsageTypes.OOC
USAGE_SELECTED_INDICATOR = 0x3A, "Usage Selected Indicator", UsageTypes.US
USAGE_IN_USE_INDICATOR = 0x3B, "Usage In Use Indicator", UsageTypes.US
USAGE_MULTI_MODE_INDICATOR = 0x3C, "Usage Multi Mode Indicator", UsageTypes.UM
INDICATOR_ON = 0x3D, "Indicator On", UsageTypes.SEL
INDICATOR_FLASH = 0x3E, "Indicator Flash", UsageTypes.SEL
INDICATOR_SLOW_BLINK = 0x3F, "Indicator Slow Blink", UsageTypes.SEL
INDICATOR_FAST_BLINK = 0x40, "Indicator Fast Blink", UsageTypes.SEL
INDICATOR_OFF = 0x41, "Indicator Off", UsageTypes.SEL
FLASH_ON_TIME = 0x42, "Flash On Time", UsageTypes.DV
SLOW_BLINK_ON_TIME = 0x43, "Slow Blink On Time", UsageTypes.DV
SLOW_BLINK_OFF_TIME = 0x44, "Slow Blink Off Time", UsageTypes.DV
FAST_BLINK_ON_TIME = 0x45, "Fast Blink On Time", UsageTypes.DV
FAST_BLINK_OFF_TIME = 0x46, "Fast Blink Off Time", UsageTypes.DV
USAGE_INDICATOR_COLOR = 0x47, "Usage Indicator Color", UsageTypes.UM
INDICATOR_RED = 0x48, "Indicator Red", UsageTypes.SEL
INDICATOR_GREEN = 0x49, "Indicator Green", UsageTypes.SEL
INDICATOR_AMBER = 0x4A, "Indicator Amber", UsageTypes.SEL
GENERIC_INDICATOR = 0x4B, "Generic Indicator", UsageTypes.OOC
SYSTEM_SUSPEND = 0x4C, "System Suspend", UsageTypes.OOC
EXTERNAL_POWER_CONNECTED = 0x4D, "External Power Connected", UsageTypes.OOC
class Button(_Data):
_USAGE_TYPES = (
UsageTypes.SEL,
UsageTypes.OOC,
UsageTypes.MC,
UsageTypes.OSC,
)
data = {
"NO_BUTTON": (0x0000, "Button 1 (primary/trigger)", _USAGE_TYPES),
"BUTTON_1": (0x0001, "Button 1 (primary/trigger)", _USAGE_TYPES),
"BUTTON_2": (0x0002, "Button 2 (secondary)", _USAGE_TYPES),
"BUTTON_3": (0x0003, "Button 3 (tertiary)", _USAGE_TYPES),
}
for _i in range(0x0004, 0xFFFF):
data[f"BUTTON_{_i}"] = _i, f"Button {_i}", _USAGE_TYPES
class Consumer(_Data):
CONSUMER_CONTROL = 0x0001, "Consumer Control", UsageTypes.CA
NUMERIC_KEY_PAD = 0x0002, "Numeric Key Pad", UsageTypes.NARY
PROGRAMMABLE_BUTTONS = 0x0003, "Programmable Buttons", UsageTypes.NARY
MICROPHONE = 0x0004, "Microphone", UsageTypes.CA
HEADPHONE = 0x0005, "Headphone", UsageTypes.CA
GRAPHIC_EQUALIZER = 0x0006, "Graphic Equalizer", UsageTypes.CA
PLUS10 = 0x0020, "+10", UsageTypes.OSC
PULS100 = 0x0021, "+100", UsageTypes.OSC
AM_PM = 0x0022, "AM/PM", UsageTypes.OSC
POWER = 0x0030, "Power", UsageTypes.OOC
REST = 0x0031, "Reset", UsageTypes.OSC
SLEEP = 0x0032, "Sleep", UsageTypes.OSC
SLEEP_AFTER = 0x0033, "Sleep After", UsageTypes.OSC
SLEEP_MODE = 0x0034, "Sleep Mode", UsageTypes.RTC
ILLUMINATION = 0x0035, "Illumination", UsageTypes.OOC
FUNCTION_BUTTONS = 0x0036, "Function Buttons", UsageTypes.NARY
MENU = 0x0040, "Menu", UsageTypes.OOC
MENU_PICK = 0x0041, "Menu Pick", UsageTypes.OSC
MENU_UP = 0x0042, "Menu Up", UsageTypes.OSC
MENU_DOWN = 0x0043, "Menu Down", UsageTypes.OSC
MENU_LEFT = 0x0044, "Menu Left", UsageTypes.OSC
MENU_RIGHT = 0x0045, "Menu Right", UsageTypes.OSC
MENU_ESCAPE = 0x0046, "Menu Escape", UsageTypes.OSC
MENU_VALUE_INCREASE = 0x0047, "Menu Value Increase", UsageTypes.OSC
MENU_VALUE_DECREASE = 0x0048, "Menu Value Decrease", UsageTypes.OSC
DATA_ON_SCREEN = 0x0060, "Data On Screen", UsageTypes.OOC
CLOSED_CAPTION = 0x0061, "Closed Caption", UsageTypes.OOC
CLOSED_CAPTION_SELECT = 0x0062, "Closed Caption Select", UsageTypes.OOC
VCR_TV = 0x0063, "VCR/TV", UsageTypes.OSC
BROADCAST_MODE = 0x0064, "Broadcast Mode", UsageTypes.OOC
SNAPSHOT = 0x0065, "Snapshot", UsageTypes.OOC
STILL = 0x0066, "Still", UsageTypes.OOC
SELECTION = 0x0080, "Selection", UsageTypes.NARY
ASSIGN_SELECTION = 0x0081, "Assign Selection", UsageTypes.OSC
MODE_STEP = 0x0082, "Mode Step", UsageTypes.OSC
RECALL_LAST = 0x0083, "Recall Last", UsageTypes.OSC
ENTER_CHANNEL = 0x0084, "Enter Channel", UsageTypes.OSC
ORDER_MOVIE = 0x0085, "Order Movie", UsageTypes.OSC
CHANNEL = 0x0086, "Channel", UsageTypes.LC
MEDIA_SELECTION = 0x0087, "Media Selection", UsageTypes.NARY
MEDIA_SELECT_COMPUTER = 0x0088, "Media Select Computer", UsageTypes.SEL
MEDIA_SELECT_TV = 0x0089, "Media Select TV", UsageTypes.SEL
MEDIA_SELECT_WWW = 0x008A, "Media Select WWW", UsageTypes.SEL
MEDIA_SELECT_DVD = 0x008B, "Media Select DVD", UsageTypes.SEL
MEDIA_SELECT_TELEPHONE = 0x008C, "Media Select Telephone", UsageTypes.SEL
MEDIA_SELECT_PROGRAM_GUIDE = 0x008D, "Media Select Program Guide", UsageTypes.SEL
MEDIA_SELECT_VIDEO_PHONE = 0x008E, "Media Select Video Phone", UsageTypes.SEL
MEDIA_SELECT_GAMES = 0x008F, "Media Select Games", UsageTypes.SEL
MEDIA_SELECT_MESSAGES = 0x0090, "Media Select Messages", UsageTypes.SEL
MEDIA_SELECT_CD = 0x0091, "Media Select CD ", UsageTypes.SEL
MEDIA_SELECT_VCR = 0x0092, "Media Select VCR", UsageTypes.SEL
MEDIA_SELECT_TUNER = 0x0093, "Media Select Tuner", UsageTypes.SEL
QUIT = 0x0094, "Quit", UsageTypes.OSC
HELP = 0x0095, "Help", UsageTypes.OOC
MEDIA_SELECT_TAPE = 0x0096, "Media Select Tape", UsageTypes.SEL
MEDIA_SELECT_CABLE = 0x0097, "Media Select Cable", UsageTypes.SEL
MEDIA_SELECT_SATELLITE = 0x0098, "Media Select Satellite", UsageTypes.SEL
MEDIA_SELECT_SECURITY = 0x0099, "Media Select Security", UsageTypes.SEL
MEDIA_SELECT_HOME = 0x009A, "Media Select Home", UsageTypes.SEL
MEDIA_SELECT_CALL = 0x009B, "Media Select Call", UsageTypes.SEL
CHANNEL_INCREMENT = 0x009C, "Channel Increment", UsageTypes.OSC
CHANNEL_DECREMENT = 0x009D, "Channel Decrement", UsageTypes.OSC
MEDIA_SELECT_SAP = 0x009E, "Media Select SAP", UsageTypes.SEL
VCR_PLUS = 0x00A0, "VCR Plus", UsageTypes.OSC
ONCE = 0x00A1, "Once", UsageTypes.OSC
DAILY = 0x00A2, "Daily", UsageTypes.OSC
WEEKLY = 0x00A3, "Weekly", UsageTypes.OSC
MONTHLY = 0x00A4, "Monthly", UsageTypes.OSC
PLAY = 0x00B0, "Play", UsageTypes.OOC
PAUSE = 0x00B1, "Pause", UsageTypes.OOC
RECORD = 0x00B2, "Record", UsageTypes.OOC
FAST_FORWARD = 0x00B3, "Fast Forward", UsageTypes.OOC
REWIND = 0x00B4, "Rewind", UsageTypes.OOC
SCAN_NEXT_TRACK = 0x00B5, "Scan Next Track", UsageTypes.OSC
SCAN_PREVIOUS_TRACK = 0x00B6, "Scan Previous Track", UsageTypes.OSC
STOP = 0x00B7, "Stop", UsageTypes.OSC
EJECT = 0x00B8, "Eject", UsageTypes.OSC
RANDOM_PLAY = 0x00B9, "Random Play", UsageTypes.OOC
SELECT_DISC = 0x00BA, "Select Disc", UsageTypes.NARY
ENTER_DISC = 0x00BB, "Enter Disc", UsageTypes.MC
REPEAT = 0x00BC, "Repeat", UsageTypes.OSC
TRACKING = 0x00BD, "Tracking", UsageTypes.LC
TRACK_NORMAL = 0x00BE, "Track Normal", UsageTypes.OSC
SLOW_TRACKING = 0x00BF, "Slow Tracking", UsageTypes.LC
FRAME_FORWARD = 0x00C0, "Frame Forward", UsageTypes.RTC
FRAME_BACK = 0x00C1, "Frame Back", UsageTypes.RTC
MARK = 0x00C2, "Mark", UsageTypes.OSC
CLEAR_MARK = 0x00C3, "Clear Mark", UsageTypes.OSC
REPEAT_FROM_MARK = 0x00C4, "Repeat From Mark", UsageTypes.OOC
RETURN_TO_MARK = 0x00C5, "Return To Mark", UsageTypes.OSC
SEARCH_MARK_FORWARD = 0x00C6, "Search Mark Forward", UsageTypes.OSC
SEARCH_MARK_BACKWARDS = 0x00C7, "Search Mark Backwards", UsageTypes.OSC
COUNTER_RESET = 0x00C8, "Counter Reset", UsageTypes.OSC
SHOW_COUNTER = 0x00C9, "Show Counter", UsageTypes.OSC
TRACKING_INCREMENT = 0x00CA, "Tracking Increment", UsageTypes.RTC
TRACKING_DECREMENT = 0x00CB, "Tracking Decrement", UsageTypes.RTC
STOP_EJECT = 0x00CC, "Stop/Eject", UsageTypes.OSC
PLAY_PAUSE = 0x00CD, "Play/Pause", UsageTypes.OSC
PLAY_SKIP = 0x00CE, "Play/Skip", UsageTypes.OSC
VOLUME = 0x00E0, "Volume", UsageTypes.LC
BALANCE = 0x00E1, "Balance", UsageTypes.LC
MUTE = 0x00E2, "Mute", UsageTypes.OOC
BASS = 0x00E3, "Bass", UsageTypes.LC
TREBLE = 0x00E4, "Treble", UsageTypes.LC
BASS_BOOST = 0x00E5, "Bass Boost", UsageTypes.OOC
SURROUND_MODE = 0x00E6, "Surround Mode", UsageTypes.OSC
LOUDNESS = 0x00E7, "Loudness", UsageTypes.OOC
MPX = 0x00E8, "MPX", UsageTypes.OOC
VOLUME_INCREMENT = 0x00E9, "Volume Increment", UsageTypes.RTC
VOLUME_DECREMENT = 0x00EA, "Volume Decrement", UsageTypes.RTC
SPEED_SELECT = 0x00F0, "Speed Select", UsageTypes.OSC
PLAYBACK_SPEED = 0x00F1, "Playback Speed", UsageTypes.NARY
STANDARD_PLAY = 0x00F2, "Standard Play", UsageTypes.SEL
LONG_PLAY = 0x00F3, "Long Play", UsageTypes.SEL
EXTENDED_PLAY = 0x00F4, "Extended Play", UsageTypes.SEL
SLOW = 0x00F5, "Slow", UsageTypes.OSC
FAN_ENABLE = 0x0100, "Fan Enable", UsageTypes.OOC
FAN_SPEED = 0x0101, "Fan Speed", UsageTypes.LC
LIGHT_ENABLE = 0x0102, "Light Enable", UsageTypes.OOC
LIGHT_ILLUMINATION_LEVEL = 0x0103, "Light Illumination Level", UsageTypes.LC
CLIMATE_CONTROL_ENABLE = 0x0104, "Climate Control Enable", UsageTypes.OOC
ROOM_TEMPERATURE = 0x0105, "Room Temperature", UsageTypes.LC
SECURITY_ENABLE = 0x0106, "Security Enable", UsageTypes.OOC
FIRE_ALARM = 0x0107, "Fire Alarm", UsageTypes.OSC
POLICE_ALARM = 0x0108, "Police Alarm", UsageTypes.OSC
PROXIMITY = 0x0109, "Proximity", UsageTypes.LC
MOTION = 0x010A, "Motion", UsageTypes.OSC
DURESS_ALARM = 0x010B, "Duress Alarm", UsageTypes.OSC
HOLDUP_ALARM = 0x010C, "Holdup Alarm", UsageTypes.OSC
MEDICAL_ALARM = 0x010D, "Medical Alarm", UsageTypes.OSC
BALANCE_RIGHT = 0x0150, "Balance Right", UsageTypes.RTC
BALANCE_LEFT = 0x0151, "Balance Left", UsageTypes.RTC
BASS_INCREMENT = 0x0152, "Bass Increment", UsageTypes.RTC
BASS_DECREMENT = 0x0153, "Bass Decrement", UsageTypes.RTC
TREBLE_INCREMENT = 0x0154, "Treble Increment", UsageTypes.RTC
TREBLE_DECREMENT = 0x0155, "Treble Decrement", UsageTypes.RTC
SPEAKER_SYSTEM = 0x0160, "Speaker System", UsageTypes.CL
CHANNEL_LEFT = 0x0161, "Channel Left", UsageTypes.CL
CHANNEL_RIGHT = 0x0162, "Channel Right", UsageTypes.CL
CHANNEL_CENTER = 0x0163, "Channel Center", UsageTypes.CL
CHANNEL_FRONT = 0x0164, "Channel Front", UsageTypes.CL
CHANNEL_CENTER_FRONT = 0x0165, "Channel Center Front", UsageTypes.CL
CHANNEL_SIDE = 0x0166, "Channel Side", UsageTypes.CL
CHANNEL_SURROUND = 0x0167, "Channel Surround", UsageTypes.CL
CHANNEL_LOW_FREQUENCY_ENHANCEMENT = 0x0168, "Channel Low Frequency Enhancement", UsageTypes.CL
CHANNEL_TOP = 0x0169, "Channel Top", UsageTypes.CL
CHANNEL_UNKNOWN = 0x016A, "Channel Unknown", UsageTypes.CL
SUBCHANNEL = 0x0170, "Sub-channel", UsageTypes.LC
SUBCHANNEL_INCREMENT = 0x0171, "Sub-channel Increment", UsageTypes.OSC
SUBCHANNEL_DECREMENT = 0x0172, "Sub-channel Decrement", UsageTypes.OSC
ALTERNATE_AUDIO_INCREMENT = 0x0173, "Alternate Audio Increment", UsageTypes.OSC
ALTERNATE_AUDIO_DECREMENT = 0x0174, "Alternate Audio Decrement", UsageTypes.OSC
APPLICATION_LAUNCH_BUTTONS = 0x0180, "Application Launch Buttons", UsageTypes.NARY
AL_LAUCH_BUTTON_CONFIGURATION_TOOL = 0x0181, "AL Launch Button Configuration Tool", UsageTypes.SEL
AL_PROGRAMMABLE_BUTTON_CONFIGURATION = 0x0182, "AL Programmable Button Configuration", UsageTypes.SEL
AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183, "AL Consumer Control Configuration", UsageTypes.SEL
AL_WORD_PROCESSOR = 0x0184, "AL Word Processor", UsageTypes.SEL
AL_TEXT_EDITOR = 0x0185, "AL Text Editor", UsageTypes.SEL
AL_SPREADSHEET = 0x0186, "AL Spreadsheet", UsageTypes.SEL
AL_GRAPHICS_EDITOR = 0x0187, "AL Graphics Editor", UsageTypes.SEL
AL_PRESENTATION_APP = 0x0188, "AL Presentation App", UsageTypes.SEL
AL_DATABASE_APP = 0x0189, "AL Database App", UsageTypes.SEL
AL_EMAIL_READER = 0x018A, "AL Email Reader", UsageTypes.SEL
AL_NEWSREADER = 0x018B, "AL Newsreader", UsageTypes.SEL
AL_VOICEMAIL = 0x018C, "AL Voicemail", UsageTypes.SEL
AL_CONTACTS_ADDRESS_BOOK = 0x018D, "AL Contacts/Address Book", UsageTypes.SEL
AL_CALENDAR_SCHEDULE = 0x018E, "AL Calendar/Schedule", UsageTypes.SEL
AL_TASK_PROJECT_MANAGER = 0x018F, "AL Task/Project Manager", UsageTypes.SEL
AL_LOG_JOURNAL_TIMECARD = 0x0190, "AL Log/Journal/Timecard", UsageTypes.SEL
AL_CHECKBOOK_FINANCE = 0x0191, "AL Checkbook/Finance", UsageTypes.SEL
AL_CALCULATOR = 0x0192, "AL Calculator", UsageTypes.SEL
AL_AV_CAPTURE_PLAYBACK = 0x0193, "AL A/V Capture/Playback", UsageTypes.SEL
AL_LOCAL_MACHINE_BROWSER = 0x0194, "AL Local Machine Browser", UsageTypes.SEL
AL_LAN_WAN_BROWSER = 0x0195, "AL LAN/WAN Browser", UsageTypes.SEL
AL_INTERNET_BROWSER = 0x0196, "AL Internet Browser", UsageTypes.SEL
AL_REMOTE_NETWORKING_ISP_CONNECT = 0x0197, "AL Remote Networking/ISP Connect", UsageTypes.SEL
AL_NETWORK_CONFERENCE = 0x0198, "AL Network Conference", UsageTypes.SEL
AL_NETWORK_CHAT = 0x0199, "AL Network Chat", UsageTypes.SEL
AL_TELEPHONY_DIALER = 0x019A, "AL Telephony/Dialer", UsageTypes.SEL
AL_LOGON = 0x019B, "AL Logon", UsageTypes.SEL
AL_LOGOFF = 0x019C, "AL Logoff", UsageTypes.SEL
AL_LOGON_LOGOFF = 0x019D, "AL Logon/Logoff", UsageTypes.SEL
AL_LOCK_SCREEN_SAVER = 0x019E, "AL Terminal Lock/Screensaver", UsageTypes.SEL
AL_CONTROL_PANEL = 0x019F, "AL Control Panel", UsageTypes.SEL
AL_COMMAND_LINE_PROCESSOR_RUN = 0x01A0, "AL Command Line Processor/Run", UsageTypes.SEL
AL_PROCESS_TASK_MANAGER = 0x01A1, "AL Process/Task Manager", UsageTypes.SEL
AL_SELECT_TASK_APPLICATION = 0x01A2, "AL Select Task/Application", UsageTypes.SEL
AL_NEXT_TASK_APPLICATION = 0x01A3, "AL Next Task/Application", UsageTypes.SEL
AL_PREVIOUS_TASK_APPLICATION = 0x01A4, "AL Previous Task/Application", UsageTypes.SEL
AL_HALT_TASK_APPLICATION = 0x01A5, "AL Preemptive Halt Task/Application", UsageTypes.SEL
AL_INTEGRATED_HELP_CENTER = 0x01A6, "AL Integrated Help Center", UsageTypes.SEL
AL_DOCUMENTS = 0x01A7, "AL Documents", UsageTypes.SEL
AL_THESAURUS = 0x01A8, "AL Thesaurus", UsageTypes.SEL
AL_DICTIONARY = 0x01A9, "AL Dictionary", UsageTypes.SEL
AL_DESKTOP = 0x01AA, "AL Desktop", UsageTypes.SEL
AL_SPELL_CHECK = 0x01AB, "AL Spell Check", UsageTypes.SEL
AL_GRAMMAR_CHECK = 0x01AC, "AL Grammar Check", UsageTypes.SEL
AL_WIRELESS_STATUS = 0x01AD, "AL Wireless Status", UsageTypes.SEL
AL_KEYBOARD_LAYOUT = 0x01AE, "AL Keyboard Layout", UsageTypes.SEL
AL_VIRUS_PROTECTION = 0x01AF, "AL Virus Protection", UsageTypes.SEL
AL_ENCRYPTION = 0x01B0, "AL Encryption", UsageTypes.SEL
AL_SCREEN_SAVER = 0x01B1, "AL Screen Saver", UsageTypes.SEL
AL_ALARMS = 0x01B2, "AL Alarms", UsageTypes.SEL
AL_CLOCK = 0x01B3, "AL Clock", UsageTypes.SEL
AL_FILE_BROWSER = 0x01B4, "AL File Browser", UsageTypes.SEL
AL_POWER_STATUS = 0x01B5, "AL Power Status", UsageTypes.SEL
AL_IMAGE_BROWSER = 0x01B6, "AL Image Browser", UsageTypes.SEL
AL_AUDIO_BROWSER = 0x01B7, "AL Audio Browser", UsageTypes.SEL
AL_VIDEO_BROWSER = 0x01B8, "AL Movie Browser", UsageTypes.SEL
AL_DIGITAL_RIGHTS_MANAGER = 0x01B9, "AL Digital Rights Manager", UsageTypes.SEL
AL_DIGITAL_WALLET = 0x01BA, "AL Digital Wallet", UsageTypes.SEL
AL_INSTANT_MESSAGING = 0x01BC, "AL Instant Messaging", UsageTypes.SEL
AL_OEM_FEATURES_TIPS_TUTORIAL_BROWSER = 0x01BD, "AL OEM Features/ Tips/Tutorial Browser", UsageTypes.SEL
AL_OEM_HELP = 0x01BE, "AL OEM Help", UsageTypes.SEL
AL_ONLINE_COMMUNITY = 0x01BF, "AL Online Community", UsageTypes.SEL
AL_ENTERTAINMENT_CONTENT_BROWSER = 0x01C0, "AL Entertainment Content Browser", UsageTypes.SEL
AL_ONLINE_SHOPPING_BROWSER = 0x01C1, "AL Online Shopping Browser", UsageTypes.SEL
AL_SMARTCARD_INFORMATION_HELP = 0x01C2, "AL SmartCard Information/Help", UsageTypes.SEL
AL_MARKET_MONITOR_FINANCE_BROWSER = 0x01C3, "AL Market Monitor/Finance Browser", UsageTypes.SEL
AL_CUSTOMIZED_CORPORATE_NEWS_BROWSER = 0x01C4, "AL Customized Corporate News Browser", UsageTypes.SEL
AL_ONLINE_ACTIVITY_BROWSER = 0x01C5, "AL Online Activity Browser", UsageTypes.SEL
AL_RESEARCH_SEARCH_BROWSER = 0x01C6, "AL Research/Search Browser", UsageTypes.SEL
AL_AUDIO_PLAYER = 0x01C7, "AL Audio Player", UsageTypes.SEL
GENERIC_GUI_APPLICATION_CONTROLS = 0x0200, "Generic GUI Application Controls", UsageTypes.NARY
AC_NEW = 0x0201, "AC New", UsageTypes.SEL
AC_OPEN = 0x0202, "AC Open", UsageTypes.SEL
AC_CLOSE = 0x0203, "AC Close", UsageTypes.SEL
AC_EXIT = 0x0204, "AC Exit", UsageTypes.SEL
AC_MAXIMIZE = 0x0205, "AC Maximize", UsageTypes.SEL
AC_MINIMIZE = 0x0206, "AC Minimize", UsageTypes.SEL
AC_SAVE = 0x0207, "AC Save", UsageTypes.SEL
AC_PRINT = 0x0208, "AC Print", UsageTypes.SEL
AC_PROPERTIES = 0x0209, "AC Properties", UsageTypes.SEL
AC_UNDO = 0x021A, "AC Undo", UsageTypes.SEL
AC_COPY = 0x021B, "AC Copy", UsageTypes.SEL
AC_CUT = 0x021C, "AC Cut", UsageTypes.SEL
AC_PASTE = 0x021D, "AC Paste", UsageTypes.SEL
AC_SELECT_ALL = 0x021E, "AC Select All", UsageTypes.SEL
AC_FIND = 0x021F, "AC Find", UsageTypes.SEL
AC_FIND_AND_REPLACE = 0x0220, "AC Find and Replace", UsageTypes.SEL
AC_SEARCH = 0x0221, "AC Search", UsageTypes.SEL
AC_GO_TO = 0x0222, "AC Go To", UsageTypes.SEL
AC_HOME = 0x0223, "AC Home", UsageTypes.SEL
AC_BACK = 0x0224, "AC Back", UsageTypes.SEL
AC_FORWARD = 0x0225, "AC Forward", UsageTypes.SEL
AC_STOP = 0x0226, "AC Stop", UsageTypes.SEL
AC_REFRESH = 0x0227, "AC Refresh", UsageTypes.SEL
AC_PREVIOUS_LINK = 0x0228, "AC Previous Link", UsageTypes.SEL
AC_NEXT_LINK = 0x0229, "AC Next Link", UsageTypes.SEL
AC_BOOKMARKS = 0x022A, "AC Bookmarks", UsageTypes.SEL
AC_HISTORY = 0x022B, "AC History", UsageTypes.SEL
AC_SUBSCRIPTIONS = 0x022C, "AC Subscriptions", UsageTypes.SEL
AC_ZOOM_IN = 0x022D, "AC Zoom In", UsageTypes.SEL
AC_ZOOM_OUT = 0x022E, "AC Zoom Out", UsageTypes.SEL
AC_ZOOM = 0x022F, "AC Zoom", UsageTypes.LC
AC_FULL_SCREEN_VIEW = 0x0230, "AC Full Screen View", UsageTypes.SEL
AC_NORMAL_VIEW = 0x0231, "AC Normal View", UsageTypes.SEL
AC_VIEW_TOGGLE = 0x0232, "AC View Toggle", UsageTypes.SEL
AC_SCROLL_UP = 0x0233, "AC Scroll Up", UsageTypes.SEL
AC_SCROLL_DOWN = 0x0234, "AC Scroll Down", UsageTypes.SEL
AC_SCROLL = 0x0235, "AC Scroll", UsageTypes.LC
AC_PAN_LEFT = 0x0236, "AC Pan Left", UsageTypes.SEL
AC_PAN_RIGHT = 0x0237, "AC Pan Right", UsageTypes.SEL
AC_PAN = 0x0238, "AC Pan", UsageTypes.LC
AC_NEW_WINDOWS = 0x0239, "AC New Window", UsageTypes.SEL
AC_TILE_HORIZONTALLY = 0x023A, "AC Tile Horizontally", UsageTypes.SEL
AC_TILE_VERTICALLY = 0x023B, "AC Tile Vertically", UsageTypes.SEL
AC_FORMAT = 0x023C, "AC Format", UsageTypes.SEL
AC_EDIT = 0x023D, "AC Edit", UsageTypes.SEL
AC_BOLD = 0x023E, "AC Bold", UsageTypes.SEL
AC_ITALICS = 0x023F, "AC Italics", UsageTypes.SEL
AC_UNDERLINE = 0x0240, "AC Underline", UsageTypes.SEL
AC_STRIKETHROUGH = 0x0241, "AC Strikethrough", UsageTypes.SEL
AC_SUBSCRIPT = 0x0242, "AC Subscript", UsageTypes.SEL
AC_SUPERSCRIPT = 0x0243, "AC Superscript", UsageTypes.SEL
AC_ALL_CAPS = 0x0244, "AC All Caps", UsageTypes.SEL
AC_ROTATE = 0x0245, "AC Rotate", UsageTypes.SEL
AC_RESIZE = 0x0246, "AC Resize", UsageTypes.SEL
AC_FLIP_HORIZONTAL = 0x0247, "AC Flip horizontal", UsageTypes.SEL
AC_FLIP_VERTICAL = 0x0248, "AC Flip Vertical", UsageTypes.SEL
AC_MIRROR_HORIZONTAL = 0x0249, "AC Mirror Horizontal", UsageTypes.SEL
AC_MIRROR_VERTICAL = 0x024A, "AC Mirror Vertical", UsageTypes.SEL
AC_FONT_SELECT = 0x024B, "AC Font Select", UsageTypes.SEL
AC_FONT_COLOR = 0x024C, "AC Font Color", UsageTypes.SEL
AC_FONT_SIZE = 0x024D, "AC Font Size", UsageTypes.SEL
AC_JUSTIFY_LEFT = 0x024E, "AC Justify Left", UsageTypes.SEL
AC_JUSTIFY_CENTER_H = 0x024F, "AC Justify Center H", UsageTypes.SEL
AC_JUSTIFY_RIGHT = 0x0250, "AC Justify Right", UsageTypes.SEL
AC_JUSTIFY_BLOCK_H = 0x0251, "AC Justify Block H", UsageTypes.SEL
AC_JUSTIFY_TOP = 0x0252, "AC Justify Top", UsageTypes.SEL
AC_JUSTIFY_CENTER_V = 0x0253, "AC Justify Center V", UsageTypes.SEL
AC_JUSTIFY_BOTTOM = 0x0254, "AC Justify Bottom", UsageTypes.SEL
AC_JUSTIFY_BLOCK_V = 0x0255, "AC Justify Block V", UsageTypes.SEL
AC_INDENT_INCREASE = 0x0256, "AC Indent Decrease", UsageTypes.SEL
AC_INDENT_DECREASE = 0x0257, "AC Indent Increase", UsageTypes.SEL
AC_NUMBERED_LIST = 0x0258, "AC Numbered List", UsageTypes.SEL
AC_RESTART_NUMBERING = 0x0259, "AC Restart Numbering", UsageTypes.SEL
AC_BULLETED_LIST = 0x025A, "AC Bulleted List", UsageTypes.SEL
AC_PROMOTE = 0x025B, "AC Promote", UsageTypes.SEL
AC_DEMOTE = 0x025C, "AC Demote", UsageTypes.SEL
AC_YES = 0x025D, "AC Yes", UsageTypes.SEL
AC_NO = 0x025E, "AC No", UsageTypes.SEL
AC_CANCEL = 0x025F, "AC Cancel", UsageTypes.SEL
AC_CATALOG = 0x0260, "AC Catalog", UsageTypes.SEL
AC_BUY_CHECKOUT = 0x0261, "AC Buy/Checkout", UsageTypes.SEL
AC_ADD_TO_CART = 0x0262, "AC Add to Cart", UsageTypes.SEL
AC_EXPAND = 0x0263, "AC Expand", UsageTypes.SEL
AC_EXPAND_ALL = 0x0264, "AC Expand All", UsageTypes.SEL
AC_COLLAPSE = 0x0265, "AC Collapse", UsageTypes.SEL
AC_COLLAPSE_ALL = 0x0266, "AC Collapse All", UsageTypes.SEL
AC_PRINT_PREVIEW = 0x0267, "AC Print Preview", UsageTypes.SEL
AC_PASTE_SPECIAL = 0x0268, "AC Paste Special", UsageTypes.SEL
AC_INSER_MODE = 0x0269, "AC Insert Mode", UsageTypes.SEL
AC_DELETE = 0x026A, "AC Delete", UsageTypes.SEL
AC_LOCK = 0x026B, "AC Lock", UsageTypes.SEL
AC_UNLOCK = 0x026C, "AC Unlock", UsageTypes.SEL
AC_PROTECT = 0x026D, "AC Protect", UsageTypes.SEL
AC_UNPROTECT = 0x026E, "AC Unprotect", UsageTypes.SEL
AC_ATTACH_COMMENT = 0x026F, "AC Attach Comment", UsageTypes.SEL
AC_DELETE_COMMENT = 0x0270, "AC Delete Comment", UsageTypes.SEL
AC_VIEW_COMMENT = 0x0271, "AC View Comment", UsageTypes.SEL
AC_SELECT_WORD = 0x0272, "AC Select Word", UsageTypes.SEL
AC_SELECT_SENTENCE = 0x0273, "AC Select Sentence", UsageTypes.SEL
AC_SELECT_PARAGRAPH = 0x0274, "AC Select Paragraph", UsageTypes.SEL
AC_SELECT_COLUMN = 0x0275, "AC Select Column", UsageTypes.SEL
AC_SELECT_ROW = 0x0276, "AC Select Row", UsageTypes.SEL
AC_SELECT_TABLE = 0x0277, "AC Select Table", UsageTypes.SEL
AC_SELECT_OBJECT = 0x0278, "AC Select Object", UsageTypes.SEL
AC_REDO_REPEAT = 0x0279, "AC Redo/Repeat", UsageTypes.SEL
AC_SORT = 0x027A, "AC Sort", UsageTypes.SEL
AC_SORT_ASCENDING = 0x027B, "AC Sort Ascending", UsageTypes.SEL
AC_SORT_DESCENDING = 0x027C, "AC Sort Descending", UsageTypes.SEL
AC_FILTER = 0x027D, "AC Filter", UsageTypes.SEL
AC_SET_CLOCK = 0x027E, "AC Set Clock", UsageTypes.SEL
AC_VIEW_CLOCK = 0x027F, "AC View Clock", UsageTypes.SEL
AC_SELECT_TIME_ZONE = 0x0280, "AC Select Time Zone", UsageTypes.SEL
AC_EDIT_TIME_ZONES = 0x0281, "AC Edit Time Zones", UsageTypes.SEL
AC_SET_ALARM = 0x0282, "AC Set Alarm", UsageTypes.SEL
AC_CLEAR_ALARM = 0x0283, "AC Clear Alarm", UsageTypes.SEL
AC_SNOOZE_ALARM = 0x0284, "AC Snooze Alarm", UsageTypes.SEL
AC_RESET_ALARM = 0x0285, "AC Reset Alarm", UsageTypes.SEL
AC_SYNCHRONIZE = 0x0286, "AC Synchronize", UsageTypes.SEL
AC_SEND_RECEIVE = 0x0287, "AC Send/Receive", UsageTypes.SEL
AC_SEND_TO = 0x0288, "AC Send To", UsageTypes.SEL
AC_REPLY = 0x0289, "AC Reply", UsageTypes.SEL
AC_REPLY_ALL = 0x028A, "AC Reply All", UsageTypes.SEL
AC_FORWARD_MSG = 0x028B, "AC Forward Msg", UsageTypes.SEL
AC_SEND = 0x028C, "AC Send", UsageTypes.SEL
AC_ATTACH_FILE = 0x028D, "AC Attach File", UsageTypes.SEL
AC_UPLOAD = 0x028E, "AC Upload", UsageTypes.SEL
AC_DOWNLOAD = 0x028F, "AC Download (Save Target As)", UsageTypes.SEL
AC_SET_BORDERS = 0x0290, "AC Set Borders", UsageTypes.SEL
AC_INSERT_ROW = 0x0291, "AC Insert Row", UsageTypes.SEL
AC_INSERT_COLUMN = 0x0292, "AC Insert Column", UsageTypes.SEL
AC_INSERT_FILE = 0x0293, "AC Insert File", UsageTypes.SEL
AC_INSERT_PICTURE = 0x0294, "AC Insert Picture", UsageTypes.SEL
AC_INSERT_OBJECT = 0x0295, "AC Insert Object", UsageTypes.SEL
AC_INSERT_SYMBOL = 0x0296, "AC Insert Symbol", UsageTypes.SEL
AC_SAVE_AND_CLOSE = 0x0297, "AC Save and Close", UsageTypes.SEL
AC_RENAME = 0x0298, "AC Rename", UsageTypes.SEL
AC_MERGE = 0x0299, "AC Merge", UsageTypes.SEL
AC_SPLIT = 0x029A, "AC Split", UsageTypes.SEL
AC_DISTRIBUTE_HORIZONTICALLY = 0x029B, "AC Disribute Horizontally", UsageTypes.SEL
AC_DISTRIBUTE_VERTICALLY = 0x029C, "AC Distribute Vertically", UsageTypes.SEL
class PowerDevice(_Data):
INAME = 0x01, "iName", UsageTypes.SV
PRESENT_STATUS = 0x02, "PresentStatus", UsageTypes.CL
CHARGED_STATUS = 0x03, "ChangedStatus", UsageTypes.CL
UPS = 0x04, "UPS", UsageTypes.CA
POWER_SUPPLY = 0x05, "PowerSupply", UsageTypes.CA
BATTERY_SYSTEM = 0x10, "BatterySystem", UsageTypes.CP
BATTERY_SYSTEM_ID = 0x11, "BatterySystemID", UsageTypes.SV
BATTERY = 0x12, "Battery", UsageTypes.CP
BATTERY_ID = 0x13, "BatteryID", UsageTypes.SV
CHARGER = 0x14, "Charger", UsageTypes.CP
CHARGER_ID = 0x15, "ChargerID", UsageTypes.SV
POWER_CONVERTER = 0x16, "PowerConverter", UsageTypes.CP
POWER_CONVERTER_ID = 0x17, "PowerConverterID", UsageTypes.SV
OUTLET_SYSTEM = 0x18, "OutletSystem", UsageTypes.CP
OUTLET_SYSTEM_ID = 0x19, "OutletSystemID", UsageTypes.SV
INPUT = 0x1A, "Input", UsageTypes.CP
INPUT_ID = 0x1B, "InputID", UsageTypes.SV
OUTPUT = 0x1C, "Output", UsageTypes.CP
OUTPUT_ID = 0x1D, "OutputID", UsageTypes.SV
FLOW = 0x1E, "Flow", UsageTypes.CP
FLOW_ID = 0x1F, "FlowID", UsageTypes.SV
OUTLET = 0x20, "Outlet", UsageTypes.CP
OUTLET_ID = 0x21, "OutletID", UsageTypes.SV
GANG = 0x22, "Gang", UsageTypes.CP
GANG_ID = 0x23, "GangID", UsageTypes.SV
POWER_SUMMARY = 0x24, "PowerSummary", UsageTypes.CP
POWER_SUMMARY_ID = 0x25, "PowerSummaryID", UsageTypes.SV
VOLTAGE = 0x30, "Voltage", UsageTypes.DV
CURRENT = 0x31, "Current", UsageTypes.DV
FREQUENCY = 0x32, "Frequency", UsageTypes.DV
APPARENT_POWER = 0x33, "ApparentPower", UsageTypes.DV
ACTIVE_POWER = 0x34, "ActivePower", UsageTypes.DV
PERCENT_LOAD = 0x35, "PercentLoad", UsageTypes.DV
TEMPERATURE = 0x36, "Temperature", UsageTypes.DV
HUMIFITY = 0x37, "Humidity", UsageTypes.DV
BAD_COUNT = 0x38, "BadCount", UsageTypes.DV
CONFIG_VOLTAGE = 0x40, "ConfigVoltage", (UsageTypes.SV, UsageTypes.DV)
CONFIG_CURRENT = 0x41, "ConfigCurrent", (UsageTypes.SV, UsageTypes.DV)
CONFIG_FREQUENCY = 0x42, "ConfigFrequency", (UsageTypes.SV, UsageTypes.DV)
CONFIG_APPARENT_POWER = 0x43, "ConfigApparentPower", (UsageTypes.SV, UsageTypes.DV)
CONFIG_ACTIVE_POWER = 0x44, "ConfigActivePower", (UsageTypes.SV, UsageTypes.DV)
CONFIG_PERCENT_LOAD = 0x45, "ConfigPercentLoad", (UsageTypes.SV, UsageTypes.DV)
CONFIG_TEMPERATURE = 0x46, "ConfigTemperature", (UsageTypes.SV, UsageTypes.DV)
CONFIG_HUMIFITY = 0x47, "ConfigHumidity", (UsageTypes.SV, UsageTypes.DV)
SWITCH_ON_CONTROL = 0x50, "SwitchOnControl", UsageTypes.DV
SWITCH_OFF_CONTROL = 0x51, "SwitchOffControl", UsageTypes.DV
TOGGLE_CONTROL = 0x52, "ToggleControl", UsageTypes.DV
LOW_VOLTAGE_TRANSFER = 0x53, "LowVoltageTransfer", UsageTypes.DV
HIGH_VOLTAGE_TRANSFER = 0x54, "HighVoltageTransfer", UsageTypes.DV
DELAY_BEFORE_REBOOT = 0x55, "DelayBeforeReboot", UsageTypes.DV
DELAY_BEFORE_STARTUP = 0x56, "DelayBeforeStartup", UsageTypes.DV
DELAY_BEFORE_SHUTDOWN = 0x57, "DelayBeforeShutdown", UsageTypes.DV
TEST = 0x58, "Test", UsageTypes.DV
MODULE_RESET = 0x59, "ModuleReset", UsageTypes.DV
AUDIBLE_ALARM_CONTROL = 0x5A, "AudibleAlarmControl", UsageTypes.DV
PRESENT = 0x60, "Present", UsageTypes.DF
GOOD = 0x61, "Good", UsageTypes.DF
INTERNAL_FAILURE = 0x62, "InternalFailure", UsageTypes.DF
VOLTAGE_OUT_OF_RANGE = 0x63, "VoltageOutOfRange", UsageTypes.DF
FREQUENCY_OUT_OF_RANGE = 0x64, "FrequencyOutOfRange", UsageTypes.DF
OVERLOAD = 0x65, "Overload", UsageTypes.DF
OVERCHARGED = 0x66, "OverCharged", UsageTypes.DF
OVER_TEMPERATURE = 0x67, "OverTemperature", UsageTypes.DF
SHUTDOWN_REQUESTED = 0x68, "ShutdownRequested", UsageTypes.DF
SHUTDOWN_IMMINEBT = 0x69, "ShutdownImminent", UsageTypes.DF
SWITCH_ON_OFF = 0x6B, "SwitchOn/Off", UsageTypes.DF
SWITCHABLE = 0x6C, "Switchable", UsageTypes.DF
USED = 0x6D, "Used", UsageTypes.DF
BOOST = 0x6E, "Boost", UsageTypes.DF
BUCK = 0x6F, "Buck", UsageTypes.DF
INITIALIZED = 0x70, "Initialized", UsageTypes.DF
TESTED = 0x71, "Tested", UsageTypes.DF
AWAITING_POWER = 0x72, "AwaitingPower", UsageTypes.DF
COMMUNICATION_LOST = 0x73, "CommunicationLost", UsageTypes.DF
IMANUFACTURER = 0xFD, "iManufacturer", UsageTypes.SV
IPRODUCT = 0xFE, "iProduct", UsageTypes.SV
ISERIALNUMBER = 0xFF, "iSerialNumber", UsageTypes.SV
class FIDO(_Data):
U2F_AUTHENTICATOR_DEVICEM = 0x01, "U2F Authenticator Device"
INPUT_REPORT_DATA = 0x20, "Input Report Data"
OUTPUT_REPORT_DATA = 0x21, "Output Report Data"
class UsagePages(_Data):
GENERIC_DESKTOP_CONTROLS_PAGE = 0x01, "Generic Desktop Controls", GenericDesktopControls
SIMULATION_CONTROLS_PAGE = 0x02, "Simulation Controls"
VR_CONTROLS_PAGE = 0x03, "VR Controls"
SPORT_CONTROLS_PAGE = 0x04, "Sport Controls"
GAME_CONTROLS_PAGE = 0x05, "Game Controls"
GENERIC_DEVICE_CONTROLS_PAGE = 0x06, "Generic Device Controls"
KEYBOARD_KEYPAD_PAGE = 0x07, "Keyboard/Keypad", KeyboardKeypad
LED_PAGE = 0x08, "LED", Led
BUTTON_PAGE = 0x09, "Button", Button
ORDINAL_PAGE = 0x0A, "Ordinal"
TELEPHONY_PAGE = 0x0B, "Telephony"
CONSUMER_PAGE = 0x0C, "Consumer", Consumer
DIGITIZER_PAGE = 0x0D, "Digitizer"
HAPTICS_PAGE = 0x0E, "Haptics"
PID_PAGE = 0x0F, "PID"
UNICODE_PAGE = 0x10, "Unicode"
EYE_AND_HEAD_TRACKER_PAGE = 0x12, "Eye and Head Tracker"
ALPHANUMERIC_DISPLAY_PAGE = 0x14, "Alphanumeric Display"
SENSOR_PAGE = 0x20, "Sensor"
MEDICAL_INSTRUMENTS_PAGE = 0x40, "Medical Instruments"
BRAILLE_DISPLAY_PAGE = 0x41, "Braillie"
LIGHTING_AND_ILLUMINATION_PAGE = 0x59, "Lighting and Illumination"
USB_MONITOR_PAGE = 0x80, "USB Monitor"
USB_ENUMERATED_VALUES_PAGE = 0x81, "USB Enumerated Values"
VESA_VIRTUAL_CONTROLS_PAGE = 0x82, "VESA Virtual Controls"
POWER_DEVICE_PAGE = 0x84, "Power Device", PowerDevice
BATTERY_SYSTEM_PAGE = 0x85, "Battery System"
BARCODE_SCANNER_PAGE = 0x8C, "Barcode Scanner"
WEIGHING_PAGE = 0x8D, "Weighing"
MSR_PAGE = 0x8E, "MSR"
RESERVED_POS_PAGE = 0x8F, "Reserved POS"
CAMERA_CONTROL_PAGE = 0x90, "Camera Control"
ARCADE_PAGE = 0x91, "Arcade"
GAMING_DEVICE_PAGE = 0x92, "Gaming Device"
FIDO_ALLIANCE_PAGE = 0xF1D0, "FIDO Alliance", FIDO
VENDOR_PAGE = 0xFF00, ..., 0xFFFF, "Vendor Page"
| 57,667 | Python | .py | 1,018 | 50.936149 | 108 | 0.701437 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,512 | test_hidpp20_complex.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_hidpp20_complex.py | ## Copyright (C) 2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import pytest
import yaml
from logitech_receiver import common
from logitech_receiver import exceptions
from logitech_receiver import hidpp20
from logitech_receiver import hidpp20_constants
from logitech_receiver import special_keys
from . import fake_hidpp
_hidpp20 = hidpp20.Hidpp20()
device_offline = fake_hidpp.Device("REGISTERS", False)
device_registers = fake_hidpp.Device("OFFLINE", True, 1.0)
device_nofeatures = fake_hidpp.Device("NOFEATURES", True, 4.5)
device_zerofeatures = fake_hidpp.Device("ZEROFEATURES", True, 4.5, [fake_hidpp.Response("0000", 0x0000, "0001")])
device_broken = fake_hidpp.Device(
"BROKEN", True, 4.5, [fake_hidpp.Response("0500", 0x0000, "0001"), fake_hidpp.Response(None, 0x0100)]
)
device_standard = fake_hidpp.Device("STANDARD", True, 4.5, fake_hidpp.r_keyboard_2)
@pytest.mark.parametrize(
"device, expected_result, expected_count",
[
(device_offline, False, 0),
(device_registers, False, 0),
(device_nofeatures, False, 0),
(device_zerofeatures, False, 0),
(device_broken, False, 0),
(device_standard, True, 9),
],
)
def test_FeaturesArray_check(device, expected_result, expected_count):
featuresarray = hidpp20.FeaturesArray(device)
result = featuresarray._check()
result2 = featuresarray._check()
assert result == expected_result
assert result2 == expected_result
assert (hidpp20_constants.SupportedFeature.ROOT in featuresarray) == expected_result
assert len(featuresarray) == expected_count
assert bool(featuresarray) == expected_result
@pytest.mark.parametrize(
"device, expected0, expected1, expected2, expected5, expected5v",
[
(device_zerofeatures, None, None, None, None, None),
(device_standard, 0x0000, 0x0001, 0x0020, hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, 3),
],
)
def test_FeaturesArray_get_feature(device, expected0, expected1, expected2, expected5, expected5v):
featuresarray = hidpp20.FeaturesArray(device)
device.features = featuresarray
result0 = featuresarray.get_feature(0)
result1 = featuresarray.get_feature(1)
result2 = featuresarray.get_feature(2)
result5 = featuresarray.get_feature(5)
result2r = featuresarray.get_feature(2)
result5v = featuresarray.get_feature_version(hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4)
assert result0 == expected0
assert result1 == expected1
assert result2 == expected2
assert result2r == expected2
assert result5 == expected5
assert result5v == expected5v
@pytest.mark.parametrize(
"device, expected_result",
[
(device_zerofeatures, []),
(
device_standard,
[
(hidpp20_constants.SupportedFeature.ROOT, 0),
(hidpp20_constants.SupportedFeature.FEATURE_SET, 1),
(hidpp20_constants.SupportedFeature.CONFIG_CHANGE, 2),
(hidpp20_constants.SupportedFeature.DEVICE_FW_VERSION, 3),
(common.NamedInt(256, "unknown:0100"), 4),
(hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, 5),
(None, 6),
(None, 7),
(hidpp20_constants.SupportedFeature.BATTERY_STATUS, 8),
],
),
],
)
def test_FeaturesArray_enumerate(device, expected_result):
featuresarray = hidpp20.FeaturesArray(device)
result = list(featuresarray.enumerate())
assert result == expected_result
def test_FeaturesArray_setitem():
featuresarray = hidpp20.FeaturesArray(device_standard)
featuresarray[hidpp20_constants.SupportedFeature.ROOT] = 3
featuresarray[hidpp20_constants.SupportedFeature.FEATURE_SET] = 5
featuresarray[hidpp20_constants.SupportedFeature.FEATURE_SET] = 4
assert featuresarray[hidpp20_constants.SupportedFeature.FEATURE_SET] == 4
assert featuresarray.inverse[4] == hidpp20_constants.SupportedFeature.FEATURE_SET
def test_FeaturesArray_delitem():
featuresarray = hidpp20.FeaturesArray(device_standard)
with pytest.raises(ValueError):
del featuresarray[5]
@pytest.mark.parametrize(
"device, expected0, expected1, expected2, expected1v",
[(device_zerofeatures, None, None, None, None), (device_standard, 0, 5, None, 3)],
)
def test_FeaturesArray_getitem(device, expected0, expected1, expected2, expected1v):
featuresarray = hidpp20.FeaturesArray(device)
device.features = featuresarray
result_get0 = featuresarray[hidpp20_constants.SupportedFeature.ROOT]
result_get1 = featuresarray[hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4]
result_get2 = featuresarray[hidpp20_constants.SupportedFeature.GKEY]
result_1v = featuresarray.get_feature_version(hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4)
assert result_get0 == expected0
assert result_get1 == expected1
assert result_get2 == expected2
assert result_1v == expected1v
@pytest.mark.parametrize(
"device, index, cid, tid, flags, default_task, flag_names",
[
(device_standard, 2, 1, 1, 0x30, "Volume Up", ["reprogrammable", "divertable"]),
(device_standard, 1, 2, 2, 0x20, "Volume Down", ["divertable"]),
],
)
def test_ReprogrammableKey_key(device, index, cid, tid, flags, default_task, flag_names):
key = hidpp20.ReprogrammableKey(device, index, cid, tid, flags)
assert key._device == device
assert key.index == index
assert key._cid == cid
assert key._tid == tid
assert key._flags == flags
assert key.key == special_keys.CONTROL[cid]
assert key.default_task == common.NamedInt(cid, default_task)
assert list(key.flags) == flag_names
@pytest.mark.parametrize(
"device, index, cid, tid, flags, pos, group, gmask, default_task, flag_names, group_names",
[
(device_standard, 1, 0x51, 0x39, 0x60, 0, 1, 1, "Right Click", ["divertable", "persistently divertable"], ["g1"]),
(device_standard, 2, 0x52, 0x3A, 0x11, 1, 2, 3, "Mouse Middle Button", ["mse", "reprogrammable"], ["g1", "g2"]),
(
device_standard,
3,
0x53,
0x3C,
0x110,
2,
2,
7,
"Mouse Back Button",
["reprogrammable", "raw XY"],
["g1", "g2", "g3"],
),
],
)
def test_reprogrammable_key_v4_key(device, index, cid, tid, flags, pos, group, gmask, default_task, flag_names, group_names):
key = hidpp20.ReprogrammableKeyV4(device, index, cid, tid, flags, pos, group, gmask)
assert key._device == device
assert key.index == index
assert key._cid == cid
assert key._tid == tid
assert key._flags == flags
assert key.pos == pos
assert key.group == group
assert key._gmask == gmask
assert key.key == special_keys.CONTROL[cid]
assert key.default_task == common.NamedInt(cid, default_task)
assert list(key.flags) == flag_names
assert list(key.group_mask) == group_names
@pytest.mark.parametrize(
"responses, index, mapped_to, remappable_to, mapping_flags",
[
(fake_hidpp.responses_key, 1, "Right Click", common.UnsortedNamedInts(Right_Click=81, Left_Click=80), []),
(fake_hidpp.responses_key, 2, "Left Click", None, ["diverted"]),
(fake_hidpp.responses_key, 3, "Mouse Back Button", None, ["diverted", "persistently diverted"]),
(fake_hidpp.responses_key, 4, "Mouse Forward Button", None, ["diverted", "raw XY diverted"]),
],
)
# these fields need access all the key data, so start by setting up a device and its key data
def test_ReprogrammableKeyV4_query(responses, index, mapped_to, remappable_to, mapping_flags):
device = fake_hidpp.Device(
"KEY", responses=responses, feature=hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, offset=5
)
device._keys = _hidpp20.get_keys(device)
key = device.keys[index]
assert key.mapped_to == mapped_to
assert (key.remappable_to == remappable_to) or remappable_to is None
assert list(key.mapping_flags) == mapping_flags
@pytest.mark.parametrize(
"responses, index, diverted, persistently_diverted, rawXY_reporting, remap, sets",
[
(fake_hidpp.responses_key, 1, True, False, True, 0x52, ["0051080000"]),
(fake_hidpp.responses_key, 2, False, True, False, 0x51, ["0052020000", "0052200000", "0052000051"]),
(fake_hidpp.responses_key, 3, False, True, True, 0x50, ["0053020000", "00530C0000", "0053300000", "0053000050"]),
(fake_hidpp.responses_key, 4, False, False, False, 0x50, ["0056020000", "0056080000", "0056200000", "0056000050"]),
],
)
def test_ReprogrammableKeyV4_set(responses, index, diverted, persistently_diverted, rawXY_reporting, remap, sets, mocker):
responses += [fake_hidpp.Response(r, 0x530, r) for r in sets]
device = fake_hidpp.Device(
"KEY", responses=responses, feature=hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, offset=5
)
device._keys = _hidpp20.get_keys(device)
device._keys._ensure_all_keys_queried() # do this now so that the last requests are sets
spy_request = mocker.spy(device, "request")
key = device.keys[index]
_mapping_flags = list(key.mapping_flags)
if "divertable" in key.flags or not diverted:
key.set_diverted(diverted)
else:
with pytest.raises(exceptions.FeatureNotSupported):
key.set_diverted(diverted)
assert ("diverted" in list(key.mapping_flags)) == (diverted and "divertable" in key.flags)
if "persistently divertable" in key.flags or not persistently_diverted:
key.set_persistently_diverted(persistently_diverted)
else:
with pytest.raises(exceptions.FeatureNotSupported):
key.set_persistently_diverted(persistently_diverted)
assert ("persistently diverted" in key.mapping_flags) == (persistently_diverted and "persistently divertable" in key.flags)
if "raw XY" in key.flags or not rawXY_reporting:
key.set_rawXY_reporting(rawXY_reporting)
else:
with pytest.raises(exceptions.FeatureNotSupported):
key.set_rawXY_reporting(rawXY_reporting)
assert ("raw XY diverted" in list(key.mapping_flags)) == (rawXY_reporting and "raw XY" in key.flags)
if remap in key.remappable_to or remap == 0:
key.remap(remap)
else:
with pytest.raises(exceptions.FeatureNotSupported):
key.remap(remap)
assert (key.mapped_to == remap) or (remap not in key.remappable_to and remap != 0)
fake_hidpp.match_requests(len(sets), responses, spy_request.call_args_list)
@pytest.mark.parametrize(
"r, index, cid, actionId, remapped, mask, status, action, modifiers, byts, remap",
[
(fake_hidpp.responses_key, 1, 0x0051, 0x02, 0x0002, 0x01, 0, "Mouse Button: 2", "Cntrl+", "02000201", "01000400"),
(fake_hidpp.responses_key, 2, 0x0052, 0x01, 0x0001, 0x00, 1, "Key: 1", "", "01000100", "02005004"),
(fake_hidpp.responses_key, 3, 0x0053, 0x02, 0x0001, 0x00, 1, "Mouse Button: 1", "", "02000100", "7FFFFFFF"),
],
)
def test_remappable_action(r, index, cid, actionId, remapped, mask, status, action, modifiers, byts, remap, mocker):
if int(remap, 16) == special_keys.KEYS_Default:
responses = r + [
fake_hidpp.Response("040000", 0x0000, "1C00"),
fake_hidpp.Response("00", 0x450, f"{cid:04X}" + "FF"),
]
else:
responses = r + [
fake_hidpp.Response("040000", 0x0000, "1C00"),
fake_hidpp.Response("00", 0x440, f"{cid:04X}" + "FF" + remap),
]
device = fake_hidpp.Device(
"KEY", responses=responses, feature=hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, offset=5
)
key = hidpp20.PersistentRemappableAction(device, index, cid, actionId, remapped, mask, status)
spy_request = mocker.spy(device, "request")
assert key._device == device
assert key.index == index
assert key._cid == cid
assert key.actionId == actionId
assert key.remapped == remapped
assert key._modifierMask == mask
assert key.cidStatus == status
assert key.key == special_keys.CONTROL[cid]
assert key.actionType == special_keys.ACTIONID[actionId]
assert key.action == action
assert key.modifiers == modifiers
assert key.data_bytes.hex().upper() == byts
key.remap(bytes.fromhex(remap))
assert key.data_bytes.hex().upper() == (byts if int(remap, 16) == special_keys.KEYS_Default else remap)
if int(remap, 16) != special_keys.KEYS_Default:
fake_hidpp.match_requests(1, responses, spy_request.call_args_list)
# KeysArray methods tested in KeysArrayV4
# KeysArrayV2 not tested as there is no documentation
@pytest.mark.parametrize(
"device, index", [(device_zerofeatures, -1), (device_zerofeatures, 5), (device_standard, -1), (device_standard, 6)]
)
def test_KeysArrayV4_index_error(device, index):
keysarray = hidpp20.KeysArrayV4(device, 5)
with pytest.raises(IndexError):
keysarray[index]
with pytest.raises(IndexError):
keysarray._query_key(index)
@pytest.mark.parametrize("device, index, top, cid", [(device_standard, 0, 2, 0x0011), (device_standard, 4, 5, 0x0003)])
def test_KeysArrayV4_query_key(device, index, top, cid):
keysarray = hidpp20.KeysArrayV4(device, 5)
keysarray._query_key(index)
assert keysarray.keys[index]._cid == cid
assert len(keysarray[index:top]) == top - index
assert len(list(keysarray)) == 5
@pytest.mark.parametrize(
"device, count, index, cid, tid, flags, pos, group, gmask",
[
(device_standard, 4, 0, 0x0011, 0x0012, 0xCDAB, 1, 2, 3),
(device_standard, 6, 1, 0x0111, 0x0022, 0xCDAB, 1, 2, 3),
(device_standard, 8, 3, 0x0311, 0x0032, 0xCDAB, 1, 2, 4),
],
)
def test_KeysArrayV4__getitem(device, count, index, cid, tid, flags, pos, group, gmask):
keysarray = hidpp20.KeysArrayV4(device, count)
result = keysarray[index]
assert result._device == device
assert result.index == index
assert result._cid == cid
assert result._tid == tid
assert result._flags == flags
assert result.pos == pos
assert result.group == group
assert result._gmask == gmask
@pytest.mark.parametrize(
"key, index", [(special_keys.CONTROL.Volume_Up, 2), (special_keys.CONTROL.Mute, 4), (special_keys.CONTROL.Next, None)]
)
def test_KeysArrayV4_index(key, index):
keysarray = hidpp20.KeysArrayV4(device_standard, 7)
result = keysarray.index(key)
assert result == index
device_key = fake_hidpp.Device(
"KEY", responses=fake_hidpp.responses_key, feature=hidpp20_constants.SupportedFeature.REPROG_CONTROLS_V4, offset=5
)
@pytest.mark.parametrize(
"key, expected_index, expected_mapped_to, expected_remappable_to",
[
(
special_keys.CONTROL.Left_Button,
0,
common.NamedInt(0x50, "Left Click"),
[common.NamedInt(0x50, "Left Click"), common.NamedInt(0x51, "Right Click")],
),
(
special_keys.CONTROL.Right_Button,
1,
common.NamedInt(0x51, "Right Click"),
[common.NamedInt(0x51, "Right Click"), common.NamedInt(0x50, "Left Click")],
),
(special_keys.CONTROL.Middle_Button, 2, common.NamedInt(0x50, "Left Click"), None),
(special_keys.CONTROL.Back_Button, 3, common.NamedInt(0x53, "Mouse Back Button"), None),
(special_keys.CONTROL.Forward_Button, 4, common.NamedInt(0x56, "Mouse Forward Button"), None),
(special_keys.CONTROL.Mouse_Gesture_Button, 5, common.NamedInt(0xC3, "Gesture Button Navigation"), None),
(special_keys.CONTROL.Smart_Shift, 6, common.NamedInt(0x50, "Left Click"), None),
(special_keys.CONTROL.Virtual_Gesture_Button, 7, common.NamedInt(0x51, "Right Click"), None),
],
)
def test_KeysArrayV4_key(key, expected_index, expected_mapped_to, expected_remappable_to):
device_key._keys = _hidpp20.get_keys(device_key)
device_key._keys._ensure_all_keys_queried()
index = device_key._keys.index(key)
mapped_to = device_key._keys[expected_index].mapped_to
remappable_to = device_key._keys[expected_index].remappable_to
assert index == expected_index
assert mapped_to == expected_mapped_to
if expected_remappable_to is not None:
assert list(remappable_to) == expected_remappable_to
@pytest.mark.parametrize(
"device, index", [(device_zerofeatures, -1), (device_zerofeatures, 5), (device_standard, -1), (device_standard, 6)]
)
def test_KeysArrayPersistent_index_error(device, index):
keysarray = hidpp20.KeysArrayPersistent(device, 5)
with pytest.raises(IndexError):
keysarray[index]
with pytest.raises(IndexError):
keysarray._query_key(index)
@pytest.mark.parametrize(
"responses, key, index, mapped_to, capabilities",
[
(fake_hidpp.responses_remap, special_keys.CONTROL.Left_Button, 0, common.NamedInt(0x01, "Mouse Button Left"), 0x41),
(fake_hidpp.responses_remap, special_keys.CONTROL.Right_Button, 1, common.NamedInt(0x01, "Mouse Button Left"), 0x41),
(fake_hidpp.responses_remap, special_keys.CONTROL.Middle_Button, 2, common.NamedInt(0x51, "DOWN"), 0x41),
],
)
def test_KeysArrayPersistent_key(responses, key, index, mapped_to, capabilities):
device = fake_hidpp.Device(
"REMAP", responses=responses, feature=hidpp20_constants.SupportedFeature.PERSISTENT_REMAPPABLE_ACTION
)
device._remap_keys = _hidpp20.get_remap_keys(device)
device._remap_keys._ensure_all_keys_queried()
assert device._remap_keys.index(key) == index
assert device._remap_keys[index].remapped == mapped_to
assert device._remap_keys.capabilities == capabilities
@pytest.mark.parametrize(
"id, length, minimum, maximum, widget, min, max, wid, string",
[
("left", 1, 5, 8, "Widget", 5, 8, "Widget", "left"),
("left", 1, None, None, None, 0, 255, "Scale", "left"),
],
)
def test_SubParam(id, length, minimum, maximum, widget, min, max, wid, string):
subparam = hidpp20.SubParam(id, length, minimum, maximum, widget)
assert subparam.id == id
assert subparam.length == length
assert subparam.minimum == min
assert subparam.maximum == max
assert subparam.widget == wid
assert subparam.__str__() == string
assert subparam.__repr__() == string
@pytest.mark.parametrize(
"device, low, high, next_index, next_diversion_index, name, cbe, si, sdi, eom, dom",
[
(device_standard, 0x01, 0x01, 5, 10, "Tap1Finger", True, 5, None, (0, 0x20), (None, None)),
(device_standard, 0x03, 0x02, 6, 11, "Tap3Finger", False, None, 11, (None, None), (1, 0x08)),
],
)
def test_Gesture(device, low, high, next_index, next_diversion_index, name, cbe, si, sdi, eom, dom):
gesture = hidpp20.Gesture(device, low, high, next_index, next_diversion_index)
assert gesture._device == device
assert gesture.id == low
assert gesture.gesture == name
assert gesture.can_be_enabled == cbe
assert gesture.can_be_enabled == cbe
assert gesture.index == si
assert gesture.diversion_index == sdi
assert gesture.enable_offset_mask() == eom
assert gesture.diversion_offset_mask() == dom
assert gesture.as_int() == low
assert int(gesture) == low
@pytest.mark.parametrize(
"responses, gest, enabled, diverted, set_result, unset_result, divert_result, undivert_result",
[
(fake_hidpp.responses_gestures, 20, None, None, None, None, None, None),
(fake_hidpp.responses_gestures, 1, True, False, "01", "00", "01", "00"),
(fake_hidpp.responses_gestures, 45, False, None, "01", "00", None, None),
],
)
def test_Gesture_set(responses, gest, enabled, diverted, set_result, unset_result, divert_result, undivert_result):
device = fake_hidpp.Device("GESTURE", responses=responses, feature=hidpp20_constants.SupportedFeature.GESTURE_2)
gestures = _hidpp20.get_gestures(device)
gesture = gestures.gesture(gest)
assert gesture.enabled() == enabled
assert gesture.diverted() == diverted
assert gesture.set(True) == (bytes.fromhex(set_result) if set_result is not None else None)
assert gesture.set(False) == (bytes.fromhex(unset_result) if unset_result is not None else None)
assert gesture.divert(True) == (bytes.fromhex(divert_result) if divert_result is not None else None)
assert gesture.divert(False) == (bytes.fromhex(undivert_result) if undivert_result is not None else None)
@pytest.mark.parametrize(
"responses, prm, id, index, size, value, default_value, write1, write2",
[
(fake_hidpp.responses_gestures, 4, common.NamedInt(4, "ScaleFactor"), 0, 2, 256, 256, "0080", "0180"),
],
)
def test_Param(responses, prm, id, index, size, value, default_value, write1, write2):
device = fake_hidpp.Device("GESTURE", responses=responses, feature=hidpp20_constants.SupportedFeature.GESTURE_2)
gestures = _hidpp20.get_gestures(device)
param = gestures.param(prm)
assert param.id == id
assert param.index == index
assert param.size == size
assert param.value == value
assert param.default_value == default_value
assert str(param) == id
assert int(param) == id
assert param.write(bytes.fromhex(write1)).hex().upper() == f"{index:02X}" + write1 + "FF"
assert param.write(bytes.fromhex(write2)).hex().upper() == f"{index:02X}" + write2 + "FF"
@pytest.mark.parametrize(
"responses, id, s, byte_count, value, string",
[
(fake_hidpp.responses_gestures, 1, "DVI field width", 1, 8, "[DVI field width=8]"),
(fake_hidpp.responses_gestures, 2, "field widths", 1, 8, "[field widths=8]"),
(fake_hidpp.responses_gestures, 3, "period unit", 2, 2048, "[period unit=2048]"),
],
)
def test_Spec(responses, id, s, byte_count, value, string):
device = fake_hidpp.Device("GESTURE", responses=responses, feature=hidpp20_constants.SupportedFeature.GESTURE_2)
gestures = _hidpp20.get_gestures(device)
spec = gestures.specs[id]
assert spec.id == id
assert spec.spec == s
assert spec.byte_count == byte_count
assert spec.value == value
assert repr(spec) == string
def test_Gestures():
device = fake_hidpp.Device(
"GESTURES", responses=fake_hidpp.responses_gestures, feature=hidpp20_constants.SupportedFeature.GESTURE_2
)
gestures = _hidpp20.get_gestures(device)
assert gestures
assert len(gestures.gestures) == 17
assert gestures.gesture(20) == gestures.gestures[20]
assert gestures.gesture_enabled(20) is None
assert gestures.gesture_enabled(1) is True
assert gestures.gesture_enabled(45) is False
assert gestures.enable_gesture(20) is None
assert gestures.enable_gesture(45) == bytes.fromhex("01")
assert gestures.disable_gesture(20) is None
assert gestures.disable_gesture(45) == bytes.fromhex("00")
assert len(gestures.params) == 1
assert gestures.param(4) == gestures.params[4]
assert gestures.get_param(4) == 256
assert gestures.set_param(4, 128) is None
assert len(gestures.specs) == 5
assert gestures.specs[2].value == 8
assert gestures.specs[4].value == 4
responses_backlight = [
fake_hidpp.Response("010118000001020003000400", 0x0400),
fake_hidpp.Response("0101FF00020003000400", 0x0410, "0101FF00020003000400"),
]
device_backlight = fake_hidpp.Device(
"BACKLIGHT", responses=responses_backlight, feature=hidpp20_constants.SupportedFeature.BACKLIGHT2
)
def test_Backlight():
backlight = _hidpp20.get_backlight(device_backlight)
result = backlight.write()
assert backlight
assert backlight.auto_supported
assert backlight.temp_supported
assert not backlight.perm_supported
assert backlight.dho == 0x0002
assert backlight.dhi == 0x0003
assert backlight.dpow == 0x0004
assert result is not None
@pytest.mark.parametrize(
"hex, ID, color, speed, period, intensity, ramp, form",
[
("FFFFFFFFFFFFFFFFFFFFFF", None, None, None, None, None, None, None),
("0000000000000000000000", common.NamedInt(0x0, "Disabled"), None, None, None, None, None, None),
("0120304010000000000000", common.NamedInt(0x1, "Static"), 0x203040, None, None, None, 0x10, None),
("0220304010000000000000", common.NamedInt(0x2, "Pulse"), 0x203040, 0x10, None, None, None, None),
("0800000000000000000000", common.NamedInt(0x8, "Boot"), None, None, None, None, None, None),
("0300000000005000000000", common.NamedInt(0x3, "Cycle"), None, None, 0x5000, 0x00, None, None),
("0A20304010005020000000", common.NamedInt(0xA, "Breathe"), 0x203040, None, 0x1000, 0x20, None, 0x50),
("0B20304000100000000000", common.NamedInt(0xB, "Ripple"), 0x203040, None, 0x1000, None, None, None),
("0A01020300500407000000", common.NamedInt(0xA, "Breathe"), 0x010203, None, 0x0050, 0x07, None, 0x04),
],
)
def test_LEDEffectSetting(hex, ID, color, speed, period, intensity, ramp, form):
byt = bytes.fromhex(hex)
setting = hidpp20.LEDEffectSetting.from_bytes(byt)
assert setting.ID == ID
if ID is None:
assert setting.bytes == byt
else:
assert getattr(setting, "color", None) == color
assert getattr(setting, "speed", None) == speed
assert getattr(setting, "period", None) == period
assert getattr(setting, "intensity", None) == intensity
assert getattr(setting, "ramp", None) == ramp
assert getattr(setting, "form", None) == form
assert setting.to_bytes() == byt
assert yaml.safe_load(yaml.dump(setting)) == setting
assert yaml.safe_load(str(setting)) == setting
@pytest.mark.parametrize(
"feature, function, response, ID, capabilities, period",
[
[
hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS,
0x20,
fake_hidpp.Response("0102000300040005", 0x0420, "010200"),
3,
4,
5,
],
[
hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS,
0x20,
fake_hidpp.Response("0102000700080009", 0x0420, "010200"),
7,
8,
9,
],
],
)
def test_LEDEffectInfo(feature, function, response, ID, capabilities, period):
device = fake_hidpp.Device(feature=feature, responses=[response])
info = hidpp20.LEDEffectInfo(feature, function, device, 1, 2)
assert info.zindex == 1
assert info.index == 2
assert info.ID == ID
assert info.capabilities == capabilities
assert info.period == period
@pytest.mark.parametrize(
"feature, function, offset, effect_function, responses, index, location, count, id_1",
[
[hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS, 0x10, 0, 0x20, fake_hidpp.zone_responses_1, 0, 1, 2, 0xB],
[hidpp20_constants.SupportedFeature.RGB_EFFECTS, 0x00, 1, 0x00, fake_hidpp.zone_responses_2, 0, 1, 2, 2],
],
)
def test_LEDZoneInfo(feature, function, offset, effect_function, responses, index, location, count, id_1):
device = fake_hidpp.Device(feature=feature, responses=responses, offset=0x07)
zone = hidpp20.LEDZoneInfo(feature, function, offset, effect_function, device, index)
assert zone.index == index
assert zone.location == location
assert zone.count == count
assert len(zone.effects) == count
assert zone.effects[1].ID == id_1
@pytest.mark.parametrize(
"responses, setting, expected_command",
[
[fake_hidpp.zone_responses_1, hidpp20.LEDEffectSetting(ID=0), None],
[fake_hidpp.zone_responses_1, hidpp20.LEDEffectSetting(ID=3, period=0x20, intensity=0x50), "000000000000000020500000"],
[
fake_hidpp.zone_responses_1,
hidpp20.LEDEffectSetting(ID=0xB, color=0x808080, period=0x20),
"000180808000002000000000",
],
],
)
def test_LEDZoneInfo_to_command(responses, setting, expected_command):
device = fake_hidpp.Device(feature=hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS, responses=responses, offset=0x07)
zone = hidpp20.LEDZoneInfo(hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS, 0x10, 0, 0x20, device, 0)
command = zone.to_command(setting)
assert command == (bytes.fromhex(expected_command) if expected_command is not None else None)
@pytest.mark.parametrize(
"feature, cls, responses, readable, count, count_0",
[
[
hidpp20_constants.SupportedFeature.COLOR_LED_EFFECTS,
hidpp20.LEDEffectsInfo,
fake_hidpp.effects_responses_1,
1,
1,
2,
],
[hidpp20_constants.SupportedFeature.RGB_EFFECTS, hidpp20.RGBEffectsInfo, fake_hidpp.effects_responses_2, 1, 1, 2],
],
)
def test_LED_RGB_EffectsInfo(feature, cls, responses, readable, count, count_0):
device = fake_hidpp.Device(feature=feature, responses=responses, offset=0x07)
effects = cls(device)
assert effects.readable == readable
assert effects.count == count
assert effects.zones[0].count == count_0
@pytest.mark.parametrize(
"hex, behavior, sector, address, typ, val, modifiers, data, byt",
[
("05010203", 0x0, 0x501, 0x0203, None, None, None, None, None),
("15020304", 0x1, 0x502, 0x0304, None, None, None, None, None),
("8000FFFF", 0x8, None, None, 0x00, None, None, None, None),
("80010102", 0x8, None, None, 0x01, 0x0102, None, None, None),
("80020454", 0x8, None, None, 0x02, 0x54, 0x04, None, None),
("80030454", 0x8, None, None, 0x03, 0x0454, None, None, None),
("900AFF01", 0x9, None, None, None, 0x0A, None, 0x01, None),
("709090A0", 0x7, None, None, None, None, None, None, b"\x70\x90\x90\xa0"),
],
)
def test_button_bytes(hex, behavior, sector, address, typ, val, modifiers, data, byt):
button = hidpp20.Button.from_bytes(bytes.fromhex(hex))
assert getattr(button, "behavior", None) == behavior
assert getattr(button, "sector", None) == sector
assert getattr(button, "address", None) == address
assert getattr(button, "type", None) == typ
assert getattr(button, "value", None) == val
assert getattr(button, "modifiers", None) == modifiers
assert getattr(button, "data", None) == data
assert getattr(button, "bytes", None) == byt
assert button.to_bytes().hex().upper() == hex
assert yaml.safe_load(yaml.dump(button)).to_bytes().hex().upper() == hex
hex1 = (
"01010290018003000700140028FFFFFF"
"FFFF0000000000000000000000000000"
"8000FFFF900AFF00800204548000FFFF"
"900AFF00800204548000FFFF900AFF00"
"800204548000FFFF900AFF0080020454"
"8000FFFF900AFF00800204548000FFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"54004500370000000000000000000000"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
"0A01020300500407000000FFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFF7C81"
)
hex2 = (
"01010290018003000700140028FFFFFF"
"FFFF0000000000000000000000000000"
"8000FFFF900AFF00800204548000FFFF"
"900AFF00800204548000FFFF900AFF00"
"800204548000FFFF900AFF0080020454"
"8000FFFF900AFF00800204548000FFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"0A01020300500407000000FFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFF27C9"
)
hex3 = (
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
"FFFFFFFFFFFFFFFFFFFFFFFFFF2307"
)
@pytest.mark.parametrize(
"hex, name, sector, enabled, buttons, gbuttons, resolutions, button, lighting",
[
(hex1, "TE7", 2, 1, 16, 0, [0x0190, 0x0380, 0x0700, 0x1400, 0x2800], "8000FFFF", "0A01020300500407000000"),
(hex2, "", 2, 1, 16, 0, [0x0190, 0x0380, 0x0700, 0x1400, 0x2800], "8000FFFF", "0A01020300500407000000"),
(hex3, "", 2, 1, 16, 0, [0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF], "FFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFF"),
],
)
def test_OnboardProfile_bytes(hex, name, sector, enabled, buttons, gbuttons, resolutions, button, lighting):
profile = hidpp20.OnboardProfile.from_bytes(sector, enabled, buttons, gbuttons, bytes.fromhex(hex))
assert profile.name == name
assert profile.sector == sector
assert profile.resolutions == resolutions
assert profile.buttons[0].to_bytes().hex().upper() == button
assert profile.lighting[0].to_bytes().hex().upper() == lighting
assert profile.to_bytes(len(hex) // 2).hex().upper() == hex
assert yaml.safe_load(yaml.dump(profile)).to_bytes(len(hex) // 2).hex().upper() == hex
@pytest.mark.parametrize(
"responses, name, count, buttons, gbuttons, sectors, size",
[
(fake_hidpp.responses_profiles, "ONB", 1, 2, 2, 1, 254),
(fake_hidpp.responses_profiles_rom, "ONB", 1, 2, 2, 1, 254),
(fake_hidpp.responses_profiles_rom_2, "ONB", 1, 2, 2, 1, 254),
],
)
def test_OnboardProfiles_device(responses, name, count, buttons, gbuttons, sectors, size):
device = fake_hidpp.Device(
name, True, 4.5, responses=responses, feature=hidpp20_constants.SupportedFeature.ONBOARD_PROFILES, offset=0x9
)
device._profiles = None
profiles = _hidpp20.get_profiles(device)
assert profiles
assert profiles.version == hidpp20.OnboardProfilesVersion
assert profiles.name == name
assert profiles.count == count
assert profiles.buttons == buttons
assert profiles.gbuttons == gbuttons
assert profiles.sectors == sectors
assert profiles.size == size
assert len(profiles.profiles) == count
assert yaml.safe_load(yaml.dump(profiles)).to_bytes().hex() == profiles.to_bytes().hex()
| 35,379 | Python | .py | 746 | 41.607239 | 127 | 0.694871 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,513 | test_notifications.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_notifications.py | import pytest
from logitech_receiver import notifications
from logitech_receiver.base import HIDPPNotification
from logitech_receiver.common import Notification
from logitech_receiver.hidpp10_constants import BoltPairingError
from logitech_receiver.hidpp10_constants import PairingError
from logitech_receiver.hidpp10_constants import Registers
from logitech_receiver.receiver import Receiver
class MockLowLevelInterface:
def open_path(self, path):
pass
def find_paired_node_wpid(self, receiver_path: str, index: int):
pass
def ping(self, handle, number, long_message=False):
pass
def request(self, handle, devnumber, request_id, *params, **kwargs):
pass
@pytest.mark.parametrize(
"sub_id, notification_data, expected_error, expected_new_device",
[
(Registers.DISCOVERY_STATUS_NOTIFICATION, b"\x01", BoltPairingError.DEVICE_TIMEOUT, None),
(Registers.PAIRING_STATUS_NOTIFICATION, b"\x02", BoltPairingError.FAILED, None),
(Notification.PAIRING_LOCK, b"\x01", PairingError.DEVICE_TIMEOUT, None),
(Notification.PAIRING_LOCK, b"\x02", PairingError.DEVICE_NOT_SUPPORTED, None),
(Notification.PAIRING_LOCK, b"\x03", PairingError.TOO_MANY_DEVICES, None),
(Notification.PAIRING_LOCK, b"\x06", PairingError.SEQUENCE_TIMEOUT, None),
],
)
def test_process_receiver_notification(sub_id, notification_data, expected_error, expected_new_device):
receiver: Receiver = Receiver(MockLowLevelInterface(), None, {}, True, None, None)
notification = HIDPPNotification(0, 0, sub_id, 0, notification_data)
result = notifications._process_receiver_notification(receiver, notification)
assert result
assert receiver.pairing.error == expected_error
assert receiver.pairing.new_device is expected_new_device
| 1,824 | Python | .py | 35 | 47.057143 | 103 | 0.759415 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,514 | test_device.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_device.py | ## Copyright (C) 2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from dataclasses import dataclass
from functools import partial
from typing import Optional
import pytest
from logitech_receiver import common
from logitech_receiver import device
from logitech_receiver import hidpp20
from . import fake_hidpp
class LowLevelInterfaceFake:
def __init__(self, responses=None):
self.responses = responses
def open_path(self, path):
return fake_hidpp.open_path(path)
def find_paired_node(self, receiver_path: str, index: int, timeout: int):
return None
def request(self, response, *args, **kwargs):
func = partial(fake_hidpp.request, self.responses)
return func(response, *args, **kwargs)
def ping(self, response, *args, **kwargs):
func = partial(fake_hidpp.ping, self.responses)
return func(response, *args, **kwargs)
def close(self, *args, **kwargs):
pass
@dataclass
class DeviceInfoStub:
path: str
product_id: str
vendor_id: int = 1133
hidpp_short: bool = False
hidpp_long: bool = True
bus_id: int = 0x0003 # USB
serial: str = "aa:aa:aa;aa"
di_bad_handle = DeviceInfoStub(None, product_id="CCCC")
di_error = DeviceInfoStub(11, product_id="CCCC")
di_CCCC = DeviceInfoStub("11", product_id="CCCC")
di_C318 = DeviceInfoStub("11", product_id="C318")
di_B530 = DeviceInfoStub("11", product_id="B350", bus_id=0x0005)
di_C068 = DeviceInfoStub("11", product_id="C06B")
di_C08A = DeviceInfoStub("11", product_id="C08A")
di_DDDD = DeviceInfoStub("11", product_id="DDDD")
@pytest.mark.parametrize(
"device_info, responses, expected_success",
[
(di_bad_handle, fake_hidpp.r_empty, None),
(di_error, fake_hidpp.r_empty, False),
(di_CCCC, fake_hidpp.r_empty, True),
],
)
def test_create_device(device_info, responses, expected_success):
low_level_mock = LowLevelInterfaceFake(responses)
if expected_success is None:
with pytest.raises(PermissionError):
device.create_device(low_level_mock, device_info)
elif not expected_success:
with pytest.raises(TypeError):
device.create_device(low_level_mock, device_info)
else:
test_device = device.create_device(low_level_mock, device_info)
assert bool(test_device) == expected_success
@pytest.mark.parametrize(
"device_info, responses, expected_codename, expected_name, expected_kind",
[(di_CCCC, fake_hidpp.r_empty, "?? (CCCC)", "Unknown device CCCC", "?")],
)
def test_device_name(device_info, responses, expected_codename, expected_name, expected_kind):
low_level = LowLevelInterfaceFake(responses)
test_device = device.create_device(low_level, device_info)
assert test_device.codename == expected_codename
assert test_device.name == expected_name
assert test_device.kind == expected_kind
@pytest.mark.parametrize(
"device_info, responses, handle, _name, _codename, number, protocol, registers",
zip(
[di_CCCC, di_C318, di_B530, di_C068, di_C08A, di_DDDD],
[
fake_hidpp.r_empty,
fake_hidpp.r_keyboard_1,
fake_hidpp.r_keyboard_2,
fake_hidpp.r_mouse_1,
fake_hidpp.r_mouse_2,
fake_hidpp.r_mouse_3,
],
[0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
[None, "Illuminated Keyboard", "Craft Advanced Keyboard", "G700 Gaming Mouse", "MX Vertical Wireless Mouse", None],
[None, "Illuminated", "Craft", "G700", "MX Vertical", None],
[0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF],
[1.0, 1.0, 4.5, 1.0, 4.5, 4.5],
[[], [], [], (common.NamedInt(7, "battery status"), common.NamedInt(81, "three leds")), [], []],
),
)
def test_device_info(device_info, responses, handle, _name, _codename, number, protocol, registers):
test_device = device.Device(LowLevelInterfaceFake(responses), None, None, None, handle=handle, device_info=device_info)
assert test_device.handle == handle
assert test_device._name == _name
assert test_device._codename == _codename
assert test_device.number == number
assert test_device._protocol == protocol
assert test_device.registers == registers
assert bool(test_device)
test_device.__del__()
assert not bool(test_device)
@dataclass
class FakeReceiver:
path: str = "11"
handle: int = 0x11
codename: Optional[str] = None
def device_codename(self, number):
return self.codename
def __contains__(self, dev):
return True
pi_CCCC = {"wpid": "CCCC", "kind": 0, "serial": None, "polling": "1ms", "power_switch": "top"}
pi_2011 = {"wpid": "2011", "kind": 1, "serial": "1234", "polling": "2ms", "power_switch": "bottom"}
pi_4066 = {"wpid": "4066", "kind": 1, "serial": "5678", "polling": "4ms", "power_switch": "left"}
pi_1007 = {"wpid": "1007", "kind": 2, "serial": "1234", "polling": "8ms", "power_switch": "right"}
pi_407B = {"wpid": "407B", "kind": 2, "serial": "5678", "polling": "1ms", "power_switch": "left"}
pi_DDDD = {"wpid": "DDDD", "kind": 2, "serial": "1234", "polling": "2ms", "power_switch": "top"}
@pytest.mark.parametrize(
"number, pairing_info, responses, handle, _name, codename, p, p2, name",
zip(
range(1, 7),
[pi_CCCC, pi_2011, pi_4066, pi_1007, pi_407B, pi_DDDD],
[
fake_hidpp.r_empty,
fake_hidpp.r_keyboard_1,
fake_hidpp.r_keyboard_2,
fake_hidpp.r_mouse_1,
fake_hidpp.r_mouse_2,
fake_hidpp.r_mouse_3,
],
[0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
[None, "Wireless Keyboard K520", "Craft Advanced Keyboard", "MX Air", "MX Vertical Wireless Mouse", None],
["CODE", "K520", "Craft", "MX Air", "MX Vertical", "CODE"],
[None, 1.0, 4.5, 1.0, 4.5, None],
[1.0, 1.0, 4.5, 1.0, 4.5, 4.5],
[
"CODE",
"Wireless Keyboard K520",
"Craft Advanced Keyboard",
"MX Air",
"MX Vertical Wireless Mouse",
"ABABABABABABABADED",
],
),
)
def test_device_receiver(number, pairing_info, responses, handle, _name, codename, p, p2, name):
low_level = LowLevelInterfaceFake(responses)
low_level.request = partial(fake_hidpp.request, fake_hidpp.replace_number(responses, number))
low_level.ping = partial(fake_hidpp.ping, fake_hidpp.replace_number(responses, number))
test_device = device.Device(low_level, FakeReceiver(codename="CODE"), number, True, pairing_info, handle=handle)
test_device.receiver.device = test_device
assert test_device.handle == handle
assert test_device._name == _name
assert test_device.codename == codename
assert test_device.number == number
assert test_device._protocol == p
assert test_device.protocol == p2
assert test_device.codename == codename
assert test_device.name == name
assert test_device == test_device
assert not (test_device != test_device)
assert bool(test_device)
test_device.__del__()
@pytest.mark.parametrize(
"number, info, responses, handle, unitId, modelId, tid, kind, firmware, serial, id, psl, rate",
zip(
range(1, 7),
[pi_CCCC, pi_2011, pi_4066, pi_1007, pi_407B, pi_DDDD],
[
fake_hidpp.r_empty,
fake_hidpp.r_keyboard_1,
fake_hidpp.r_keyboard_2,
fake_hidpp.r_mouse_1,
fake_hidpp.r_mouse_2,
fake_hidpp.r_mouse_3,
],
[None, 0x11, 0x11, 0x11, 0x11, 0x11],
[None, None, "12345678", None, None, "12345679"], # unitId
[None, None, "1234567890AB", None, None, "123456780000"], # modelId
[None, None, {"btid": "1234", "wpid": "5678", "usbid": "90AB"}, None, None, {"usbid": "1234"}], # tid_map
["?", 1, 1, 2, 2, 2], # kind
[(), True, (), (), (), True], # firmware
[None, "1234", "5678", "1234", "5678", "1234"], # serial
["", "1234", "12345678", "1234", "5678", "12345679"], # id
["top", "bottom", "left", "right", "left", "top"], # power switch location
["1ms", "2ms", "4ms", "8ms", "1ms", "9ms"], # polling rate
),
)
def test_device_ids(number, info, responses, handle, unitId, modelId, tid, kind, firmware, serial, id, psl, rate):
low_level = LowLevelInterfaceFake(responses)
low_level.request = partial(fake_hidpp.request, fake_hidpp.replace_number(responses, number))
low_level.ping = partial(fake_hidpp.ping, fake_hidpp.replace_number(responses, number))
test_device = device.Device(low_level, FakeReceiver(), number, True, info, handle=handle)
assert test_device.unitId == unitId
assert test_device.modelId == modelId
assert test_device.tid_map == tid
assert test_device.kind == kind
assert test_device.firmware == firmware or len(test_device.firmware) > 0 and firmware is True
assert test_device.id == id
assert test_device.power_switch_location == psl
assert test_device.polling_rate == rate
class FakeDevice(device.Device): # a fully functional Device but its HID++ functions look at local data
def __init__(self, responses, *args, **kwargs):
self.responses = responses
super().__init__(LowLevelInterfaceFake(responses), *args, **kwargs)
request = fake_hidpp.Device.request
ping = fake_hidpp.Device.ping
@pytest.mark.parametrize(
"device_info, responses, protocol, led, keys, remap, gestures, backlight, profiles",
[
(di_CCCC, fake_hidpp.r_empty, 1.0, type(None), None, None, None, None, None),
(di_C318, fake_hidpp.r_empty, 1.0, type(None), None, None, None, None, None),
(di_B530, fake_hidpp.r_keyboard_1, 1.0, type(None), None, None, None, None, None),
(di_B530, fake_hidpp.r_keyboard_2, 2.0, type(None), 4, 0, 0, None, None),
(di_B530, fake_hidpp.complex_responses_1, 4.5, hidpp20.LEDEffectsInfo, 0, 0, 0, None, None),
(di_B530, fake_hidpp.complex_responses_2, 4.5, hidpp20.RGBEffectsInfo, 8, 3, 1, True, True),
],
)
def test_device_complex(device_info, responses, protocol, led, keys, remap, gestures, backlight, profiles, mocker):
test_device = FakeDevice(responses, None, None, True, device_info=device_info)
test_device._name = "TestDevice"
test_device._protocol = protocol
spy_request = mocker.spy(test_device, "request")
assert type(test_device.led_effects) == led
if keys is None:
assert test_device.keys == keys
else:
assert len(test_device.keys) == keys
if remap is None:
assert test_device.remap_keys == remap
else:
assert len(test_device.remap_keys) == remap
assert (test_device.gestures is None) == (gestures is None)
assert (test_device.backlight is None) == (backlight is None)
assert (test_device.profiles is None) == (profiles is None)
test_device.set_configuration(55)
if protocol > 1.0:
spy_request.assert_called_with(0x210, 55, no_reply=False)
test_device.reset()
if protocol > 1.0:
spy_request.assert_called_with(0x210, 0, no_reply=False)
@pytest.mark.parametrize(
"device_info, responses, protocol, p, persister, settings",
[
(di_CCCC, fake_hidpp.r_empty, 1.0, None, None, 0),
(di_C318, fake_hidpp.r_empty, 1.0, {}, {}, 0),
(di_C318, fake_hidpp.r_keyboard_1, 1.0, {"n": "n"}, {"n": "n"}, 1),
(di_B530, fake_hidpp.r_keyboard_2, 4.5, {"m": "m"}, {"m": "m"}, 1),
(di_C068, fake_hidpp.r_mouse_1, 1.0, {"o": "o"}, {"o": "o"}, 2),
(di_C08A, fake_hidpp.r_mouse_2, 4.5, {"p": "p"}, {"p": "p"}, 0),
],
)
def test_device_settings(device_info, responses, protocol, p, persister, settings, mocker):
mocker.patch("solaar.configuration.persister", return_value=p)
test_device = FakeDevice(responses, None, None, True, device_info=device_info)
test_device._name = "TestDevice"
test_device._protocol = protocol
assert test_device.persister == persister
assert len(test_device.settings) == settings
@pytest.mark.parametrize(
"device_info, responses, protocol, battery, changed",
[
(di_C318, fake_hidpp.r_empty, 1.0, None, {"active": True, "alert": 0, "reason": None}),
(
di_C318,
fake_hidpp.r_keyboard_1,
1.0,
common.Battery(50, None, 0, None),
{"active": True, "alert": 0, "reason": None},
),
(
di_B530,
fake_hidpp.r_keyboard_2,
4.5,
common.Battery(18, 52, None, None),
{"active": True, "alert": 0, "reason": None},
),
],
)
def test_device_battery(device_info, responses, protocol, battery, changed, mocker):
test_device = FakeDevice(responses, None, None, online=True, device_info=device_info)
test_device._name = "TestDevice"
test_device._protocol = protocol
spy_changed = mocker.spy(test_device, "changed")
assert test_device.battery() == battery
test_device.read_battery()
spy_changed.assert_called_with(**changed)
| 13,801 | Python | .py | 300 | 39.74 | 123 | 0.644206 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,515 | test_diversion.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_diversion.py | import textwrap
from unittest import mock
from unittest.mock import mock_open
import pytest
from logitech_receiver import diversion
from logitech_receiver.base import HIDPPNotification
from logitech_receiver.hidpp20_constants import SupportedFeature
@pytest.fixture
def rule_config():
rule_content = """
%YAML 1.3
---
- MouseGesture: Mouse Left
- KeyPress:
- [Control_L, Alt_L, Left]
- click
...
---
- MouseGesture: Mouse Up
- KeyPress:
- [Super_L, Up]
- click
...
---
- Test: [thumb_wheel_up, 10]
- KeyPress:
- [Control_L, Page_Down]
- click
...
---
"""
return textwrap.dedent(rule_content)
def test_load_rule_config(rule_config):
expected_rules = [
[
diversion.MouseGesture,
diversion.KeyPress,
],
[diversion.MouseGesture, diversion.KeyPress],
[diversion.Test, diversion.KeyPress],
]
with mock.patch("builtins.open", new=mock_open(read_data=rule_config)):
loaded_rules = diversion._load_rule_config(file_path=mock.Mock())
assert len(loaded_rules.components) == 2 # predefined and user configured rules
user_configured_rules = loaded_rules.components[0]
assert isinstance(user_configured_rules, diversion.Rule)
for components, expected_components in zip(user_configured_rules.components, expected_rules):
for component, expected_component in zip(components.components, expected_components):
assert isinstance(component, expected_component)
def test_diversion_rule():
args = [
{
"Rule": [ # Implement problematic keys for Craft and MX Master
{"Rule": [{"Key": ["Brightness Down", "pressed"]}, {"KeyPress": "XF86_MonBrightnessDown"}]},
{"Rule": [{"Key": ["Brightness Up", "pressed"]}, {"KeyPress": "XF86_MonBrightnessUp"}]},
]
},
]
rule = diversion.Rule(args)
assert len(rule.components) == 1
root_rule = rule.components[0]
assert isinstance(root_rule, diversion.Rule)
assert len(root_rule.components) == 2
for component in root_rule.components:
assert isinstance(component, diversion.Rule)
assert len(component.components) == 2
key = component.components[0]
assert isinstance(key, diversion.Key)
key = component.components[1]
assert isinstance(key, diversion.KeyPress)
def test_key_is_down():
result = diversion.key_is_down(key=diversion.CONTROL.G2)
assert result is False
def test_feature():
expected_data = {"Feature": "CONFIG CHANGE"}
result = diversion.Feature("CONFIG_CHANGE")
assert result.data() == expected_data
@pytest.mark.parametrize(
"feature, data",
[
(
SupportedFeature.REPROG_CONTROLS_V4,
[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
),
(SupportedFeature.GKEY, [0x01, 0x02, 0x03, 0x04]),
(SupportedFeature.MKEYS, [0x01, 0x02, 0x03, 0x04]),
(SupportedFeature.MR, [0x01, 0x02, 0x03, 0x04]),
(SupportedFeature.THUMB_WHEEL, [0x01, 0x02, 0x03, 0x04, 0x05]),
(SupportedFeature.DEVICE_UNIT_ID, [0x01, 0x02, 0x03, 0x04, 0x05]),
],
)
def test_process_notification(feature, data):
device_mock = mock.Mock()
notification = HIDPPNotification(
report_id=0x01,
devnumber=1,
sub_id=0x13,
address=0x00,
data=bytes(data),
)
diversion.process_notification(device_mock, notification, feature)
| 3,558 | Python | .py | 101 | 28.663366 | 108 | 0.650831 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,516 | test_receiver.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_receiver.py | from dataclasses import dataclass
from functools import partial
from unittest import mock
import pytest
from logitech_receiver import base
from logitech_receiver import common
from logitech_receiver import exceptions
from logitech_receiver import receiver
from . import fake_hidpp
class LowLevelInterfaceFake:
def __init__(self, responses=None):
self.responses = responses
def open_path(self, path):
return fake_hidpp.open_path(path)
def product_information(self, usb_id: int) -> dict:
return base.product_information(usb_id)
def find_paired_node(self, receiver_path: str, index: int, timeout: int):
return None
def request(self, response, *args, **kwargs):
func = partial(fake_hidpp.request, self.responses)
return func(response, *args, **kwargs)
def ping(self, response, *args, **kwargs):
func = partial(fake_hidpp.ping, self.responses)
return func(response, *args, **kwargs)
def close(self, *args, **kwargs):
pass
@pytest.mark.parametrize(
"index, expected_kind",
[
(0, None),
(1, 2), # mouse
(2, 2), # mouse
(3, 1), # keyboard
(4, 3), # numpad
(5, None),
],
)
def test_get_kind_from_index(index, expected_kind):
mock_receiver = mock.Mock()
if expected_kind:
assert receiver._get_kind_from_index(mock_receiver, index) == expected_kind
else:
with pytest.raises(exceptions.NoSuchDevice):
receiver._get_kind_from_index(mock_receiver, index)
@dataclass
class DeviceInfo:
path: str
vendor_id: int = 1133
product_id: int = 0xC52B
responses_unifying = [
fake_hidpp.Response("000000", 0x8003, "FF"),
fake_hidpp.Response("000300", 0x8102),
fake_hidpp.Response("0316CC9CB40506220000000000000000", 0x83B5, "03"),
fake_hidpp.Response("20200840820402020700000000000000", 0x83B5, "20"),
fake_hidpp.Response("21211420110400010D1A000000000000", 0x83B5, "21"),
fake_hidpp.Response("22220840660402010700000000020000", 0x83B5, "22"),
fake_hidpp.Response("30198E3EB80600000001000000000000", 0x83B5, "30"),
fake_hidpp.Response("31811119511A40000002000000000000", 0x83B5, "31"),
fake_hidpp.Response("32112C46EA1E40000003000000000000", 0x83B5, "32"),
fake_hidpp.Response("400B4D58204D61737465722033000000", 0x83B5, "40"),
fake_hidpp.Response("41044B35323020202020202020202020", 0x83B5, "41"),
fake_hidpp.Response("42054372616674000000000000000000", 0x83B5, "42"),
fake_hidpp.Response("012411", 0x81F1, "01"),
fake_hidpp.Response("020036", 0x81F1, "02"),
fake_hidpp.Response("03AAAC", 0x81F1, "03"),
fake_hidpp.Response("040209", 0x81F1, "04"),
]
responses_c534 = [
fake_hidpp.Response("000000", 0x8003, "FF", handle=0x12),
fake_hidpp.Response("000209", 0x8102, handle=0x12),
fake_hidpp.Response("0316CC9CB40502220000000000000000", 0x83B5, "03", handle=0x12),
fake_hidpp.Response("00000445AB", 0x83B5, "04", handle=0x12),
]
responses_unusual = [
fake_hidpp.Response("000000", 0x8003, "FF", handle=0x13),
fake_hidpp.Response("000300", 0x8102, handle=0x13),
fake_hidpp.Response("00000445AB", 0x83B5, "04", handle=0x13),
fake_hidpp.Response("0326CC9CB40508220000000000000000", 0x83B5, "03", handle=0x13),
]
responses_lacking = [
fake_hidpp.Response("000000", 0x8003, "FF", handle=0x14),
fake_hidpp.Response("000300", 0x8102, handle=0x14),
]
mouse_info = {
"kind": common.NamedInt(2, "mouse"),
"polling": "8ms",
"power_switch": common.NamedInt(1, "base"),
"serial": "198E3EB8",
"wpid": "4082",
}
c534_info = {"kind": common.NamedInt(0, "unknown"), "polling": "", "power_switch": "(unknown)", "serial": None, "wpid": "45AB"}
@pytest.mark.parametrize(
"device_info, responses, handle, serial, max_devices, ",
[
(DeviceInfo(path=None), [], False, None, None),
(DeviceInfo(path=11), [], None, None, None),
(DeviceInfo(path="11"), responses_unifying, 0x11, "16CC9CB4", 6),
(DeviceInfo(path="12", product_id=0xC534), responses_c534, 0x12, "16CC9CB4", 2),
(DeviceInfo(path="12", product_id=0xC539), responses_c534, 0x12, "16CC9CB4", 2),
(DeviceInfo(path="13"), responses_unusual, 0x13, "26CC9CB4", 1),
(DeviceInfo(path="14"), responses_lacking, 0x14, None, 1),
],
)
def test_receiver_factory_create_receiver(device_info, responses, handle, serial, max_devices):
mock_low_level = LowLevelInterfaceFake(responses)
if handle is False:
with pytest.raises(Exception): # noqa: B017
receiver.create_receiver(mock_low_level, device_info, lambda x: x)
elif handle is None:
r = receiver.create_receiver(mock_low_level, device_info, lambda x: x)
assert r is None
else:
r = receiver.create_receiver(mock_low_level, device_info, lambda x: x)
assert r.handle == handle
assert r.serial == serial
assert r.max_devices == max_devices
@pytest.mark.parametrize(
"device_info, responses, firmware, codename, remaining_pairings, pairing_info, count",
[
(DeviceInfo("11"), responses_unifying, 3, "K520", -1, mouse_info, 3),
(DeviceInfo("12", product_id=0xC534), responses_c534, None, None, 4, c534_info, 2),
(DeviceInfo("13", product_id=0xCCCC), responses_unusual, None, None, -1, c534_info, 3),
],
)
def test_receiver_factory_props(device_info, responses, firmware, codename, remaining_pairings, pairing_info, count):
mock_low_level = LowLevelInterfaceFake(responses)
r = receiver.create_receiver(mock_low_level, device_info, lambda x: x)
assert len(r.firmware) == firmware if firmware is not None else firmware is None
assert r.device_codename(2) == codename
assert r.remaining_pairings() == remaining_pairings
assert r.device_pairing_information(1) == pairing_info
assert r.count() == count
@pytest.mark.parametrize(
"device_info, responses, status_str, strng",
[
(DeviceInfo("11"), responses_unifying, "No paired devices.", "<UnifyingReceiver(11,17)>"),
(DeviceInfo("12", product_id=0xC534), responses_c534, "No paired devices.", "<NanoReceiver(12,18)>"),
(DeviceInfo("13", product_id=0xCCCC), responses_unusual, "No paired devices.", "<Receiver(13,19)>"),
],
)
def test_receiver_factory_string(device_info, responses, status_str, strng):
mock_low_level = LowLevelInterfaceFake(responses)
r = receiver.create_receiver(mock_low_level, device_info, lambda x: x)
assert r.status_string() == status_str
assert str(r) == strng
@pytest.mark.parametrize(
"device_info, responses",
[
(DeviceInfo("14"), responses_lacking),
(DeviceInfo("14", product_id="C534"), responses_lacking),
],
)
def test_receiver_factory_no_device(device_info, responses):
mock_low_level = LowLevelInterfaceFake(responses)
r = receiver.create_receiver(mock_low_level, device_info, lambda x: x)
with pytest.raises(exceptions.NoSuchDevice):
r.device_pairing_information(1)
| 7,078 | Python | .py | 157 | 39.713376 | 127 | 0.686366 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,517 | test_desktop_notifications.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_desktop_notifications.py | from unittest import mock
from logitech_receiver import desktop_notifications
def test_notifications_available():
result = desktop_notifications.notifications_available()
assert not result
def test_init():
assert not desktop_notifications.init()
def test_uninit():
assert desktop_notifications.uninit() is None
def test_show():
dev = mock.MagicMock()
reason = "unknown"
assert desktop_notifications.show(dev, reason) is None
| 463 | Python | .py | 13 | 31.692308 | 60 | 0.772727 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,518 | test_common.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_common.py | from enum import IntFlag
import pytest
import yaml
from logitech_receiver import common
def test_crc16():
value = b"123456789"
expected = 0x29B1
result = common.crc16(value)
assert result == expected
def test_named_int():
named_int = common.NamedInt(0x2, "pulse")
assert named_int.name == "pulse"
assert named_int == 2
assert repr(named_int) == "NamedInt(2, 'pulse')"
def test_named_int_comparison():
named_int = common.NamedInt(0, "entry")
named_int_equal = common.NamedInt(0, "entry")
named_int_unequal_name = common.NamedInt(0, "unequal")
named_int_unequal_value = common.NamedInt(5, "entry")
named_int_unequal = common.NamedInt(2, "unequal")
assert named_int == named_int_equal
assert named_int != named_int_unequal_name
assert named_int != named_int_unequal_value
assert named_int != named_int_unequal
assert named_int is not None
assert named_int == 0
assert named_int == "entry"
def test_named_int_comparison_exception():
named_int = common.NamedInt(0, "entry")
with pytest.raises(TypeError):
assert named_int == b"\x00"
def test_named_int_conversions():
named_int = common.NamedInt(2, "two")
assert named_int.bytes() == b"\x00\x02"
assert str(named_int) == "two"
def test_named_int_yaml():
named_int = common.NamedInt(2, "two")
yaml_string = yaml.dump(named_int)
# assert yaml_string == "!NamedInt {name: two, value: 2}\n"
yaml_load = yaml.safe_load(yaml_string)
assert yaml_load == named_int
def test_named_ints():
named_ints = common.NamedInts(empty=0, critical=5, low=20, good=50, full=90)
assert named_ints.empty == 0
assert named_ints.empty.name == "empty"
assert named_ints.critical == 5
assert named_ints.critical.name == "critical"
assert named_ints.low == 20
assert named_ints.low.name == "low"
assert named_ints.good == 50
assert named_ints.good.name == "good"
assert named_ints.full == 90
assert named_ints.full.name == "full"
assert len(named_ints) == 5
assert 5 in named_ints
assert 6 not in named_ints
assert "critical" in named_ints
assert "easy" not in named_ints
assert common.NamedInt(5, "critical") in named_ints
assert common.NamedInt(5, "five") not in named_ints
assert common.NamedInt(6, "critical") not in named_ints
assert named_ints[5] == "critical"
assert named_ints["critical"] == "critical"
assert named_ints[66] is None
assert named_ints["5"] is None
assert len(named_ints[:]) == len(named_ints)
assert len(named_ints[0:100]) == len(named_ints)
assert len(named_ints[5:90]) == 3
assert len(named_ints[5:]) == 4
assert named_ints[90:5] == []
def test_named_ints_fallback():
named_ints = common.NamedInts(empty=0, critical=5, low=20, good=50, full=90)
named_ints._fallback = lambda x: str(x)
fallback = named_ints[80]
assert fallback == common.NamedInt(80, "80")
def test_named_ints_list():
named_ints_list = common.NamedInts.list([0, 5, 20, 50, 90])
assert len(named_ints_list) == 5
assert 50 in named_ints_list
assert 60 not in named_ints_list
def test_named_ints_range():
named_ints_range = common.NamedInts.range(0, 5)
assert len(named_ints_range) == 6
assert 4 in named_ints_range
assert 6 not in named_ints_range
@pytest.mark.parametrize(
"code, expected_flags",
[
(0, []),
(0b0010, ["two"]),
(0b0101, ["one", "three"]),
(0b1001, ["one", "unknown:000008"]),
],
)
def test_named_ints_flag_names(code, expected_flags):
named_ints_flag_bits = common.NamedInts(one=0b001, two=0b010, three=0b100)
flags = list(named_ints_flag_bits.flag_names(code))
assert flags == expected_flags
@pytest.mark.parametrize(
"code, expected_flags",
[
(0, []),
(0b0010, ["two"]),
(0b0101, ["one", "three"]),
(0b1001, ["one", "unknown:000008"]),
],
)
def test_flag_names(code, expected_flags):
class ExampleFlag(IntFlag):
one = 0x1
two = 0x2
three = 0x4
flags = common.flag_names(ExampleFlag, code)
assert list(flags) == expected_flags
def test_named_ints_setitem():
named_ints = common.NamedInts(empty=0, critical=5, low=20, good=50, full=90)
named_ints[55] = "better"
named_ints[60] = common.NamedInt(60, "sixty")
with pytest.raises(TypeError):
named_ints[70] = 70
with pytest.raises(ValueError):
named_ints[70] = "empty"
with pytest.raises(ValueError):
named_ints[50] = "new"
assert named_ints[55] == "better"
assert named_ints[60] == "sixty"
def test_named_ints_other():
named_ints = common.NamedInts(empty=0, critical=5)
named_ints_2 = common.NamedInts(good=50)
union = named_ints.__or__(named_ints_2)
assert list(named_ints) == [common.NamedInt(0, "empty"), common.NamedInt(5, "critical")]
assert len(named_ints) == 2
assert repr(named_ints) == "NamedInts(NamedInt(0, 'empty'), NamedInt(5, 'critical'))"
assert len(union) == 3
assert list(union) == [common.NamedInt(0, "empty"), common.NamedInt(5, "critical"), common.NamedInt(50, "good")]
def test_unsorted_named_ints():
named_ints = common.UnsortedNamedInts(critical=5, empty=0)
named_ints_2 = common.UnsortedNamedInts(good=50)
union = named_ints.__or__(named_ints_2)
unionr = named_ints_2.__or__(named_ints)
assert len(union) == 3
assert list(union) == [common.NamedInt(5, "critical"), common.NamedInt(0, "empty"), common.NamedInt(50, "good")]
assert len(unionr) == 3
assert list(unionr) == [common.NamedInt(50, "good"), common.NamedInt(5, "critical"), common.NamedInt(0, "empty")]
@pytest.mark.parametrize(
"bytes_input, expected_output",
[
(b"\x01\x02\x03\x04", "01020304"),
(b"", ""),
],
)
def test_strhex(bytes_input, expected_output):
result = common.strhex(bytes_input)
assert result == expected_output
def test_bytest2int():
value = b"\x12\x34\x56\x78"
expected = 0x12345678
result = common.bytes2int(value)
assert result == expected
def test_int2bytes():
value = 0x12345678
expected = b"\x12\x34\x56\x78"
result = common.int2bytes(value)
assert result == expected
def test_kw_exception():
e = common.KwException(foo=0, bar="bar")
assert e.foo == 0
assert e.bar == "bar"
@pytest.mark.parametrize(
"status, expected_level, expected_ok, expected_charging, expected_string",
[
(common.BatteryStatus.FULL, common.BatteryLevelApproximation.FULL, True, True, "Battery: full (full)"),
(common.BatteryStatus.ALMOST_FULL, common.BatteryLevelApproximation.GOOD, True, True, "Battery: good (almost full)"),
(common.BatteryStatus.RECHARGING, common.BatteryLevelApproximation.GOOD, True, True, "Battery: good (recharging)"),
(
common.BatteryStatus.SLOW_RECHARGE,
common.BatteryLevelApproximation.LOW,
True,
True,
"Battery: low (slow recharge)",
),
(common.BatteryStatus.DISCHARGING, None, True, False, ""),
],
)
def test_battery(status, expected_level, expected_ok, expected_charging, expected_string):
battery = common.Battery(None, None, status, None)
assert battery.status == status
assert battery.level == expected_level
assert battery.ok() == expected_ok
assert battery.charging() == expected_charging
assert battery.to_str() == expected_string
def test_battery_2():
battery = common.Battery(50, None, common.BatteryStatus.DISCHARGING, None)
assert battery.status == common.BatteryStatus.DISCHARGING
assert battery.level == 50
assert battery.ok()
assert not battery.charging()
assert battery.to_str() == "Battery: 50% (discharging)"
| 7,879 | Python | .py | 198 | 34.39899 | 125 | 0.667237 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,519 | test_base.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_base.py | import struct
import sys
from unittest import mock
import pytest
from logitech_receiver import base
from logitech_receiver import exceptions
from logitech_receiver.base import HIDPP_SHORT_MESSAGE_ID
from logitech_receiver.base import request
from logitech_receiver.hidpp10_constants import ERROR
@pytest.mark.parametrize(
"usb_id, expected_name, expected_receiver_kind",
[
(0xC548, "Bolt Receiver", "bolt"),
(0xC52B, "Unifying Receiver", "unifying"),
(0xC531, "Nano Receiver", "nano"),
(0xC53F, "Lightspeed Receiver", None),
(0xC517, "EX100 Receiver 27 Mhz", "27Mhz"),
],
)
def test_product_information(usb_id, expected_name, expected_receiver_kind):
res = base.product_information(usb_id)
assert res["name"] == expected_name
assert isinstance(res["vendor_id"], int)
assert isinstance(res["product_id"], int)
if expected_receiver_kind:
assert res["receiver_kind"] == expected_receiver_kind
def test_filter_receivers_known():
bus_id = 2
vendor_id = 0x046D
product_id = 0xC548
receiver_info = base._filter_receivers(bus_id, vendor_id, product_id)
assert receiver_info["name"] == "Bolt Receiver"
assert receiver_info["receiver_kind"] == "bolt"
def test_filter_receivers_unknown():
bus_id = 1
vendor_id = 0x046D
product_id = 0xC500
receiver_info = base._filter_receivers(bus_id, vendor_id, product_id)
assert receiver_info["bus_id"] == bus_id
assert receiver_info["product_id"] == product_id
@pytest.mark.parametrize(
"product_id, hidpp_short, hidpp_long",
[
(0xC548, True, False),
(0xC07E, True, False),
(0xC07E, False, True),
(0xA07E, False, True),
(0xA07E, None, None),
(0xA07C, False, False),
],
)
def test_filter_products_of_interest(product_id, hidpp_short, hidpp_long):
bus_id = 3
vendor_id = 0x046D
receiver_info = base._filter_products_of_interest(
bus_id,
vendor_id,
product_id,
hidpp_short=hidpp_short,
hidpp_long=hidpp_long,
)
if not hidpp_short and not hidpp_long:
assert receiver_info is None
else:
assert isinstance(receiver_info["vendor_id"], int)
assert receiver_info["product_id"] == product_id
@pytest.mark.parametrize(
"report_id, sub_id, address, valid_notification",
[
(0x1, 0x72, 0x57, True),
(0x1, 0x40, 0x63, True),
(0x1, 0x40, 0x71, True),
(0x1, 0x80, 0x71, False),
(0x1, 0x00, 0x70, False),
(0x20, 0x09, 0x71, False),
(0x1, 0x37, 0x71, False),
],
)
def test_make_notification(report_id, sub_id, address, valid_notification):
devnumber = 123
data = bytes([sub_id, address, 0x02, 0x03, 0x04])
result = base.make_notification(report_id, devnumber, data)
if valid_notification:
assert isinstance(result, base.HIDPPNotification)
assert result.report_id == report_id
assert result.devnumber == devnumber
assert result.sub_id == sub_id
assert result.address == address
assert result.data == bytes([0x02, 0x03, 0x04])
else:
assert result is None
def test_get_next_sw_id():
res1 = base._get_next_sw_id()
res2 = base._get_next_sw_id()
assert res1 == 2
assert res2 == 3
@pytest.mark.parametrize(
"prefix, error_code, return_error, raise_exception",
[
(b"\x8f", ERROR.invalid_SubID__command, False, False),
(b"\x8f", ERROR.invalid_SubID__command, True, False),
(b"\xff", ERROR.invalid_SubID__command, False, True),
],
)
def test_request_errors(prefix: bytes, error_code: ERROR, return_error: bool, raise_exception: bool):
handle = 0
device_number = 66
next_sw_id = 0x02
reply_data_sw_id = struct.pack("!H", 0x0000 | next_sw_id)
with mock.patch(
"logitech_receiver.base._read",
return_value=(HIDPP_SHORT_MESSAGE_ID, device_number, prefix + reply_data_sw_id + struct.pack("B", error_code)),
), mock.patch("logitech_receiver.base._skip_incoming", return_value=None), mock.patch(
"logitech_receiver.base.write", return_value=None
), mock.patch("logitech_receiver.base._get_next_sw_id", return_value=next_sw_id):
if raise_exception:
with pytest.raises(exceptions.FeatureCallError) as context:
request(handle, device_number, next_sw_id, return_error=return_error)
assert context.value.number == device_number
assert context.value.request == next_sw_id
assert context.value.error == error_code
assert context.value.params == b""
else:
result = request(handle, device_number, next_sw_id, return_error=return_error)
assert result == (error_code if return_error else None)
@pytest.mark.skipif(sys.platform == "darwin", reason="Test only runs on Linux")
@pytest.mark.parametrize(
"simulated_error, expected_result",
[
(ERROR.invalid_SubID__command, 1.0),
(ERROR.resource_error, None),
(ERROR.connection_request_failed, None),
(ERROR.unknown_device, exceptions.NoSuchDevice),
],
)
def test_ping_errors(simulated_error: ERROR, expected_result):
handle = 1
device_number = 1
next_sw_id = 0x05
reply_data_sw_id = struct.pack("!H", 0x0010 | next_sw_id)
with mock.patch(
"logitech_receiver.base._read",
return_value=(HIDPP_SHORT_MESSAGE_ID, device_number, b"\x8f" + reply_data_sw_id + bytes([simulated_error])),
), mock.patch("logitech_receiver.base._get_next_sw_id", return_value=next_sw_id):
if isinstance(expected_result, type) and issubclass(expected_result, Exception):
with pytest.raises(expected_result) as context:
base.ping(handle=handle, devnumber=device_number)
assert context.value.number == device_number
assert context.value.request == struct.unpack("!H", reply_data_sw_id)[0]
else:
result = base.ping(handle=handle, devnumber=device_number)
assert result == expected_result
| 6,135 | Python | .py | 152 | 33.756579 | 119 | 0.657643 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,520 | fake_hidpp.py | pwr-Solaar_Solaar/tests/logitech_receiver/fake_hidpp.py | ## Copyright (C) 2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""HID++ data and functions common to several logitech_receiver test files"""
from __future__ import annotations
import errno
import threading
from dataclasses import dataclass
from dataclasses import field
from struct import pack
from typing import Any
from typing import Optional
from logitech_receiver import device
from logitech_receiver import hidpp20
from solaar import configuration
def open_path(path: Optional[str]) -> int:
if path is None:
raise OSError(errno.EACCES, "Fake access error")
return int(path, 16) # can raise exception
def ping(responses, handle, devnumber, long_message=False):
for r in responses:
if handle == r.handle and devnumber == r.devnumber and r.id == 0x0010:
return r.response
def request(
responses,
handle,
devnumber,
id,
*params,
no_reply=False,
return_error=False,
long_message=False,
protocol=1.0,
):
params = b"".join(pack("B", p) if isinstance(p, int) else p for p in params)
print("REQUEST ", hex(handle), hex(devnumber), hex(id), params.hex())
for r in responses:
if handle == r.handle and devnumber == r.devnumber and r.id == id and bytes.fromhex(r.params) == params:
print("RESPONSE", hex(r.handle), hex(r.devnumber), hex(r.id), r.params, r.response)
return bytes.fromhex(r.response) if r.response is not None else None
@dataclass
class Response:
response: str | float
id: int
params: str = ""
handle: int = 0x11
devnumber: int = 0xFF
no_reply: bool = False
def replace_number(responses, number): # change the devnumber for a list of responses
return [Response(r.response, r.id, r.params, r.handle, number, r.no_reply) for r in responses]
def adjust_responses_index(index, responses): # change index-4 responses to index
return [Response(r.response, r.id - 0x400 + (index << 8), r.params, r.handle, r.devnumber, r.no_reply) for r in responses]
r_empty = [ # a HID++ device with no responses except for ping
Response(1.0, 0x0010), # ping
]
r_keyboard_1 = [ # a HID++ 1.0 keyboard
Response(1.0, 0x0010), # ping
Response("001234", 0x81F1, "01"), # firmware
Response("003412", 0x81F1, "02"), # firmware
Response("002345", 0x81F1, "03"), # firmware
Response("003456", 0x81F1, "04"), # firmware
Response("050050", 0x8107), # battery status
]
r_keyboard_2 = [ # a HID++ 2.0 keyboard
Response(4.2, 0x0010), # ping
Response("010001", 0x0000, "0001"), # feature set at 0x01
Response("020003", 0x0000, "0020"), # CONFIG_CHANGE at 0x02
Response("030001", 0x0000, "0003"), # device information at 0x03
Response("040003", 0x0000, "0100"), # unknown 0100 at 0x04
Response("050003", 0x0000, "1B04"), # reprogrammable keys V4 at 0x05
Response("060003", 0x0000, "0007"), # device friendly name at 0x06
Response("070003", 0x0000, "0005"), # device name at 0x07
Response("080003", 0x0000, "1000"), # battery status at 0x08
Response("08", 0x0100), # 8 features
Response("00010001", 0x0110, "01"), # feature set at 0x01
Response("00200003", 0x0110, "02"), # CONFIG_CHANGE at 0x02
Response("00030001", 0x0110, "03"), # device information at 0x03
Response("01000003", 0x0110, "04"), # unknown 0100 at 0x04
Response("1B040003", 0x0110, "05"), # reprogrammable keys V4 at 0x05
Response("00070003", 0x0000, "06"), # device friendly name at 0x06
Response("00050003", 0x0000, "07"), # device name at 0x07
Response("10000001", 0x0110, "08"), # battery status at 0x02
Response("0212345678000D1234567890ABAA01", 0x0300), # device information
Response("04", 0x0500), # reprogrammable keys V4
Response("00110012AB010203CD00", 0x0510, "00"), # reprogrammable keys V4
Response("01110022AB010203CD00", 0x0510, "01"), # reprogrammable keys V4
Response("00010111AB010203CD00", 0x0510, "02"), # reprogrammable keys V4
Response("03110032AB010204CD00", 0x0510, "03"), # reprogrammable keys V4
Response("00030333AB010203CD00", 0x0510, "04"), # reprogrammable keys V4
Response("12", 0x0600), # friendly namme
Response("004142434445464748494A4B4C4D4E", 0x0610, "00"),
Response("0E4F50515253000000000000000000", 0x0610, "0E"),
Response("12", 0x0700), # name and kind
Response("4142434445464748494A4B4C4D4E4F", 0x0710, "00"),
Response("505152530000000000000000000000", 0x0710, "0F"),
Response("00", 0x0720),
Response("12345678", 0x0800), # battery status
]
r_mouse_1 = [ # a HID++ 1.0 mouse
Response(1.0, 0x0010), # ping
]
r_mouse_2 = [ # a HID++ 2.0 mouse with few responses except for ping
Response(4.2, 0x0010), # ping
]
r_mouse_3 = [ # a HID++ 2.0 mouse
Response(4.5, 0x0010), # ping
Response("010001", 0x0000, "0001"), # feature set at 0x01
Response("020002", 0x0000, "8060"), # report rate at 0x02
Response("040001", 0x0000, "0003"), # device information at 0x04
Response("050002", 0x0000, "0005"), # device type and name at 0x05
Response("08", 0x0100), # 8 features
Response("00010001", 0x0110, "01"), # feature set at 0x01
Response("80600002", 0x0110, "02"), # report rate at 0x02
Response("00030001", 0x0110, "04"), # device information at 0x04
Response("00050002", 0x0110, "05"), # device type and name at 0x05
Response("09", 0x0210), # report rate - current rate
Response("03123456790008123456780000AA01", 0x0400), # device information
Response("0141424302030100", 0x0410, "00"), # firmware 0
Response("0241", 0x0410, "01"), # firmware 1
Response("05", 0x0410, "02"), # firmware 2
Response("12", 0x0500), # name count - 18 characters
Response("414241424142414241424142414241", 0x0510, "00"), # name - first 15 characters
Response("444544000000000000000000000000", 0x0510, "0F"), # name - last 3 characters
]
responses_key = [ # responses for Reprogrammable Keys V4 at 0x05
Response("08", 0x0500), # Reprogrammable Keys V4 count
Response("00500038010001010400000000000000", 0x0510, "00"), # left button
Response("00510039010001010400000000000000", 0x0510, "01"), # right button
Response("0052003A310003070500000000000000", 0x0510, "02"), # middle button
Response("0053003C710002030100000000000000", 0x0510, "03"), # back button
Response("0056003E710002030100000000000000", 0x0510, "04"), # forward button
Response("00C300A9310003070300000000000000", 0x0510, "05"), # smart shift?
Response("00C4009D310003070500000000000000", 0x0510, "06"), # ?
Response("00D700B4A00004000300000000000000", 0x0510, "07"), # ?
Response("00500000000000000000000000000000", 0x0520, "0050"), # left button
Response("00510000000000000000000000000000", 0x0520, "0051"), # ...
Response("00520100500000000000000000000000", 0x0520, "0052"),
Response("00530500000000000000000000000000", 0x0520, "0053"),
Response("00561100000000000000000000000000", 0x0520, "0056"),
Response("00C30000000000000000000000000000", 0x0520, "00C3"),
Response("00C40000500000000000000000000000", 0x0520, "00C4"),
Response("00D70000510000000000000000000000", 0x0520, "00D7"),
Response("0041", 0x0400), # flags
Response("0401", 0x0410), # count
Response("0050", 0x0420, "00FF"), # left button
Response("0051", 0x0420, "01FF"), # right button
Response("0052", 0x0420, "02FF"), # middle button
Response("0053", 0x0420, "03FF"), # back button
Response("0050000100500000", 0x0430, "0050FF"), # left button current
Response("0051000100500001", 0x0430, "0051FF"), # right button current
Response("0052000100500001", 0x0430, "0052FF"), # middle button current
Response("0053000100500001", 0x0430, "0053FF"), # back button current
Response("0050FF01005000", 0x0440, "0050FF01005000"), # left button write
Response("0051FF01005000", 0x0440, "0051FF01005000"), # right button write
Response("0051FF01005100", 0x0440, "0051FF01005100"), # right button set write
]
responses_remap = [ # responses for Persistent Remappable Actions at 0x04 and reprogrammable keys at 0x05
Response("0041", 0x0400),
Response("03", 0x0410),
Response("0301", 0x0410, "00"),
Response("0050", 0x0420, "00FF"),
Response("0050000200010001", 0x0430, "0050FF"), # Left Button
Response("0051", 0x0420, "01FF"),
Response("0051000200010000", 0x0430, "0051FF"), # Left Button
Response("0052", 0x0420, "02FF"),
Response("0052000100510000", 0x0430, "0052FF"), # key DOWN
Response("050002", 0x0000, "1B04"), # REPROGRAMMABLE_KEYS_V4
] + responses_key
responses_gestures = [ # the commented-out messages are not used by either the setting or other testing
Response("4203410141020400320480148C21A301", 0x0400, "0000"), # items
Response("A302A11EA30A4105822C852DAD2AAD2B", 0x0400, "0008"),
Response("8F408F418F434204AF54912282558264", 0x0400, "0010"),
Response("01000000000000000000000000000000", 0x0400, "0018"),
Response("01000000000000000000000000000000", 0x0410, "000101"), # enable
# Response("02000000000000000000000000000000", 0x0410, "000102"),
# Response("04000000000000000000000000000000", 0x0410, "000104"),
# Response("08000000000000000000000000000000", 0x0410, "000108"),
Response("00000000000000000000000000000000", 0x0410, "000110"),
# Response("20000000000000000000000000000000", 0x0410, "000120"),
# Response("40000000000000000000000000000000", 0x0410, "000140"),
# Response("00000000000000000000000000000000", 0x0410, "000180"),
# Response("00000000000000000000000000000000", 0x0410, "010101"),
# Response("00000000000000000000000000000000", 0x0410, "010102"),
# Response("04000000000000000000000000000000", 0x0410, "010104"),
# Response("00000000000000000000000000000000", 0x0410, "010108"),
Response("6F000000000000000000000000000000", 0x0410, "0001FF"),
Response("04000000000000000000000000000000", 0x0410, "01010F"),
Response("00000000000000000000000000000000", 0x0430, "000101"), # divert
# Response("00000000000000000000000000000000", 0x0430, "000102"),
# Response("00000000000000000000000000000000", 0x0430, "000104"),
# Response("00000000000000000000000000000000", 0x0430, "000108"),
Response("00000000000000000000000000000000", 0x0430, "000110"),
# Response("00000000000000000000000000000000", 0x0430, "000120"),
# Response("00000000000000000000000000000000", 0x0430, "000140"),
# Response("00000000000000000000000000000000", 0x0430, "000180"),
# Response("00000000000000000000000000000000", 0x0430, "010101"),
# Response("00000000000000000000000000000000", 0x0430, "010102"),
Response("00000000000000000000000000000000", 0x0430, "0001FF"),
Response("00000000000000000000000000000000", 0x0430, "010103"),
Response("08000000000000000000000000000000", 0x0450, "01FF"),
Response("08000000000000000000000000000000", 0x0450, "02FF"),
Response("08000000000000000000000000000000", 0x0450, "03FF"),
Response("00040000000000000000000000000000", 0x0450, "04FF"),
Response("5C020000000000000000000000000000", 0x0450, "05FF"),
Response("01000000000000000000000000000000", 0x0460, "00FF"),
Response("01000000000000000000000000000000", 0x0470, "00FF"),
Response("01", 0x0420, "00010101"), # set index 1
Response("00", 0x0420, "00010100"), # unset index 1
Response("01", 0x0420, "00011010"), # set index 4
Response("00", 0x0420, "00011000"), # unset index 4
Response("01", 0x0440, "00010101"), # divert index 1
Response("00", 0x0440, "00010100"), # undivert index 1
Response("000080FF", 0x0480, "000080FF"), # write param 0
Response("000180FF", 0x0480, "000180FF"), # write param 0
]
zone_responses_1 = [ # responses for COLOR LED EFFECTS
Response("00000102", 0x0710, "00FF00"),
Response("0000000300040005", 0x0720, "000000"),
Response("0001000B00080009", 0x0720, "000100"),
]
zone_responses_2 = [ # responses for RGB EFFECTS
Response("0000000102", 0x0700, "00FF00"),
Response("0000000300040005", 0x0700, "000000"),
Response("0001000200080009", 0x0700, "000100"),
]
effects_responses_1 = [Response("0100000001", 0x0700)] + zone_responses_1
effects_responses_2 = [Response("FFFF0100000001", 0x0700, "FFFF00")] + zone_responses_2
responses_profiles = [ # OnboardProfile in RAM
Response("0104010101020100FE0200", 0x0900),
Response("000101FF", 0x0950, "00000000"),
Response("FFFFFFFF", 0x0950, "00000004"),
Response("01010290018003000700140028FFFFFF", 0x0950, "00010000"),
Response("FFFF0000000000000000000000000000", 0x0950, "00010010"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "00010020"),
Response("900aFF00800204548000FFFF900aFF00", 0x0950, "00010030"),
Response("800204548000FFFF900aFF0080020454", 0x0950, "00010040"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "00010050"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "00010060"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "00010070"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "00010080"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "00010090"),
Response("54004500370000000000000000000000", 0x0950, "000100A0"),
Response("00000000000000000000000000000000", 0x0950, "000100B0"),
Response("00000000000000000000000000000000", 0x0950, "000100C0"),
Response("0A01020300500407000000FFFFFFFFFF", 0x0950, "000100D0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "000100E0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFF7C81AB", 0x0950, "000100EE"),
]
responses_profiles_rom = [ # OnboardProfile in ROM
Response("0104010101020100FE0200", 0x0900),
Response("00000000", 0x0950, "00000000"),
Response("010101FF", 0x0950, "01000000"),
Response("FFFFFFFF", 0x0950, "01000004"),
Response("01010290018003000700140028FFFFFF", 0x0950, "01010000"),
Response("FFFF0000000000000000000000000000", 0x0950, "01010010"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "01010020"),
Response("900aFF00800204548000FFFF900aFF00", 0x0950, "01010030"),
Response("800204548000FFFF900aFF0080020454", 0x0950, "01010040"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "01010050"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010060"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010070"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010080"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010090"),
Response("54004500370000000000000000000000", 0x0950, "010100A0"),
Response("00000000000000000000000000000000", 0x0950, "010100B0"),
Response("00000000000000000000000000000000", 0x0950, "010100C0"),
Response("0A01020300500407000000FFFFFFFFFF", 0x0950, "010100D0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "010100E0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFF7C81AB", 0x0950, "010100EE"),
]
responses_profiles_rom_2 = [ # OnboardProfile in ROM
Response("0104010101020100FE0200", 0x0900),
Response("FFFFFFFF", 0x0950, "00000000"),
Response("010101FF", 0x0950, "01000000"),
Response("FFFFFFFF", 0x0950, "01000004"),
Response("01010290018003000700140028FFFFFF", 0x0950, "01010000"),
Response("FFFF0000000000000000000000000000", 0x0950, "01010010"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "01010020"),
Response("900aFF00800204548000FFFF900aFF00", 0x0950, "01010030"),
Response("800204548000FFFF900aFF0080020454", 0x0950, "01010040"),
Response("8000FFFF900aFF00800204548000FFFF", 0x0950, "01010050"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010060"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010070"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010080"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "01010090"),
Response("54004500370000000000000000000000", 0x0950, "010100A0"),
Response("00000000000000000000000000000000", 0x0950, "010100B0"),
Response("00000000000000000000000000000000", 0x0950, "010100C0"),
Response("0A01020300500407000000FFFFFFFFFF", 0x0950, "010100D0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0950, "010100E0"),
Response("FFFFFFFFFFFFFFFFFFFFFFFFFF7C81AB", 0x0950, "010100EE"),
]
complex_responses_1 = [ # COLOR_LED_EFFECTS
Response(4.2, 0x0010), # ping
Response("010001", 0x0000, "0001"), # FEATURE SET at x01
Response("020001", 0x0000, "0020"), # CONFIG_CHANGE at x02
Response("0A", 0x0100), # 10 features
Response("070001", 0x0000, "8070"), # COLOR_LED_EFFECTS at 0x07
*effects_responses_1,
]
complex_responses_2 = [ # RGB_EFFECTS + reprogrammable keys + persistent actions
Response(4.2, 0x0010), # ping
Response("010001", 0x0000, "0001"), # FEATURE SET at x01
Response("020001", 0x0000, "0020"), # CONFIG_CHANGE at x02
Response("0A", 0x0100), # 10 features
Response("070001", 0x0000, "8071"), # RGB_EFFECTS at 0x07
*effects_responses_2,
Response("040001", 0x0000, "1C00"), # Persistent Remappable Actions at 0x04
*responses_remap,
Response("080001", 0x0000, "6501"), # Gestures at 0x08
*adjust_responses_index(8, responses_gestures),
Response("060003", 0x0000, "1982"), # Backlight 2 at 0x06
Response("010118000001020003000400", 0x0600),
Response("090003", 0x0000, "8100"), # Onboard Profiles at 0x09
*responses_profiles,
]
responses_speedchange = [
Response("0100", 0x0400),
Response("010001", 0x0000, "0001"), # FEATURE SET at x01
Response("0A", 0x0100), # 10 features
Response("0120", 0x0410, "0120"),
Response("050001", 0x0000, "1B04"), # REPROG_CONTROLS_V4
Response("01", 0x0500),
Response("00ED009D310003070500000000000000", 0x0510, "00"), # DPI Change
Response("00ED0000000000000000000000000000", 0x0520, "00ED"), # DPI Change current
Response("060000", 0x0000, "2205"), # POINTER_SPEED
]
# A fake device that uses provided data (responses) to respond to HID++ commands.
# Some methods from the real device are used to set up data structures needed for settings
@dataclass
class Device:
name: str = "TESTD"
online: bool = True
protocol: float = 2.0
responses: Any = field(default_factory=list)
codename: str = "TESTC"
feature: Optional[int] = None
offset: Optional[int] = 4
version: Optional[int] = 0
wpid: Optional[str] = "0000"
setting_callback: Any = None
sliding = profiles = _backlight = _keys = _remap_keys = _led_effects = _gestures = None
_gestures_lock = threading.Lock()
read_register = device.Device.read_register
write_register = device.Device.write_register
backlight = device.Device.backlight
keys = device.Device.keys
remap_keys = device.Device.remap_keys
led_effects = device.Device.led_effects
gestures = device.Device.gestures
__hash__ = device.Device.__hash__
feature_request = device.Device.feature_request
def __post_init__(self):
self._name = self.name
self._protocol = self.protocol
self.persister = configuration._DeviceEntry()
self.features = hidpp20.FeaturesArray(self)
self.settings = []
if self.feature is not None:
self.features = hidpp20.FeaturesArray(self)
self.responses = [
Response("010001", 0x0000, "0001"),
Response("20", 0x0100),
] + self.responses
self.responses.append(
Response(
f"{int(self.offset):0>2X}00{int(self.version):0>2X}",
0x0000,
f"{int(self.feature):0>4X}",
)
)
if self.setting_callback is None:
self.setting_callback = lambda x, y, z: None
self.add_notification_handler = lambda x, y: None
def request(self, id, *params, no_reply=False, long_message=False, protocol=2.0):
params = b"".join(pack("B", p) if isinstance(p, int) else p for p in params)
print("REQUEST ", self._name, hex(id), params.hex().upper())
for r in self.responses:
if id == r.id and params == bytes.fromhex(r.params):
print("RESPONSE", self._name, hex(r.id), r.params, r.response)
return bytes.fromhex(r.response) if isinstance(r.response, str) else r.response
print("RESPONSE", self._name, None)
def ping(self, handle=None, devnumber=None, long_message=False):
print("PING", self._protocol)
return self._protocol
def match_requests(number, responses, call_args_list):
for i in range(0 - number, 0):
param = b"".join(pack("B", p) if isinstance(p, int) else p for p in call_args_list[i][0][1:]).hex().upper()
print("MATCH", i, hex(call_args_list[i][0][0]), param, hex(responses[i].id), responses[i].params)
assert call_args_list[i][0][0] == responses[i].id
assert param == responses[i].params
| 21,905 | Python | .py | 403 | 49.30273 | 126 | 0.703928 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,521 | test_hidpp20_simple.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_hidpp20_simple.py | ## Copyright (C) 2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import pytest
from logitech_receiver import common
from logitech_receiver import hidpp20
from logitech_receiver import hidpp20_constants
from logitech_receiver.hidpp20_constants import SupportedFeature
from . import fake_hidpp
_hidpp20 = hidpp20.Hidpp20()
def test_get_firmware():
responses = [
fake_hidpp.Response("02FFFF", 0x0400),
fake_hidpp.Response("01414243030401000101000102030405", 0x0410, "00"),
fake_hidpp.Response("02414243030401000101000102030405", 0x0410, "01"),
]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.DEVICE_FW_VERSION)
result = _hidpp20.get_firmware(device)
assert len(result) == 2
assert isinstance(result[0], common.FirmwareInfo)
assert isinstance(result[1], common.FirmwareInfo)
def test_get_ids():
responses = [fake_hidpp.Response("FF12345678000D123456789ABC", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.DEVICE_FW_VERSION)
unitId, modelId, tid_map = _hidpp20.get_ids(device)
assert unitId == "12345678"
assert modelId == "123456789ABC"
assert tid_map == {"btid": "1234", "wpid": "5678", "usbid": "9ABC"}
def test_get_kind():
responses = [fake_hidpp.Response("00", 0x0420)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.DEVICE_NAME)
result = _hidpp20.get_kind(device)
assert result == "keyboard"
assert result == 1
def test_get_name():
responses = [
fake_hidpp.Response("12", 0x0400),
fake_hidpp.Response("4142434445464748494A4B4C4D4E4F", 0x0410, "00"),
fake_hidpp.Response("505152530000000000000000000000", 0x0410, "0F"),
]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.DEVICE_NAME)
result = _hidpp20.get_name(device)
assert result == "ABCDEFGHIJKLMNOPQR"
def test_get_friendly_name():
responses = [
fake_hidpp.Response("12", 0x0400),
fake_hidpp.Response("004142434445464748494A4B4C4D4E", 0x0410, "00"),
fake_hidpp.Response("0E4F50515253000000000000000000", 0x0410, "0E"),
]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.DEVICE_FRIENDLY_NAME)
result = _hidpp20.get_friendly_name(device)
assert result == "ABCDEFGHIJKLMNOPQR"
def test_get_battery_status():
responses = [fake_hidpp.Response("502000FFFF", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.BATTERY_STATUS)
feature, battery = _hidpp20.get_battery_status(device)
assert feature == SupportedFeature.BATTERY_STATUS
assert battery.level == 80
assert battery.next_level == 32
assert battery.status == common.BatteryStatus.DISCHARGING
def test_get_battery_voltage():
responses = [fake_hidpp.Response("1000FFFFFF", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.BATTERY_VOLTAGE)
feature, battery = _hidpp20.get_battery_voltage(device)
assert feature == SupportedFeature.BATTERY_VOLTAGE
assert battery.level == 90
assert battery.status == common.BatteryStatus.RECHARGING
assert battery.voltage == 0x1000
def test_get_battery_unified():
responses = [fake_hidpp.Response("500100FFFF", 0x0410)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.UNIFIED_BATTERY)
feature, battery = _hidpp20.get_battery_unified(device)
assert feature == SupportedFeature.UNIFIED_BATTERY
assert battery.level == 80
assert battery.status == common.BatteryStatus.DISCHARGING
def test_get_adc_measurement():
responses = [fake_hidpp.Response("100003", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.ADC_MEASUREMENT)
feature, battery = _hidpp20.get_adc_measurement(device)
assert feature == SupportedFeature.ADC_MEASUREMENT
assert battery.level == 90
assert battery.status == common.BatteryStatus.RECHARGING
assert battery.voltage == 0x1000
def test_get_battery():
responses = [fake_hidpp.Response("502000FFFF", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.BATTERY_STATUS)
feature, battery = _hidpp20.get_battery(device, SupportedFeature.BATTERY_STATUS)
assert feature == SupportedFeature.BATTERY_STATUS
assert battery.level == 80
assert battery.next_level == 32
assert battery.status == common.BatteryStatus.DISCHARGING
def test_get_battery_none():
responses = [
fake_hidpp.Response(None, 0x0000, f"{int(SupportedFeature.BATTERY_STATUS):0>4X}"),
fake_hidpp.Response(None, 0x0000, f"{int(SupportedFeature.BATTERY_VOLTAGE):0>4X}"),
fake_hidpp.Response("500100ffff", 0x0410),
]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.UNIFIED_BATTERY)
feature, battery = _hidpp20.get_battery(device, None)
assert feature == SupportedFeature.UNIFIED_BATTERY
assert battery.level == 80
assert battery.status == common.BatteryStatus.DISCHARGING
# get_keys is in test_hidpp20_complex
# get_remap_keys is in test_hidpp20_complex
# TODO get_gestures is complex
# get_backlight is in test_hidpp20_complex
# get_profiles is in test_hidpp20_complex
def test_get_mouse_pointer_info():
responses = [fake_hidpp.Response("01000A", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.MOUSE_POINTER)
result = _hidpp20.get_mouse_pointer_info(device)
assert result == {
"dpi": 0x100,
"acceleration": "med",
"suggest_os_ballistics": False,
"suggest_vertical_orientation": True,
}
def test_get_vertical_scrolling_info():
responses = [fake_hidpp.Response("01080C", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.VERTICAL_SCROLLING)
result = _hidpp20.get_vertical_scrolling_info(device)
assert result == {"roller": "standard", "ratchet": 8, "lines": 12}
def test_get_hi_res_scrolling_info():
responses = [fake_hidpp.Response("0102", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.HI_RES_SCROLLING)
mode, resolution = _hidpp20.get_hi_res_scrolling_info(device)
assert mode == 1
assert resolution == 2
def test_get_pointer_speed_info():
responses = [fake_hidpp.Response("0102", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.POINTER_SPEED)
result = _hidpp20.get_pointer_speed_info(device)
assert result == 0x0102 / 256
def test_get_lowres_wheel_status():
responses = [fake_hidpp.Response("01", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.LOWRES_WHEEL)
result = _hidpp20.get_lowres_wheel_status(device)
assert result == "HID++"
def test_get_hires_wheel():
responses = [
fake_hidpp.Response("010C", 0x0400),
fake_hidpp.Response("05FF", 0x0410),
fake_hidpp.Response("03FF", 0x0430),
]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.HIRES_WHEEL)
multi, has_invert, has_ratchet, inv, res, target, ratchet = _hidpp20.get_hires_wheel(device)
assert multi == 1
assert has_invert is True
assert has_ratchet is True
assert inv is True
assert res is False
assert target is True
assert ratchet is True
def test_get_new_fn_inversion():
responses = [fake_hidpp.Response("0300", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.NEW_FN_INVERSION)
result = _hidpp20.get_new_fn_inversion(device)
assert result == (True, False)
@pytest.fixture
def mock_gethostname(mocker):
mocker.patch("socket.gethostname", return_value="ABCDEFG.foo.org")
@pytest.mark.parametrize(
"responses, expected_result",
[
([fake_hidpp.Response(None, 0x0400)], {}),
([fake_hidpp.Response("02000000", 0x0400)], {}),
(
[
fake_hidpp.Response("03000200", 0x0400),
fake_hidpp.Response("FF01FFFF05FFFF", 0x0410, "00"),
fake_hidpp.Response("0000414243444500FFFFFFFFFF", 0x0430, "0000"),
fake_hidpp.Response("FF01FFFF10FFFF", 0x0410, "01"),
fake_hidpp.Response("01004142434445464748494A4B4C4D", 0x0430, "0100"),
fake_hidpp.Response("01134E4F5000FFFFFFFFFFFFFFFFFF", 0x0430, "010E"),
fake_hidpp.Response("000000000008", 0x0410, "00"),
fake_hidpp.Response("0208", 0x0440, "000041424344454647"),
],
{0: (True, "ABCDEFG"), 1: (True, "ABCDEFGHIJKLMNO")},
),
],
)
def test_get_host_names(responses, expected_result, mock_gethostname):
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.HOSTS_INFO)
result = _hidpp20.get_host_names(device)
assert result == expected_result
@pytest.mark.parametrize(
"responses, expected_result",
[
([fake_hidpp.Response(None, 0x0400)], None),
(
[
fake_hidpp.Response("03000002", 0x0400),
fake_hidpp.Response("000000000008", 0x0410, "02"),
fake_hidpp.Response("020E", 0x0440, "02004142434445464748494A4B4C4D4E"),
],
True,
),
(
[
fake_hidpp.Response("03000002", 0x0400),
fake_hidpp.Response("000000000014", 0x0410, "02"),
fake_hidpp.Response("020E", 0x0440, "02004142434445464748494A4B4C4D4E"),
fake_hidpp.Response("0214", 0x0440, "020E4F505152535455565758"),
],
True,
),
],
)
def test_set_host_name(responses, expected_result):
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.HOSTS_INFO)
result = _hidpp20.set_host_name(device, "ABCDEFGHIJKLMNOPQRSTUVWX")
assert result == expected_result
def test_get_onboard_mode():
responses = [fake_hidpp.Response("03FFFFFFFF", 0x0420)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.ONBOARD_PROFILES)
result = _hidpp20.get_onboard_mode(device)
assert result == 0x3
def test_set_onboard_mode():
responses = [fake_hidpp.Response("03FFFFFFFF", 0x0410, "03")]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.ONBOARD_PROFILES)
res = _hidpp20.set_onboard_mode(device, 0x3)
assert res is not None
@pytest.mark.parametrize(
"responses, expected_result",
[
([fake_hidpp.Response("03FFFF", 0x0420)], "1ms"),
(
[
fake_hidpp.Response(None, 0x0000, f"{int(SupportedFeature.REPORT_RATE):04X}"),
fake_hidpp.Response("04FFFF", 0x0420),
],
"500us",
),
],
)
def test_get_polling_rate(
responses,
expected_result,
):
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.EXTENDED_ADJUSTABLE_REPORT_RATE)
result = _hidpp20.get_polling_rate(device)
assert result == expected_result
def test_get_remaining_pairing():
responses = [fake_hidpp.Response("03FFFF", 0x0400)]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.REMAINING_PAIRING)
result = _hidpp20.get_remaining_pairing(device)
assert result == 0x03
def test_config_change():
responses = [fake_hidpp.Response("03FFFF", 0x0410, "02")]
device = fake_hidpp.Device(responses=responses, feature=SupportedFeature.CONFIG_CHANGE)
result = _hidpp20.config_change(device, 0x2)
assert result == bytes.fromhex("03FFFF")
def test_decipher_battery_status():
report = b"\x50\x20\x00\xff\xff"
feature, battery = hidpp20.decipher_battery_status(report)
assert feature == SupportedFeature.BATTERY_STATUS
assert battery.level == 80
assert battery.next_level == 32
assert battery.status == common.BatteryStatus.DISCHARGING
def test_decipher_battery_voltage():
report = b"\x10\x00\xff\xff\xff"
feature, battery = hidpp20.decipher_battery_voltage(report)
assert feature == SupportedFeature.BATTERY_VOLTAGE
assert battery.level == 90
assert battery.status == common.BatteryStatus.RECHARGING
assert battery.voltage == 0x1000
def test_decipher_battery_unified():
report = b"\x50\x01\x00\xff\xff"
feature, battery = hidpp20.decipher_battery_unified(report)
assert feature == SupportedFeature.UNIFIED_BATTERY
assert battery.level == 80
assert battery.status == common.BatteryStatus.DISCHARGING
def test_decipher_adc_measurement():
report = b"\x10\x00\x03"
feature, battery = hidpp20.decipher_adc_measurement(report)
assert feature == SupportedFeature.ADC_MEASUREMENT
assert battery.level == 90
assert battery.status == common.BatteryStatus.RECHARGING
assert battery.voltage == 0x1000
@pytest.mark.parametrize(
"code, expected_flags",
[
(0x01, ["unknown:000001"]),
(0x0F, ["unknown:00000F"]),
(0xF0, ["internal", "hidden", "obsolete", "unknown:000010"]),
(0x20, ["internal"]),
(0x33, ["internal", "unknown:000013"]),
(0x3F, ["internal", "unknown:00001F"]),
(0x40, ["hidden"]),
(0x50, ["hidden", "unknown:000010"]),
(0x5F, ["hidden", "unknown:00001F"]),
(0x7F, ["internal", "hidden", "unknown:00001F"]),
(0x80, ["obsolete"]),
(0xA0, ["internal", "obsolete"]),
(0xE0, ["internal", "hidden", "obsolete"]),
(0xFF, ["internal", "hidden", "obsolete", "unknown:00001F"]),
],
)
def test_feature_flag_names(code, expected_flags):
flags = common.flag_names(hidpp20_constants.FeatureFlag, code)
assert list(flags) == expected_flags
| 14,555 | Python | .py | 313 | 40.43131 | 109 | 0.704145 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,522 | test_settings.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_settings.py | import pytest
from logitech_receiver import settings
@pytest.mark.parametrize(
"current, new, expected",
[
(False, "toggle", True),
(True, "~", False),
("don't care", True, True),
("don't care", "true", True),
("don't care", "false", False),
("don't care", "no", False),
("don't care", "off", False),
("don't care", "True", True),
("don't care", "yes", True),
("don't care", "on", True),
("anything", "anything", None),
],
)
def test_bool_or_toggle(current, new, expected):
result = settings.bool_or_toggle(current=current, new=new)
assert result == expected
| 671 | Python | .py | 21 | 25.619048 | 62 | 0.55418 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,523 | test_setting_templates.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_setting_templates.py | ## Copyright (C) 2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""The tests work by creating a faked device (from the hidpp module) that uses provided data as responses to HID++ commands.
The device uses some methods from the real device to set up data structures that are needed for some tests.
"""
from dataclasses import dataclass
from typing import Any
import pytest
from logitech_receiver import common
from logitech_receiver import hidpp20
from logitech_receiver import hidpp20_constants
from logitech_receiver import settings_templates
from logitech_receiver import special_keys
from . import fake_hidpp
# TODO action part of DpiSlidingXY, MouseGesturesXY
class Setup:
def __init__(self, test, *params):
self.test = test
self.responses = [r for r in params if isinstance(r, fake_hidpp.Response)]
self.choices = None if isinstance(params[0], fake_hidpp.Response) else params[0]
@dataclass
class RegisterTest:
sclass: Any
initial_value: Any = False
write_value: Any = True
write_params: str = "01"
register_tests = [
Setup(
RegisterTest(settings_templates.RegisterHandDetection, False, True, [b"\x00\x00\x00"]),
fake_hidpp.Response("000030", 0x8101), # keyboard_hand_detection
fake_hidpp.Response("000000", 0x8001, "000000"),
),
Setup(
RegisterTest(settings_templates.RegisterHandDetection, True, False, [b"\x00\x00\x30"]),
fake_hidpp.Response("000000", 0x8101), # keyboard_hand_detection
fake_hidpp.Response("000030", 0x8001, "000030"),
),
Setup(
RegisterTest(settings_templates.RegisterSmoothScroll, False, True, [b"\x40"]),
fake_hidpp.Response("00", 0x8101), # mouse_button_flags
fake_hidpp.Response("40", 0x8001, "40"),
),
Setup(
RegisterTest(settings_templates.RegisterSideScroll, True, False, [b"\x00"]),
fake_hidpp.Response("02", 0x8101), # mouse_button_flags
fake_hidpp.Response("00", 0x8001, "00"),
),
Setup(
RegisterTest(settings_templates.RegisterFnSwap, False, True, [b"\x00\x01"]),
fake_hidpp.Response("0000", 0x8109), # keyboard_fn_swap
fake_hidpp.Response("0001", 0x8009, "0001"),
),
Setup(
RegisterTest(
settings_templates._PerformanceMXDpi, common.NamedInt(0x88, "800"), common.NamedInt(0x89, "900"), [b"\x89"]
),
fake_hidpp.Response("88", 0x8163), # mouse_dpi
fake_hidpp.Response("89", 0x8063, "89"),
),
]
@pytest.mark.parametrize("test", register_tests)
def test_register_template(test, mocker):
device = fake_hidpp.Device(protocol=1.0, responses=test.responses)
spy_request = mocker.spy(device, "request")
setting = test.test.sclass.build(device)
value = setting.read(cached=False)
cached_value = setting.read(cached=True)
write_value = setting.write(test.test.write_value)
assert setting is not None
assert value == test.test.initial_value
assert cached_value == test.test.initial_value
assert write_value == test.test.write_value
spy_request.assert_called_with(test.test.sclass.register + 0x8000, *test.test.write_params)
@dataclass
class FeatureTest:
sclass: Any
initial_value: Any = False
write_value: Any = True
matched_calls: int = 1
offset: int = 0x04
version: int = 0x00
rewrite: bool = False
simple_tests = [
Setup(
FeatureTest(settings_templates.K375sFnSwap, False, True, offset=0x06),
fake_hidpp.Response("FF0001", 0x0600, "FF"),
fake_hidpp.Response("FF0101", 0x0610, "FF01"),
),
Setup(
FeatureTest(settings_templates.K375sFnSwap, False, True, offset=0x06),
fake_hidpp.Response("050001", 0x0000, "1815"), # HOSTS_INFO
fake_hidpp.Response("FF0001", 0x0600, "FF"),
fake_hidpp.Response("FF0101", 0x0610, "FF01"),
),
Setup(
FeatureTest(settings_templates.K375sFnSwap, False, True, offset=0x06),
fake_hidpp.Response("050001", 0x0000, "1815"), # HOSTS_INFO
fake_hidpp.Response("07050301", 0x0500), # current host is 0x01, i.e., host 2
fake_hidpp.Response("010001", 0x0600, "01"),
fake_hidpp.Response("010101", 0x0610, "0101"),
),
Setup(
FeatureTest(settings_templates.FnSwap, True, False),
fake_hidpp.Response("01", 0x0400),
fake_hidpp.Response("00", 0x0410, "00"),
),
Setup(
FeatureTest(settings_templates.NewFnSwap, True, False),
fake_hidpp.Response("01", 0x0400),
fake_hidpp.Response("00", 0x0410, "00"),
),
# Setup( # Backlight has caused problems
# FeatureTest(settings_templates.Backlight, 0, 5, offset=0x06),
# fake_hidpp.Response("00", 0x0600),
# fake_hidpp.Response("05", 0x0610, "05"),
# ),
Setup(
FeatureTest(settings_templates.Backlight2DurationHandsOut, 80, 160, version=0x03),
fake_hidpp.Response("011830000000100040006000", 0x0400),
fake_hidpp.Response("0118FF00200040006000", 0x0410, "0118FF00200040006000"),
),
Setup(
FeatureTest(settings_templates.Backlight2DurationHandsIn, 320, 160, version=0x03),
fake_hidpp.Response("011830000000200040006000", 0x0400),
fake_hidpp.Response("0118FF00200020006000", 0x0410, "0118FF00200020006000"),
),
Setup(
FeatureTest(settings_templates.Backlight2DurationPowered, 480, 80, version=0x03),
fake_hidpp.Response("011830000000200040006000", 0x0400),
fake_hidpp.Response("0118FF00200040001000", 0x0410, "0118FF00200040001000"),
),
Setup(
FeatureTest(settings_templates.Backlight3, 0x50, 0x70),
fake_hidpp.Response("50", 0x0410),
fake_hidpp.Response("70", 0x0420, "007009"),
),
Setup(
FeatureTest(settings_templates.HiResScroll, True, False),
fake_hidpp.Response("01", 0x0400),
fake_hidpp.Response("00", 0x0410, "00"),
),
Setup(
FeatureTest(settings_templates.LowresMode, False, True),
fake_hidpp.Response("00", 0x0400),
fake_hidpp.Response("01", 0x0410, "01"),
),
Setup(
FeatureTest(settings_templates.HiresSmoothInvert, True, False),
fake_hidpp.Response("06", 0x0410),
fake_hidpp.Response("02", 0x0420, "02"),
),
Setup(
FeatureTest(settings_templates.HiresSmoothResolution, True, False),
fake_hidpp.Response("06", 0x0410),
fake_hidpp.Response("04", 0x0420, "04"),
),
Setup(
FeatureTest(settings_templates.HiresMode, False, True),
fake_hidpp.Response("06", 0x0410),
fake_hidpp.Response("07", 0x0420, "07"),
),
Setup(
FeatureTest(settings_templates.PointerSpeed, 0x0100, 0x0120),
fake_hidpp.Response("0100", 0x0400),
fake_hidpp.Response("0120", 0x0410, "0120"),
),
Setup(
FeatureTest(settings_templates.ThumbMode, True, False),
fake_hidpp.Response("0100", 0x0410),
fake_hidpp.Response("0000", 0x0420, "0000"),
),
Setup(
FeatureTest(settings_templates.ThumbInvert, False, True),
fake_hidpp.Response("0100", 0x0410),
fake_hidpp.Response("0101", 0x0420, "0101"),
),
Setup(
FeatureTest(settings_templates.DivertCrown, False, True),
fake_hidpp.Response("01", 0x0410),
fake_hidpp.Response("02", 0x0420, "02"),
),
Setup(
FeatureTest(settings_templates.CrownSmooth, True, False),
fake_hidpp.Response("0001", 0x0410),
fake_hidpp.Response("0002", 0x0420, "0002"),
),
Setup(
FeatureTest(settings_templates.DivertGkeys, False, True),
fake_hidpp.Response("01", 0x0420, "01"),
),
Setup(
FeatureTest(settings_templates.ScrollRatchet, 2, 1),
fake_hidpp.Response("02", 0x0400),
fake_hidpp.Response("01", 0x0410, "01"),
),
Setup(
FeatureTest(settings_templates.SmartShift, 1, 10),
fake_hidpp.Response("0100", 0x0400),
fake_hidpp.Response("000A", 0x0410, "000A"),
),
Setup(
FeatureTest(settings_templates.SmartShift, 5, 50),
fake_hidpp.Response("0005", 0x0400),
fake_hidpp.Response("00FF", 0x0410, "00FF"),
),
Setup(
FeatureTest(settings_templates.SmartShiftEnhanced, 5, 50),
fake_hidpp.Response("0005", 0x0410),
fake_hidpp.Response("00FF", 0x0420, "00FF"),
),
Setup(
FeatureTest(settings_templates.DisableKeyboardKeys, {1: True, 8: True}, {1: False, 8: True}),
fake_hidpp.Response("09", 0x0400),
fake_hidpp.Response("09", 0x0410),
fake_hidpp.Response("08", 0x0420, "08"),
),
Setup(
FeatureTest(settings_templates.DualPlatform, 0, 1),
fake_hidpp.Response("00", 0x0400),
fake_hidpp.Response("01", 0x0420, "01"),
),
Setup(
FeatureTest(settings_templates.MKeyLEDs, {1: False, 2: False, 4: False}, {1: False, 2: True, 4: True}),
fake_hidpp.Response("03", 0x0400),
fake_hidpp.Response("06", 0x0410, "06"),
),
Setup(
FeatureTest(settings_templates.MRKeyLED, False, True),
fake_hidpp.Response("01", 0x0400, "01"),
),
Setup(
FeatureTest(settings_templates.Sidetone, 5, 0xA),
fake_hidpp.Response("05", 0x0400),
fake_hidpp.Response("0A", 0x0410, "0A"),
),
Setup(
FeatureTest(settings_templates.ADCPower, 5, 0xA),
fake_hidpp.Response("05", 0x0410),
fake_hidpp.Response("0A", 0x0420, "0A"),
),
Setup(
FeatureTest(settings_templates.LEDControl, 0, 1),
fake_hidpp.Response("00", 0x0470),
fake_hidpp.Response("01", 0x0480, "01"),
),
Setup(
FeatureTest(
settings_templates.LEDZoneSetting,
hidpp20.LEDEffectSetting(ID=3, intensity=0x50, period=0x100),
hidpp20.LEDEffectSetting(ID=3, intensity=0x50, period=0x101),
),
fake_hidpp.Response("0100000001", 0x0400),
fake_hidpp.Response("00000102", 0x0410, "00FF00"),
fake_hidpp.Response("0000000300040005", 0x0420, "000000"),
fake_hidpp.Response("0001000B00080009", 0x0420, "000100"),
fake_hidpp.Response("000000000000010050", 0x04E0, "00"),
fake_hidpp.Response("000000000000000101500000", 0x0430, "000000000000000101500000"),
),
Setup(
FeatureTest(settings_templates.RGBControl, 0, 1),
fake_hidpp.Response("0000", 0x0450),
fake_hidpp.Response("010100", 0x0450, "0101"),
),
Setup(
FeatureTest(
settings_templates.RGBEffectSetting,
hidpp20.LEDEffectSetting(ID=3, intensity=0x50, period=0x100),
hidpp20.LEDEffectSetting(ID=2, color=0x505050, speed=0x50),
),
fake_hidpp.Response("FFFF0100000001", 0x0400, "FFFF00"),
fake_hidpp.Response("0000000102", 0x0400, "00FF00"),
fake_hidpp.Response("0000000300040005", 0x0400, "000000"),
fake_hidpp.Response("0001000200080009", 0x0400, "000100"),
fake_hidpp.Response("000000000000010050", 0x04E0, "00"),
fake_hidpp.Response("00015050505000000000000001", 0x0410, "00015050505000000000000001"),
),
Setup(
FeatureTest(settings_templates.RGBEffectSetting, None, hidpp20.LEDEffectSetting(ID=3, intensity=0x60, period=0x101)),
fake_hidpp.Response("FFFF0100000001", 0x0400, "FFFF00"),
fake_hidpp.Response("0000000102", 0x0400, "00FF00"),
fake_hidpp.Response("0000000300040005", 0x0400, "000000"),
fake_hidpp.Response("0001000200080009", 0x0400, "000100"),
fake_hidpp.Response("00000000000000010160000001", 0x0410, "00000000000000010160000001"),
),
Setup(
FeatureTest(settings_templates.RGBEffectSetting, None, hidpp20.LEDEffectSetting(ID=3, intensity=0x60, period=0x101)),
fake_hidpp.Response("FF000200020004000000000000000000", 0x0400, "FFFF00"),
fake_hidpp.Response("00000002040000000000000000000000", 0x0400, "00FF00"),
fake_hidpp.Response("00000000000000000000000000000000", 0x0400, "000000"),
fake_hidpp.Response("00010001000000000000000000000000", 0x0400, "000100"),
fake_hidpp.Response("00020003C00503E00000000000000000", 0x0400, "000200"),
fake_hidpp.Response("0003000AC0011E0B0000000000000000", 0x0400, "000300"),
fake_hidpp.Response("01000001070000000000000000000000", 0x0400, "01FF00"),
fake_hidpp.Response("01000000000000000000000000000000", 0x0400, "010000"),
fake_hidpp.Response("01010001000000000000000000000000", 0x0400, "010100"),
fake_hidpp.Response("0102000AC0011E0B0000000000000000", 0x0400, "010200"),
fake_hidpp.Response("01030003C00503E00000000000000000", 0x0400, "010300"),
fake_hidpp.Response("01040004DCE1001E0000000000000000", 0x0400, "010400"),
fake_hidpp.Response("0105000B000000320000000000000000", 0x0400, "010500"),
fake_hidpp.Response("0106000C001B02340000000000000000", 0x0400, "010600"),
fake_hidpp.Response("00020000000000010160000001", 0x0410, "00020000000000010160000001"),
),
Setup(
FeatureTest(settings_templates.Backlight2, 0xFF, 0x00),
common.NamedInts(Disabled=0xFF, Enabled=0x00),
fake_hidpp.Response("000201000000000000000000", 0x0400),
fake_hidpp.Response("010201", 0x0410, "0102FF00000000000000"),
),
Setup(
FeatureTest(settings_templates.Backlight2, 0x03, 0xFF),
common.NamedInts(Disabled=0xFF, Automatic=0x01, Manual=0x03),
fake_hidpp.Response("011838000000000000000000", 0x0400),
fake_hidpp.Response("001801", 0x0410, "0018FF00000000000000"),
),
Setup(
FeatureTest(settings_templates.Backlight2Level, 0, 3, version=0x03),
[0, 4],
fake_hidpp.Response("011830000000000000000000", 0x0400),
fake_hidpp.Response("05", 0x0420),
fake_hidpp.Response("01180103000000000000", 0x0410, "0118FF03000000000000"),
),
Setup(
FeatureTest(settings_templates.Backlight2Level, 0, 2, version=0x03),
[0, 4],
fake_hidpp.Response("011830000000000000000000", 0x0400),
fake_hidpp.Response("05", 0x0420),
fake_hidpp.Response("01180102000000000000", 0x0410, "0118FF02000000000000"),
),
Setup(
FeatureTest(settings_templates.OnboardProfiles, 0, 1, offset=0x0C),
common.NamedInts(**{"Disabled": 0, "Profile 1": 1, "Profile 2": 2}),
fake_hidpp.Response("01030001010101000101", 0x0C00),
fake_hidpp.Response("00010100000201FFFFFFFFFFFFFFFFFF", 0x0C50, "00000000"),
fake_hidpp.Response("000201FFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0C50, "00000004"),
fake_hidpp.Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0C50, "00000008"),
fake_hidpp.Response("02", 0x0C20),
fake_hidpp.Response("01", 0x0C10, "01"),
fake_hidpp.Response("0001", 0x0C30, "0001"),
),
Setup(
FeatureTest(settings_templates.OnboardProfiles, 1, 0, offset=0x0C),
common.NamedInts(**{"Disabled": 0, "Profile 1": 1, "Profile 2": 2}),
fake_hidpp.Response("01030001010101000101", 0x0C00),
fake_hidpp.Response("00010100000201FFFFFFFFFFFFFFFFFF", 0x0C50, "00000000"),
fake_hidpp.Response("000201FFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0C50, "00000004"),
fake_hidpp.Response("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 0x0C50, "00000008"),
fake_hidpp.Response("01", 0x0C20),
fake_hidpp.Response("0001", 0x0C40),
fake_hidpp.Response("02", 0x0C10, "02"),
),
Setup(
FeatureTest(settings_templates.ReportRate, 1, 5, offset=0x0C),
common.NamedInts(**{"1ms": 1, "2ms": 2, "5ms": 5, "6ms": 6}),
fake_hidpp.Response("33", 0x0C00),
fake_hidpp.Response("01", 0x0C10),
fake_hidpp.Response("05", 0x0C20, "05"),
),
Setup(
FeatureTest(settings_templates.ExtendedReportRate, 1, 5, offset=0x0C),
common.NamedInts(**{"8ms": 0, "4ms": 1, "500us": 4, "250us": 5}),
fake_hidpp.Response("33", 0x0C10),
fake_hidpp.Response("01", 0x0C20),
fake_hidpp.Response("05", 0x0C30, "05"),
),
Setup(
FeatureTest(settings_templates.AdjustableDpi, 800, 400, version=0x03),
common.NamedInts.list([400, 800, 1600]),
fake_hidpp.Response("000190032006400000", 0x0410, "000000"),
fake_hidpp.Response("000320", 0x0420),
fake_hidpp.Response("000190", 0x0430, "000190"),
),
Setup(
FeatureTest(settings_templates.AdjustableDpi, 256, 512, version=0x03),
common.NamedInts.list([256, 512]),
fake_hidpp.Response("000100e10002000000", 0x0410, "000000"),
fake_hidpp.Response("000100", 0x0420),
fake_hidpp.Response("000200", 0x0430, "000200"),
),
Setup(
FeatureTest(settings_templates.AdjustableDpi, 400, 800, version=0x03),
common.NamedInts.list([400, 800, 1200, 1600]),
fake_hidpp.Response("000190E19006400000000000000000", 0x0410, "000000"),
fake_hidpp.Response("000190", 0x0420),
fake_hidpp.Response("000320", 0x0430, "000320"),
),
Setup(
FeatureTest(settings_templates.Multiplatform, 0, 1),
common.NamedInts(**{"MacOS 0.1-0.5": 0, "iOS 0.1-0.7": 1, "Linux 0.2-0.9": 2, "Windows 0.3-0.9": 3}),
fake_hidpp.Response("020004000001", 0x0400),
fake_hidpp.Response("00FF200000010005", 0x0410, "00"),
fake_hidpp.Response("01FF400000010007", 0x0410, "01"),
fake_hidpp.Response("02FF040000020009", 0x0410, "02"),
fake_hidpp.Response("03FF010000030009", 0x0410, "03"),
fake_hidpp.Response("FF01", 0x0430, "FF01"),
),
Setup(
FeatureTest(settings_templates.ChangeHost, 1, 0),
common.NamedInts(**{"1:ABCDEF": 0, "2:GHIJKL": 1}),
fake_hidpp.Response("050003", 0x0000, "1815"), # HOSTS_INFO
fake_hidpp.Response("01000200", 0x0500),
fake_hidpp.Response("000100000600", 0x0510, "00"),
fake_hidpp.Response("000041424344454600", 0x0530, "0000"),
fake_hidpp.Response("000100000600", 0x0510, "01"),
fake_hidpp.Response("00004748494A4B4C00", 0x0530, "0100"),
fake_hidpp.Response("0201", 0x0400),
fake_hidpp.Response(True, 0x0410, "00"),
),
Setup(
FeatureTest(settings_templates.BrightnessControl, 0x10, 0x20),
[0, 80],
fake_hidpp.Response("00505100000000", 0x0400), # 0 to 80, all acceptable, no separate on/off
fake_hidpp.Response("10", 0x0410), # brightness 16
fake_hidpp.Response("0020", 0x0420, "0020"), # set brightness 32
),
Setup(
FeatureTest(settings_templates.BrightnessControl, 0x10, 0x00),
[0, 80],
fake_hidpp.Response("00505104000000", 0x0400), # 0 to 80, all acceptable, separate on/off
fake_hidpp.Response("10", 0x0410), # brightness 16
fake_hidpp.Response("01", 0x0430), # on
fake_hidpp.Response("00", 0x0440), # set off
fake_hidpp.Response("0000", 0x0420, "0000"), # set brightness 0
),
Setup(
FeatureTest(settings_templates.BrightnessControl, 0x00, 0x20),
[0, 80],
fake_hidpp.Response("00505104000000", 0x0400), # 0 to 80, all acceptable, separate on/off
fake_hidpp.Response("10", 0x0410), # brightness 16
fake_hidpp.Response("00", 0x0430), # off
fake_hidpp.Response("01", 0x0440), # set on
fake_hidpp.Response("0020", 0x0420, "0020"), # set brightness 32
),
Setup(
FeatureTest(settings_templates.BrightnessControl, 0x20, 0x08),
[0, 80],
fake_hidpp.Response("00504104001000", 0x0400), # 16 to 80, all acceptable, separate on/off
fake_hidpp.Response("20", 0x0410), # brightness 32
fake_hidpp.Response("01", 0x0430), # on
fake_hidpp.Response("00", 0x0440, "00"), # set off
),
Setup(
FeatureTest(settings_templates.SpeedChange, 0, None, 0), # need to set up all settings to successfully write
common.NamedInts(**{"Off": 0, "DPI Change": 0xED}),
*fake_hidpp.responses_speedchange,
),
]
@pytest.fixture
def mock_gethostname(mocker):
mocker.patch("socket.gethostname", return_value="ABCDEF.foo.org")
@pytest.mark.parametrize("test", simple_tests)
def test_simple_template(test, mocker, mock_gethostname):
tst = test.test
print("TEST", tst.sclass.feature)
device = fake_hidpp.Device(responses=test.responses, feature=tst.sclass.feature, offset=tst.offset, version=tst.version)
spy_request = mocker.spy(device, "request")
setting = settings_templates.check_feature(device, tst.sclass)
assert setting is not None
if isinstance(setting, list):
setting = setting[0]
if isinstance(test.choices, list):
assert setting._validator.min_value == test.choices[0]
assert setting._validator.max_value == test.choices[1]
elif test.choices is not None:
assert setting.choices == test.choices
value = setting.read(cached=False)
assert value == tst.initial_value
cached_value = setting.read(cached=True)
assert cached_value == tst.initial_value
write_value = setting.write(tst.write_value) if tst.write_value is not None else None
assert write_value == tst.write_value
fake_hidpp.match_requests(tst.matched_calls, test.responses, spy_request.call_args_list)
responses_reprog_controls = [
fake_hidpp.Response("03", 0x0500),
fake_hidpp.Response("00500038010001010400000000000000", 0x0510, "00"), # left button
fake_hidpp.Response("00510039010001010400000000000000", 0x0510, "01"), # right button
fake_hidpp.Response("00C4009D310003070500000000000000", 0x0510, "02"), # smart shift
fake_hidpp.Response("00500000000000000000000000000000", 0x0520, "0050"), # left button current
fake_hidpp.Response("00510000500000000000000000000000", 0x0520, "0051"), # right button current
fake_hidpp.Response("00C40000000000000000000000000000", 0x0520, "00C4"), # smart shift current
fake_hidpp.Response("00500005000000000000000000000000", 0x0530, "0050000050"), # left button write
fake_hidpp.Response("00510005000000000000000000000000", 0x0530, "0051000050"), # right button write
fake_hidpp.Response("00C4000C400000000000000000000000", 0x0530, "00C40000C4"), # smart shift write
]
key_tests = [
Setup(
FeatureTest(settings_templates.ReprogrammableKeys, {0x50: 0x50, 0x51: 0x50, 0xC4: 0xC4}, {0x51: 0x51}, 4, offset=0x05),
{
common.NamedInt(0x50, "Left Button"): common.UnsortedNamedInts(Left_Click=0x50, Right_Click=0x51),
common.NamedInt(0x51, "Right Button"): common.UnsortedNamedInts(Right_Click=0x51, Left_Click=0x50),
common.NamedInt(0xC4, "Smart Shift"): common.UnsortedNamedInts(Smart_Shift=0xC4, Left_Click=80, Right_Click=81),
},
*responses_reprog_controls,
fake_hidpp.Response("0051000051", 0x0530, "0051000051"), # right button set write
),
Setup(
FeatureTest(settings_templates.DivertKeys, {0xC4: 0}, {0xC4: 1}, 2, offset=0x05),
{common.NamedInt(0xC4, "Smart Shift"): common.NamedInts(Regular=0, Diverted=1, Mouse_Gestures=2)},
*responses_reprog_controls,
fake_hidpp.Response("00C4020000", 0x0530, "00C4020000"), # Smart Shift write
fake_hidpp.Response("00C4030000", 0x0530, "00C4030000"), # Smart Shift divert write
),
Setup(
FeatureTest(settings_templates.DivertKeys, {0xC4: 0}, {0xC4: 2}, 2, offset=0x05),
{common.NamedInt(0xC4, "Smart Shift"): common.NamedInts(Regular=0, Diverted=1, Mouse_Gestures=2, Sliding_DPI=3)},
*responses_reprog_controls,
fake_hidpp.Response("0A0001", 0x0000, "2201"), # ADJUSTABLE_DPI
fake_hidpp.Response("00C4300000", 0x0530, "00C4300000"), # Smart Shift write
fake_hidpp.Response("00C4030000", 0x0530, "00C4030000"), # Smart Shift divert write
),
Setup(
FeatureTest(settings_templates.PersistentRemappableAction, {80: 16797696, 81: 16797696}, {0x51: 16797952}, 3),
{
common.NamedInt(80, "Left Button"): special_keys.KEYS_KEYS_CONSUMER,
common.NamedInt(81, "Right Button"): special_keys.KEYS_KEYS_CONSUMER,
},
fake_hidpp.Response("050001", 0x0000, "1B04"), # REPROG_CONTROLS_V4
*responses_reprog_controls,
fake_hidpp.Response("0041", 0x0400),
fake_hidpp.Response("0201", 0x0410),
fake_hidpp.Response("02", 0x0400),
fake_hidpp.Response("0050", 0x0420, "00FF"), # left button
fake_hidpp.Response("0051", 0x0420, "01FF"), # right button
fake_hidpp.Response("0050000100500000", 0x0430, "0050FF"), # left button current
fake_hidpp.Response("0051000100500001", 0x0430, "0051FF"), # right button current
fake_hidpp.Response("0050FF01005000", 0x0440, "0050FF01005000"), # left button write
fake_hidpp.Response("0051FF01005000", 0x0440, "0051FF01005000"), # right button write
fake_hidpp.Response("0051FF01005100", 0x0440, "0051FF01005100"), # right button set write
),
Setup(
FeatureTest(
settings_templates.Gesture2Gestures,
{
1: True,
2: True,
30: True,
10: True,
45: False,
42: True,
43: True,
64: False,
65: False,
67: False,
84: True,
34: False,
},
{45: True},
4,
),
*fake_hidpp.responses_gestures,
fake_hidpp.Response("0001FF6F", 0x0420, "0001FF6F"), # write
fake_hidpp.Response("01010F04", 0x0420, "01010F04"),
fake_hidpp.Response("0001FF7F", 0x0420, "0001FF7F"), # write 45
fake_hidpp.Response("01010F04", 0x0420, "01010F04"),
),
Setup(
FeatureTest(
settings_templates.Gesture2Divert,
{1: False, 2: False, 10: False, 44: False, 64: False, 65: False, 67: False, 84: False, 85: False, 100: False},
{44: True},
4,
),
*fake_hidpp.responses_gestures,
fake_hidpp.Response("0001FF00", 0x0440, "0001FF00"), # write
fake_hidpp.Response("01010300", 0x0440, "01010300"),
fake_hidpp.Response("0001FF08", 0x0440, "0001FF08"), # write 44
fake_hidpp.Response("01010300", 0x0440, "01010300"),
),
Setup(
FeatureTest(settings_templates.Gesture2Params, {4: {"scale": 256}}, {4: {"scale": 128}}, 2),
*fake_hidpp.responses_gestures,
fake_hidpp.Response("000100FF000000000000000000000000", 0x0480, "000100FF"),
fake_hidpp.Response("000080FF000000000000000000000000", 0x0480, "000080FF"),
),
Setup(
FeatureTest(settings_templates.Equalizer, {0: -0x20, 1: 0x10}, {1: 0x18}, 2),
[-32, 32],
fake_hidpp.Response("0220000000", 0x0400),
fake_hidpp.Response("0000800100000000000000", 0x0410, "00"),
fake_hidpp.Response("E010", 0x0420, "00"),
fake_hidpp.Response("E010", 0x0430, "02E010"),
fake_hidpp.Response("E018", 0x0430, "02E018"),
),
Setup(
FeatureTest(settings_templates.PerKeyLighting, {1: -1, 2: -1, 9: -1, 10: -1, 113: -1}, {2: 0xFF0000}, 4, 4, 0, 1),
{
common.NamedInt(1, "A"): special_keys.COLORSPLUS,
common.NamedInt(2, "B"): special_keys.COLORSPLUS,
common.NamedInt(9, "I"): special_keys.COLORSPLUS,
common.NamedInt(10, "J"): special_keys.COLORSPLUS,
common.NamedInt(113, "KEY 113"): special_keys.COLORSPLUS,
},
fake_hidpp.Response("00000606000000000000000000000000", 0x0400, "0000"), # first group of keys
fake_hidpp.Response("00000200000000000000000000000000", 0x0400, "0001"), # second group of keys
fake_hidpp.Response("00000000000000000000000000000000", 0x0400, "0002"), # last group of keys
fake_hidpp.Response("02FF0000", 0x0410, "02FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("02FF0000", 0x0410, "02FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
),
Setup(
FeatureTest(
settings_templates.PerKeyLighting,
{1: -1, 2: -1, 9: -1, 10: -1, 113: -1},
{2: 0xFF0000, 9: 0xFF0000, 10: 0xFF0000},
8,
4,
0,
1,
),
{
common.NamedInt(1, "A"): special_keys.COLORSPLUS,
common.NamedInt(2, "B"): special_keys.COLORSPLUS,
common.NamedInt(9, "I"): special_keys.COLORSPLUS,
common.NamedInt(10, "J"): special_keys.COLORSPLUS,
common.NamedInt(113, "KEY 113"): special_keys.COLORSPLUS,
},
fake_hidpp.Response("00000606000000000000000000000000", 0x0400, "0000"), # first group of keys
fake_hidpp.Response("00000200000000000000000000000000", 0x0400, "0001"), # second group of keys
fake_hidpp.Response("00000000000000000000000000000000", 0x0400, "0002"), # last group of keys
fake_hidpp.Response("02FF0000", 0x0410, "02FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("09FF0000", 0x0410, "09FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("0AFF0000", 0x0410, "0AFF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("02FF000009FF00000AFF0000", 0x0410, "02FF000009FF00000AFF0000"), # write three values
fake_hidpp.Response("00", 0x0470, "00"), # finish
),
Setup(
FeatureTest(
settings_templates.PerKeyLighting,
{1: -1, 2: -1, 9: -1, 10: -1, 113: -1, 114: -1},
{1: 0xFF0000, 2: 0xFF0000, 9: 0xFF0000, 10: 0xFF0000, 113: 0x00FF00, 114: 0xFF0000},
15,
4,
0,
1,
),
{
common.NamedInt(1, "A"): special_keys.COLORSPLUS,
common.NamedInt(2, "B"): special_keys.COLORSPLUS,
common.NamedInt(9, "I"): special_keys.COLORSPLUS,
common.NamedInt(10, "J"): special_keys.COLORSPLUS,
common.NamedInt(113, "KEY 113"): special_keys.COLORSPLUS,
common.NamedInt(114, "KEY 114"): special_keys.COLORSPLUS,
},
fake_hidpp.Response("00000606000000000000000000000000", 0x0400, "0000"), # first group of keys
fake_hidpp.Response("00000600000000000000000000000000", 0x0400, "0001"), # second group of keys
fake_hidpp.Response("00000000000000000000000000000000", 0x0400, "0002"), # last group of keys
fake_hidpp.Response("01FF0000", 0x0410, "01FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("02FF0000", 0x0410, "02FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("09FF0000", 0x0410, "09FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("0AFF0000", 0x0410, "0AFF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("7100FF00", 0x0410, "7100FF00"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("72FF0000", 0x0410, "72FF0000"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
fake_hidpp.Response("FF00000102090A72", 0x460, "FF00000102090A72"), # write one value for five keys
fake_hidpp.Response("7100FF00", 0x0410, "7100FF00"), # write one value
fake_hidpp.Response("00", 0x0470, "00"), # finish
),
Setup(
FeatureTest(settings_templates.ExtendedAdjustableDpi, {0: 256}, {0: 512}, 2, offset=0x9),
{common.NamedInt(0, "X"): common.NamedInts.list([256, 512])},
fake_hidpp.Response("000000", 0x0910, "00"), # no y direction, no lod
fake_hidpp.Response("0000000100e10002000000", 0x0920, "000000"),
fake_hidpp.Response("00010000000000000000", 0x0950),
fake_hidpp.Response("000100000000", 0x0960, "000100000000"),
fake_hidpp.Response("000200000000", 0x0960, "000200000000"),
),
Setup(
FeatureTest(settings_templates.ExtendedAdjustableDpi, {0: 0x64, 1: 0xE4}, {0: 0x164}, 2, offset=0x9),
{
common.NamedInt(0, "X"): common.NamedInts.list([0x064, 0x074, 0x084, 0x0A4, 0x0C4, 0x0E4, 0x0124, 0x0164, 0x01C4]),
common.NamedInt(1, "Y"): common.NamedInts.list([0x064, 0x074, 0x084, 0x0A4, 0x0C4, 0x0E4, 0x0124, 0x0164]),
},
fake_hidpp.Response("000001", 0x0910, "00"), # supports y direction, no lod
fake_hidpp.Response("0000000064E0100084E02000C4E02000", 0x0920, "000000"),
fake_hidpp.Response("000001E4E0400124E0400164E06001C4", 0x0920, "000001"),
fake_hidpp.Response("00000000000000000000000000000000", 0x0920, "000002"),
fake_hidpp.Response("0000000064E0100084E02000C4E02000", 0x0920, "000100"),
fake_hidpp.Response("000001E4E0400124E040016400000000", 0x0920, "000101"),
fake_hidpp.Response("000064007400E4007400", 0x0950),
fake_hidpp.Response("00006400E400", 0x0960, "00006400E400"),
fake_hidpp.Response("00016400E400", 0x0960, "00016400E400"),
),
Setup(
FeatureTest(settings_templates.ExtendedAdjustableDpi, {0: 0x64, 1: 0xE4, 2: 1}, {1: 0x164}, 2, offset=0x9),
{
common.NamedInt(0, "X"): common.NamedInts.list([0x064, 0x074, 0x084, 0x0A4, 0x0C4, 0x0E4, 0x0124, 0x0164, 0x01C4]),
common.NamedInt(1, "Y"): common.NamedInts.list([0x064, 0x074, 0x084, 0x0A4, 0x0C4, 0x0E4, 0x0124, 0x0164]),
common.NamedInt(2, "LOD"): common.NamedInts(LOW=0, MEDIUM=1, HIGH=2),
},
fake_hidpp.Response("000003", 0x0910, "00"), # supports y direction and lod
fake_hidpp.Response("0000000064E0100084E02000C4E02000", 0x0920, "000000"),
fake_hidpp.Response("000001E4E0400124E0400164E06001C4", 0x0920, "000001"),
fake_hidpp.Response("00000000000000000000000000000000", 0x0920, "000002"),
fake_hidpp.Response("0000000064E0100084E02000C4E02000", 0x0920, "000100"),
fake_hidpp.Response("000001E4E0400124E040016400000000", 0x0920, "000101"),
fake_hidpp.Response("000064007400E4007401", 0x0950),
fake_hidpp.Response("00006400E401", 0x0960, "00006400E401"),
fake_hidpp.Response("000064016401", 0x0960, "000064016401"),
),
]
@pytest.mark.parametrize("test", key_tests)
def test_key_template(test, mocker):
tst = test.test
device = fake_hidpp.Device(responses=test.responses, feature=tst.sclass.feature, offset=tst.offset, version=tst.version)
spy_request = mocker.spy(device, "request")
print("FEATURE", tst.sclass.feature)
setting = settings_templates.check_feature(device, tst.sclass)
assert setting is not None
if isinstance(setting, list):
setting = setting[0]
if isinstance(test.choices, list):
assert setting._validator.min_value == test.choices[0]
assert setting._validator.max_value == test.choices[1]
elif test.choices is not None:
assert setting.choices == test.choices
value = setting.read(cached=False)
assert value == tst.initial_value
write_value = setting.write(value)
assert write_value == tst.initial_value
for key, val in tst.write_value.items():
write_value = setting.write_key_value(key, val)
assert write_value == val
value[key] = val
if tst.rewrite:
write_value = setting.write(value)
fake_hidpp.match_requests(tst.matched_calls, test.responses, spy_request.call_args_list)
@pytest.mark.parametrize(
"responses, currentSpeed, newSpeed",
[
(fake_hidpp.responses_speedchange, 100, 200),
(fake_hidpp.responses_speedchange, None, 250),
],
)
def test_SpeedChange_action(responses, currentSpeed, newSpeed, mocker):
device = fake_hidpp.Device(responses=responses, feature=hidpp20_constants.SupportedFeature.POINTER_SPEED)
spy_setting_callback = mocker.spy(device, "setting_callback")
settings_templates.check_feature_settings(device, device.settings) # need to set up all the settings
device.persister = {"pointer_speed": currentSpeed, "_speed-change": newSpeed}
speed_setting = next(filter(lambda s: s.name == "speed-change", device.settings), None)
pointer_setting = next(filter(lambda s: s.name == "pointer_speed", device.settings), None)
speed_setting.write(237)
speed_setting._rw.press_action()
if newSpeed is not None and speed_setting is not None:
spy_setting_callback.assert_any_call(device, type(pointer_setting), [newSpeed])
assert device.persister["_speed-change"] == currentSpeed
assert device.persister["pointer_speed"] == newSpeed
@pytest.mark.parametrize("test", simple_tests + key_tests)
def test_check_feature_settings(test, mocker):
tst = test.test
device = fake_hidpp.Device(responses=test.responses, feature=tst.sclass.feature, offset=tst.offset, version=tst.version)
already_known = []
setting = settings_templates.check_feature_settings(device, already_known)
assert setting is True
assert already_known
@pytest.mark.parametrize(
"test",
[
Setup(
FeatureTest(settings_templates.K375sFnSwap, False, True, offset=0x06),
fake_hidpp.Response("FF0001", 0x0600, "FF"),
fake_hidpp.Response("FF0101", 0x0610, "FF01"),
)
],
)
def test_check_feature_setting(test, mocker):
tst = test.test
device = fake_hidpp.Device(responses=test.responses, feature=tst.sclass.feature, offset=tst.offset, version=tst.version)
setting = settings_templates.check_feature_setting(device, tst.sclass.name)
assert setting
| 38,737 | Python | .py | 790 | 41.370886 | 127 | 0.659427 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,524 | test_hidpp10.py | pwr-Solaar_Solaar/tests/logitech_receiver/test_hidpp10.py | from dataclasses import dataclass
from dataclasses import field
from typing import Any
from typing import List
from typing import Optional
import pytest
from logitech_receiver import common
from logitech_receiver import hidpp10
from logitech_receiver import hidpp10_constants
from logitech_receiver.hidpp10_constants import Registers
_hidpp10 = hidpp10.Hidpp10()
@dataclass
class Response:
response: Optional[str]
request_id: int
params: Any
@dataclass
class Device:
name: str = "Device"
online: bool = True
kind: str = "fake"
protocol: float = 1.0
isDevice: bool = False # incorrect, but useful here
registers: List[Registers] = field(default_factory=list)
responses: List[Response] = field(default_factory=list)
def request(self, id, params=None, no_reply=False):
if params is None:
params = []
print("REQUEST ", self.name, hex(id), params)
for r in self.responses:
if id == r.request_id and params == r.params:
print("RESPONSE", self.name, hex(r.request_id), r.params, r.response)
return bytes.fromhex(r.response) if r.response is not None else None
device_offline = Device("OFFLINE", False)
device_leds = Device("LEDS", True, registers=[Registers.THREE_LEDS, Registers.BATTERY_STATUS])
device_features = Device("FEATURES", True, protocol=4.5)
registers_standard = [Registers.BATTERY_STATUS, Registers.FIRMWARE]
responses_standard = [
Response("555555", 0x8100 | Registers.BATTERY_STATUS, 0x00),
Response("666666", 0x8100 | Registers.BATTERY_STATUS, 0x10),
Response("777777", 0x8000 | Registers.BATTERY_STATUS, 0x00),
Response("888888", 0x8000 | Registers.BATTERY_STATUS, 0x10),
Response("052100", 0x8100 | Registers.BATTERY_STATUS, []),
Response("ABCDEF", 0x8100 | Registers.FIRMWARE, 0x01),
Response("ABCDEF", 0x8100 | Registers.FIRMWARE, 0x02),
Response("ABCDEF", 0x8100 | Registers.FIRMWARE, 0x03),
Response("ABCDEF", 0x8100 | Registers.FIRMWARE, 0x04),
Response("000900", 0x8100 | Registers.NOTIFICATIONS, []),
Response("101010", 0x8100 | Registers.MOUSE_BUTTON_FLAGS, []),
Response("010101", 0x8100 | Registers.KEYBOARD_FN_SWAP, []),
Response("020202", 0x8100 | Registers.DEVICES_CONFIGURATION, []),
Response("030303", 0x8000 | Registers.DEVICES_CONFIGURATION, 0x00),
]
device_standard = Device("STANDARD", True, registers=registers_standard, responses=responses_standard)
@pytest.mark.parametrize(
"device, register, param, expected_result",
[
(device_offline, Registers.THREE_LEDS, 0x00, None),
(device_standard, Registers.THREE_LEDS, 0x00, None),
(device_standard, Registers.BATTERY_STATUS, 0x00, "555555"),
(device_standard, Registers.BATTERY_STATUS, 0x10, "666666"),
],
)
def test_read_register(device, register, param, expected_result, mocker):
spy_request = mocker.spy(device, "request")
result = hidpp10.read_register(device, register, param)
assert result == (bytes.fromhex(expected_result) if expected_result else None)
spy_request.assert_called_once_with(0x8100 | register, param)
@pytest.mark.parametrize(
"device, register, param, expected_result",
[
(device_offline, Registers.THREE_LEDS, 0x00, None),
(device_standard, Registers.THREE_LEDS, 0x00, None),
(device_standard, Registers.BATTERY_STATUS, 0x00, "777777"),
(device_standard, Registers.BATTERY_STATUS, 0x10, "888888"),
],
)
def test_write_register(device, register, param, expected_result, mocker):
spy_request = mocker.spy(device, "request")
result = hidpp10.write_register(device, register, param)
assert result == (bytes.fromhex(expected_result) if expected_result else None)
spy_request.assert_called_once_with(0x8000 | register, param)
def device_charge(name, response):
responses = [Response(response, 0x8100 | Registers.BATTERY_CHARGE, [])]
return Device(name, registers=[], responses=responses)
device_charge1 = device_charge("DISCHARGING", "550030")
device_charge2 = device_charge("RECHARGING", "440050")
device_charge3 = device_charge("FULL", "600090")
device_charge4 = device_charge("OTHER", "220000")
def device_status(name, response):
responses = [Response(response, 0x8100 | Registers.BATTERY_STATUS, [])]
return Device(name, registers=[], responses=responses)
device_status1 = device_status("FULL", "072200")
device_status2 = device_status("GOOD", "052100")
device_status3 = device_status("LOW", "032200")
device_status4 = device_status("CRITICAL", "010100")
device_status5 = device_status("EMPTY", "000000")
device_status6 = device_status("NOSTATUS", "002200")
@pytest.mark.parametrize(
"device, expected_result, expected_register",
[
(device_offline, None, None),
(device_features, None, None),
(device_leds, None, None),
(
device_standard,
common.Battery(common.BatteryLevelApproximation.GOOD, None, common.BatteryStatus.RECHARGING, None),
Registers.BATTERY_STATUS,
),
(device_charge1, common.Battery(0x55, None, common.BatteryStatus.DISCHARGING, None), Registers.BATTERY_CHARGE),
(
device_charge2,
common.Battery(0x44, None, common.BatteryStatus.RECHARGING, None),
Registers.BATTERY_CHARGE,
),
(
device_charge3,
common.Battery(0x60, None, common.BatteryStatus.FULL, None),
Registers.BATTERY_CHARGE,
),
(device_charge4, common.Battery(0x22, None, None, None), Registers.BATTERY_CHARGE),
(
device_status1,
common.Battery(common.BatteryLevelApproximation.FULL, None, common.BatteryStatus.FULL, None),
Registers.BATTERY_STATUS,
),
(
device_status2,
common.Battery(common.BatteryLevelApproximation.GOOD, None, common.BatteryStatus.RECHARGING, None),
Registers.BATTERY_STATUS,
),
(
device_status3,
common.Battery(common.BatteryLevelApproximation.LOW, None, common.BatteryStatus.FULL, None),
Registers.BATTERY_STATUS,
),
(
device_status4,
common.Battery(common.BatteryLevelApproximation.CRITICAL, None, None, None),
Registers.BATTERY_STATUS,
),
(
device_status5,
common.Battery(common.BatteryLevelApproximation.EMPTY, None, common.BatteryStatus.DISCHARGING, None),
Registers.BATTERY_STATUS,
),
(
device_status6,
common.Battery(None, None, common.BatteryStatus.FULL, None),
Registers.BATTERY_STATUS,
),
],
)
def test_hidpp10_get_battery(device, expected_result, expected_register):
result = _hidpp10.get_battery(device)
assert result == expected_result
if expected_register is not None:
assert expected_register in device.registers
@pytest.mark.parametrize(
"device, expected_firmwares",
[
(device_offline, []),
(
device_standard,
[
common.FirmwareKind.Firmware,
common.FirmwareKind.Bootloader,
common.FirmwareKind.Other,
],
),
],
)
def test_hidpp10_get_firmware(device, expected_firmwares):
firmwares = _hidpp10.get_firmware(device)
if not expected_firmwares:
assert firmwares is None
else:
firmware_types = [firmware.kind for firmware in firmwares]
assert firmware_types == expected_firmwares
assert len(firmwares) == len(expected_firmwares)
@pytest.mark.parametrize(
"device, level, charging, warning, p1, p2",
[
(device_leds, common.BatteryLevelApproximation.EMPTY, False, False, 0x33, 0x00),
(device_leds, common.BatteryLevelApproximation.CRITICAL, False, False, 0x22, 0x00),
(device_leds, common.BatteryLevelApproximation.LOW, False, False, 0x20, 0x00),
(device_leds, common.BatteryLevelApproximation.GOOD, False, False, 0x20, 0x02),
(device_leds, common.BatteryLevelApproximation.FULL, False, False, 0x20, 0x22),
(device_leds, None, True, False, 0x30, 0x33),
(device_leds, None, False, True, 0x02, 0x00),
(device_leds, None, False, False, 0x11, 0x11),
],
)
def test_set_3leds(device, level, charging, warning, p1, p2, mocker):
spy_request = mocker.spy(device, "request")
_hidpp10.set_3leds(device, level, charging, warning)
spy_request.assert_called_once_with(0x8000 | Registers.THREE_LEDS, p1, p2)
@pytest.mark.parametrize("device", [device_offline, device_features])
def test_set_3leds_missing(device, mocker):
spy_request = mocker.spy(device, "request")
_hidpp10.set_3leds(device)
assert spy_request.call_count == 0
@pytest.mark.parametrize("device", [device_standard])
def test_get_notification_flags(device):
result = _hidpp10.get_notification_flags(device)
assert result == int("000900", 16)
def test_set_notification_flags(mocker):
device = device_standard
spy_request = mocker.spy(device, "request")
result = _hidpp10.set_notification_flags(
device, hidpp10_constants.NOTIFICATION_FLAG.battery_status, hidpp10_constants.NOTIFICATION_FLAG.wireless
)
spy_request.assert_called_once_with(0x8000 | Registers.NOTIFICATIONS, b"\x10\x01\x00")
assert result is not None
def test_set_notification_flags_bad(mocker):
device = device_features
spy_request = mocker.spy(device, "request")
result = _hidpp10.set_notification_flags(
device, hidpp10_constants.NOTIFICATION_FLAG.battery_status, hidpp10_constants.NOTIFICATION_FLAG.wireless
)
assert spy_request.call_count == 0
assert result is None
def test_get_device_features():
result = _hidpp10.get_device_features(device_standard)
assert result == int("101010", 16)
@pytest.mark.parametrize(
"device, register, expected_result",
[
(device_standard, Registers.BATTERY_STATUS, "052100"),
(device_standard, Registers.MOUSE_BUTTON_FLAGS, "101010"),
(device_standard, Registers.KEYBOARD_ILLUMINATION, None),
(device_features, Registers.KEYBOARD_ILLUMINATION, None),
],
)
def test_get_register(device, register, expected_result):
result = _hidpp10._get_register(device, register)
assert result == (int(expected_result, 16) if expected_result is not None else None)
@pytest.mark.parametrize(
"device, expected_result",
[
(device_standard, 2),
(device_features, None),
],
)
def test_get_configuration_pending_flags(device, expected_result):
result = hidpp10.get_configuration_pending_flags(device)
assert result == expected_result
@pytest.mark.parametrize(
"device, expected_result",
[
(device_standard, True),
(device_features, False),
],
)
def test_set_configuration_pending_flags(device, expected_result):
result = hidpp10.set_configuration_pending_flags(device, 0x00)
assert result == expected_result
| 11,131 | Python | .py | 257 | 36.910506 | 119 | 0.691859 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,525 | test_keysymdef.py | pwr-Solaar_Solaar/tests/test_keysyms/test_keysymdef.py | from keysyms import keysymdef
def test_keysymdef():
key_mapping = keysymdef.key_symbols
assert key_mapping["0"] == 48
assert key_mapping["A"] == 65
assert key_mapping["a"] == 97
| 197 | Python | .py | 6 | 28.666667 | 39 | 0.680851 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,526 | test_about_dialog.py | pwr-Solaar_Solaar/tests/solaar/ui/test_about_dialog.py | from solaar.ui.about import about
from solaar.ui.about.model import AboutModel
def test_about_model():
expected_name = "Daniel Pavel"
model = AboutModel()
authors = model.get_authors()
assert expected_name in authors[0]
def test_about_dialog(mocker):
view_mock = mocker.Mock()
about.show(view=view_mock)
assert view_mock.init_ui.call_count == 1
assert view_mock.update_version_info.call_count == 1
assert view_mock.update_description.call_count == 1
assert view_mock.update_authors.call_count == 1
assert view_mock.update_credits.call_count == 1
assert view_mock.update_copyright.call_count == 1
assert view_mock.update_translators.call_count == 1
assert view_mock.update_website.call_count == 1
assert view_mock.show.call_count == 1
| 802 | Python | .py | 19 | 37.631579 | 56 | 0.729032 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,527 | test_desktop_notifications.py | pwr-Solaar_Solaar/tests/solaar/ui/test_desktop_notifications.py | from unittest import mock
from solaar.ui import desktop_notifications
def test_notifications_available():
result = desktop_notifications.notifications_available()
assert not result
def test_init():
assert not desktop_notifications.init()
def test_uninit():
assert desktop_notifications.uninit() is None
def test_alert():
reason = "unknown"
assert desktop_notifications.alert(reason) is None
def test_show():
dev = mock.MagicMock()
reason = "unknown"
assert desktop_notifications.show(dev, reason) is None
| 553 | Python | .py | 16 | 30.5625 | 60 | 0.761905 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,528 | test_pair_window.py | pwr-Solaar_Solaar/tests/solaar/ui/test_pair_window.py | from dataclasses import dataclass
from dataclasses import field
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from unittest import mock
import gi
import pytest
from logitech_receiver import receiver
from solaar.ui import pair_window
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk # NOQA: E402
gtk_init = Gtk.init_check()[0]
@dataclass
class Device:
name: str = "test device"
kind: str = "test kind"
@dataclass
class Receiver:
find_paired_node_wpid_func: Callable[[str, int], Any]
name: str
receiver_kind: str
_set_lock: bool = True
pairing: receiver.Pairing = field(default_factory=receiver.Pairing)
pairable: bool = True
_remaining_pairings: Optional[int] = None
def reset_pairing(self):
self.receiver = receiver.Pairing()
def remaining_pairings(self, cache=True):
return self._remaining_pairings
def set_lock(self, value=False, timeout=0):
self.pairing.lock_open = self._set_lock
return self._set_lock
def discover(self, cancel=False, timeout=30):
self.pairing.discovering = self._set_lock
return self._set_lock
def pair_device(self, pair=True, slot=0, address=b"\0\0\0\0\0\0", authentication=0x00, entropy=20, force=False):
print("PD", self.pairable)
return self.pairable
@dataclass
class Assistant:
drawable: bool = True
pages: List[Any] = field(default_factory=list)
def is_drawable(self):
return self.drawable
def next_page(self):
return True
def set_page_complete(self, page, b):
return True
def commit(self):
return True
def append_page(self, page):
self.pages.append(page)
def remove_page(self, page):
return True
def set_page_type(self, page, type):
return True
def destroy(self):
pass
@pytest.mark.skipif(not gtk_init, reason="requires Gtk")
@pytest.mark.parametrize(
"receiver, lock_open, discovering, page_type",
[
(Receiver(mock.Mock(), "unifying", "unifying", True), True, False, Gtk.AssistantPageType.PROGRESS),
(Receiver(mock.Mock(), "unifying", "unifying", False), False, False, Gtk.AssistantPageType.SUMMARY),
(Receiver(mock.Mock(), "nano", "nano", True, _remaining_pairings=5), True, False, Gtk.AssistantPageType.PROGRESS),
(Receiver(mock.Mock(), "nano", "nano", False), False, False, Gtk.AssistantPageType.SUMMARY),
(Receiver(mock.Mock(), "bolt", "bolt", True), False, True, Gtk.AssistantPageType.PROGRESS),
(Receiver(mock.Mock(), "bolt", "bolt", False), False, False, Gtk.AssistantPageType.SUMMARY),
],
)
def test_create(receiver, lock_open, discovering, page_type):
assistant = pair_window.create(receiver)
assert assistant is not None
assert assistant.get_page_type(assistant.get_nth_page(0)) == page_type
assert receiver.pairing.lock_open == lock_open
assert receiver.pairing.discovering == discovering
@pytest.mark.parametrize(
"receiver, expected_result, expected_error",
[
(Receiver(mock.Mock(), "unifying", "unifying", True), True, False),
(Receiver(mock.Mock(), "unifying", "unifying", False), False, True),
(Receiver(mock.Mock(), "bolt", "bolt", True), True, False),
(Receiver(mock.Mock(), "bolt", "bolt", False), False, True),
],
)
def test_prepare(receiver, expected_result, expected_error):
result = pair_window.prepare(receiver)
assert result == expected_result
assert bool(receiver.pairing.error) == expected_error
@pytest.mark.parametrize("assistant, expected_result", [(Assistant(True), True), (Assistant(False), False)])
def test_check_lock_state_drawable(assistant, expected_result):
r = Receiver(mock.Mock(), "succeed", "unifying", True, receiver.Pairing(lock_open=True))
result = pair_window.check_lock_state(assistant, r, 2)
assert result == expected_result
@pytest.mark.skipif(not gtk_init, reason="requires Gtk")
@pytest.mark.parametrize(
"receiver, count, expected_result",
[
(Receiver(mock.Mock(), "fail", "unifying", False, receiver.Pairing(lock_open=False)), 2, False),
(Receiver(mock.Mock(), "succeed", "unifying", True, receiver.Pairing(lock_open=True)), 1, True),
(Receiver(mock.Mock(), "error", "unifying", True, receiver.Pairing(error="error")), 0, False),
(Receiver(mock.Mock(), "new device", "unifying", True, receiver.Pairing(new_device=Device())), 2, False),
(Receiver(mock.Mock(), "closed", "unifying", True, receiver.Pairing()), 2, False),
(Receiver(mock.Mock(), "closed", "unifying", True, receiver.Pairing()), 1, False),
(Receiver(mock.Mock(), "closed", "unifying", True, receiver.Pairing()), 0, False),
(Receiver(mock.Mock(), "fail bolt", "bolt", False), 1, False),
(Receiver(mock.Mock(), "succeed bolt", "bolt", True, receiver.Pairing(lock_open=True)), 0, True),
(Receiver(mock.Mock(), "error bolt", "bolt", True, receiver.Pairing(error="error")), 2, False),
(Receiver(mock.Mock(), "new device", "bolt", True, receiver.Pairing(lock_open=True, new_device=Device())), 1, False),
(Receiver(mock.Mock(), "discovering", "bolt", True, receiver.Pairing(lock_open=True)), 1, True),
(Receiver(mock.Mock(), "closed", "bolt", True, receiver.Pairing()), 2, False),
(Receiver(mock.Mock(), "closed", "bolt", True, receiver.Pairing()), 1, False),
(Receiver(mock.Mock(), "closed", "bolt", True, receiver.Pairing()), 0, False),
(
Receiver(
mock.Mock(),
"pass1",
"bolt",
True,
receiver.Pairing(lock_open=True, device_passkey=50, device_authentication=0x01),
),
0,
True,
),
(
Receiver(
mock.Mock(),
"pass2",
"bolt",
True,
receiver.Pairing(lock_open=True, device_passkey=50, device_authentication=0x02),
),
0,
True,
),
(
Receiver(
mock.Mock(),
"adt",
"bolt",
True,
receiver.Pairing(discovering=True, device_address=2, device_name=5),
pairable=True,
),
2,
True,
),
(
Receiver(
mock.Mock(),
"adf",
"bolt",
True,
receiver.Pairing(discovering=True, device_address=2, device_name=5),
pairable=False,
),
2,
False,
),
(Receiver(mock.Mock(), "add fail", "bolt", False, receiver.Pairing(device_address=2, device_passkey=5)), 2, False),
],
)
def test_check_lock_state(receiver, count, expected_result):
assistant = Assistant(True)
check_state = pair_window._check_lock_state(assistant, receiver, count)
assert check_state == expected_result
@pytest.mark.parametrize(
"receiver, pair_device, set_lock, discover, error",
[
(
Receiver(mock.Mock(), "unifying", "unifying", pairing=receiver.Pairing(lock_open=False, error="error")),
0,
0,
0,
None,
),
(
Receiver(mock.Mock(), "unifying", "unifying", pairing=receiver.Pairing(lock_open=True, error="error")),
0,
1,
0,
"error",
),
(Receiver(mock.Mock(), "bolt", "bolt", pairing=receiver.Pairing(lock_open=False, error="error")), 0, 0, 0, None),
(Receiver(mock.Mock(), "bolt", "bolt", pairing=receiver.Pairing(lock_open=True, error="error")), 1, 0, 0, "error"),
(Receiver(mock.Mock(), "bolt", "bolt", pairing=receiver.Pairing(discovering=True, error="error")), 0, 0, 1, "error"),
],
)
def test_finish(receiver, pair_device, set_lock, discover, error, mocker):
spy_pair_device = mocker.spy(receiver, "pair_device")
spy_set_lock = mocker.spy(receiver, "set_lock")
spy_discover = mocker.spy(receiver, "discover")
assistant = Assistant(True)
pair_window._finish(assistant, receiver)
assert spy_pair_device.call_count == pair_device
assert spy_set_lock.call_count == set_lock
assert spy_discover.call_count == discover
assert receiver.pairing.error == error
@pytest.mark.skipif(not gtk_init, reason="requires Gtk")
@pytest.mark.parametrize("error", ["timeout", "device not supported", "too many devices"])
def test_create_failure_page(error, mocker):
spy_create = mocker.spy(pair_window, "_create_page")
pair_window._pairing_failed(Assistant(True), Receiver(mock.Mock(), "nano", "nano"), error)
assert spy_create.call_count == 1
| 8,887 | Python | .py | 206 | 35.276699 | 125 | 0.625478 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,529 | test_common.py | pwr-Solaar_Solaar/tests/solaar/ui/test_common.py | from unittest import mock
from unittest.mock import PropertyMock
import pytest
from solaar.ui import common
@pytest.mark.parametrize(
"reason, expected_in_title, expected_in_text",
[
(
"permissions",
"Permissions error",
"not have permission to open",
),
("nodevice", "connect to device error", "error connecting"),
("unpair", "Unpairing failed", "receiver returned an error"),
],
)
def test_create_error_text(reason, expected_in_title, expected_in_text):
obj = mock.Mock()
obj.name = PropertyMock(return_value="test")
title, text = common._create_error_text(reason, obj)
assert expected_in_title in title
assert expected_in_text in text
| 744 | Python | .py | 22 | 28 | 72 | 0.670391 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,530 | test_i18n.py | pwr-Solaar_Solaar/tests/solaar/ui/test_i18n.py | import locale
import os
import platform
import pytest
from solaar import i18n
@pytest.fixture
def set_locale_de():
backup_lang = os.environ.get("LC_ALL", "")
try:
yield
finally:
os.environ["LC_ALL"] = backup_lang
i18n.set_locale_to_system_default()
@pytest.mark.skipif(platform.system() == "Linux", reason="Adapt test for Linux")
def test_set_locale_to_system_default(set_locale_de):
os.environ["LC_ALL"] = "de_DE.UTF-8"
i18n.set_locale_to_system_default()
language, encoding = locale.getlocale()
assert language == "de_DE"
assert encoding == "UTF-8"
| 615 | Python | .py | 20 | 26.55 | 80 | 0.688245 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,531 | test_hidapi.py | pwr-Solaar_Solaar/tests/hidapi/test_hidapi.py | import platform
from unittest import mock
if platform.system() == "Linux":
import hidapi.udev_impl as hidapi
else:
import hidapi.hidapi_impl as hidapi
def test_find_paired_node():
hidapi.enumerate(mock.Mock())
| 226 | Python | .py | 8 | 25.25 | 39 | 0.761682 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,532 | test_data.py | pwr-Solaar_Solaar/tests/hid_parser/test_data.py | from hid_parser.data import Button
from hid_parser.data import Consumer
def test_consumer():
consumer = Consumer()
assert consumer.PLAY_PAUSE == 0xCD
def test_button():
button = Button()
assert button.NO_BUTTON == 0x0
assert button.BUTTON_1 == 0x1
| 274 | Python | .py | 9 | 26.555556 | 38 | 0.725869 | pwr-Solaar/Solaar | 5,327 | 400 | 31 | GPL-2.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,533 | hamster-cli.py | projecthamster_hamster/src/hamster-cli.py | #!/usr/bin/env python3
# - coding: utf-8 -
# Copyright (C) 2010 Matías Ribecky <matias at mribecky.com.ar>
# Copyright (C) 2010-2012 Toms Bauģis <toms.baugis@gmail.com>
# Copyright (C) 2012 Ted Smith <tedks at cs.umd.edu>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
'''A script to control the applet from the command line.'''
import sys, os
import argparse
import re
import gi
gi.require_version('Gdk', '3.0') # noqa: E402
gi.require_version('Gtk', '3.0') # noqa: E402
from gi.repository import GLib as glib
from gi.repository import Gdk as gdk
from gi.repository import Gtk as gtk
from gi.repository import Gio as gio
from gi.repository import GLib as glib
import hamster
from hamster import client, reports
from hamster import logger as hamster_logger
from hamster.about import About
from hamster.edit_activity import CustomFactController
from hamster.overview import Overview
from hamster.preferences import PreferencesEditor
from hamster.lib import default_logger, stuff
from hamster.lib import datetime as dt
from hamster.lib.fact import Fact
logger = default_logger(__file__)
def word_wrap(line, max_len):
"""primitive word wrapper"""
lines = []
cur_line, cur_len = "", 0
for word in line.split():
if len("%s %s" % (cur_line, word)) < max_len:
cur_line = ("%s %s" % (cur_line, word)).strip()
else:
if cur_line:
lines.append(cur_line)
cur_line = word
if cur_line:
lines.append(cur_line)
return lines
def fact_dict(fact_data, with_date):
fact = {}
if with_date:
fmt = '%Y-%m-%d %H:%M'
else:
fmt = '%H:%M'
fact['start'] = fact_data.start_time.strftime(fmt)
if fact_data.end_time:
fact['end'] = fact_data.end_time.strftime(fmt)
else:
end_date = dt.datetime.now()
fact['end'] = ''
fact['duration'] = fact_data.delta.format()
fact['activity'] = fact_data.activity
fact['category'] = fact_data.category
if fact_data.tags:
fact['tags'] = ' '.join('#%s' % tag for tag in fact_data.tags)
else:
fact['tags'] = ''
fact['description'] = fact_data.description
return fact
class Hamster(gtk.Application):
"""Hamster gui.
Actions should eventually be accessible via Gio.DBusActionGroup
with the 'org.gnome.Hamster.GUI' id.
but that is still experimental, the actions API is subject to change.
Discussion with "external" developers welcome !
The separate dbus org.gnome.Hamster.WindowServer
is still the stable recommended way to show windows for now.
"""
def __init__(self):
# inactivity_timeout: How long (ms) the service should stay alive
# after all windows have been closed.
gtk.Application.__init__(self,
application_id="org.gnome.Hamster.GUI",
#inactivity_timeout=10000,
register_session=True)
self.about_controller = None # 'about' window controller
self.fact_controller = None # fact window controller
self.overview_controller = None # overview window controller
self.preferences_controller = None # settings window controller
self.connect("startup", self.on_startup)
self.connect("activate", self.on_activate)
# we need them before the startup phase
# so register/activate_action work before the app is ran.
# cf. https://gitlab.gnome.org/GNOME/glib/blob/master/gio/tests/gapplication-example-actions.c
self.add_actions()
def add_actions(self):
# most actions have no parameters
# for type "i", use Variant.new_int32() and .get_int32() to pack/unpack
for name in ("about", "add", "clone", "edit", "overview", "preferences"):
data_type = glib.VariantType("i") if name in ("edit", "clone") else None
action = gio.SimpleAction.new(name, data_type)
action.connect("activate", self.on_activate_window)
self.add_action(action)
action = gio.SimpleAction.new("quit", None)
action.connect("activate", self.on_activate_quit)
self.add_action(action)
def on_activate(self, data=None):
logger.debug("activate")
if not self.get_windows():
self.activate_action("overview")
def on_activate_window(self, action=None, data=None):
self._open_window(action.get_name(), data)
def on_activate_quit(self, data=None):
self.on_activate_quit()
def on_startup(self, data=None):
logger.debug("startup")
# Must be the same as application_id. Won't be required with gtk4.
glib.set_prgname(self.get_application_id())
# localized name, but let's keep it simple.
glib.set_application_name("Hamster")
def _open_window(self, name, data=None):
logger.debug("opening '{}'".format(name))
if name == "about":
if not self.about_controller:
# silence warning "GtkDialog mapped without a transient parent"
# https://stackoverflow.com/a/38408127/3565696
_dummy = gtk.Window()
self.about_controller = About(parent=_dummy)
logger.debug("new About")
controller = self.about_controller
elif name in ("add", "clone", "edit"):
if self.fact_controller:
# Something is already going on, with other arguments, present it.
# Or should we just discard the forgotten one ?
logger.warning("Fact controller already active. Please close first.")
else:
fact_id = data.get_int32() if data else None
self.fact_controller = CustomFactController(name, fact_id=fact_id)
logger.debug("new CustomFactController")
controller = self.fact_controller
elif name == "overview":
if not self.overview_controller:
self.overview_controller = Overview()
logger.debug("new Overview")
controller = self.overview_controller
elif name == "preferences":
if not self.preferences_controller:
self.preferences_controller = PreferencesEditor()
logger.debug("new PreferencesEditor")
controller = self.preferences_controller
window = controller.window
if window not in self.get_windows():
self.add_window(window)
logger.debug("window added")
# Essential for positioning on wayland.
# This should also select the correct window type if unset yet.
# https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html
if name != "overview" and self.overview_controller:
window.set_transient_for(self.overview_controller.window)
# so the dialog appears on top of the transient-for:
window.set_type_hint(gdk.WindowTypeHint.DIALOG)
else:
# toplevel
window.set_transient_for(None)
controller.present()
logger.debug("window presented")
def present_fact_controller(self, action, fact_id=0):
"""Present the fact controller window to add, clone or edit a fact.
Args:
action (str): "add", "clone" or "edit"
"""
assert action in ("add", "clone", "edit")
if action in ("clone", "edit"):
action_data = glib.Variant.new_int32(int(fact_id))
else:
action_data = None
# always open dialogs through actions,
# both for consistency, and to reduce the paths to test.
app.activate_action(action, action_data)
class HamsterCli(object):
"""Command line interface."""
def __init__(self):
self.storage = client.Storage()
def assist(self, *args):
assist_command = args[0] if args else ""
if assist_command == "start":
hamster_client._activities(sys.argv[-1])
elif assist_command == "export":
formats = "html tsv xml ical".split()
chosen = sys.argv[-1]
formats = [f for f in formats if not chosen or f.startswith(chosen)]
print("\n".join(formats))
def toggle(self):
self.storage.toggle()
def start(self, *args):
'''Start a new activity.'''
if not args:
print("Error: please specify activity")
return 0
fact = Fact.parse(" ".join(args), range_pos="tail")
if fact.start_time is None:
fact.start_time = dt.datetime.now()
self.storage.check_fact(fact, default_day=dt.hday.today())
id_ = self.storage.add_fact(fact)
return id_
def stop(self, *args):
'''Stop tracking the current activity.'''
self.storage.stop_tracking()
def export(self, *args):
args = args or []
export_format, start_time, end_time = "html", None, None
if args:
export_format = args[0]
(start_time, end_time), __ = dt.Range.parse(" ".join(args[1:]))
start_time = start_time or dt.datetime.combine(dt.date.today(), dt.time())
end_time = end_time or start_time.replace(hour=23, minute=59, second=59)
facts = self.storage.get_facts(start_time, end_time)
writer = reports.simple(facts, start_time.date(), end_time.date(), export_format)
def _activities(self, search=""):
'''Print the names of all the activities.'''
if "@" in search:
activity, category = search.split("@")
for cat in self.storage.get_categories():
if not category or cat['name'].lower().startswith(category.lower()):
print("{}@{}".format(activity, cat['name']))
else:
for activity in self.storage.get_activities(search):
print(activity['name'])
if activity['category']:
print("{}@{}".format(activity['name'], activity['category']))
def activities(self, *args):
'''Print the names of all the activities.'''
search = args[0] if args else ""
for activity in self.storage.get_activities(search):
print("{}@{}".format(activity['name'], activity['category']))
def categories(self, *args):
'''Print the names of all the categories.'''
for category in self.storage.get_categories():
print(category['name'])
def list(self, *times):
"""list facts within a date range"""
(start_time, end_time), __ = dt.Range.parse(" ".join(times or []))
start_time = start_time or dt.datetime.combine(dt.date.today(), dt.time())
end_time = end_time or start_time.replace(hour=23, minute=59, second=59)
self._list(start_time, end_time)
def current(self, *args):
"""prints current activity. kinda minimal right now"""
facts = self.storage.get_todays_facts()
if facts and not facts[-1].end_time:
print("{} {}".format(str(facts[-1]).strip(),
facts[-1].delta.format(fmt="HH:MM")))
else:
print((_("No activity")))
def search(self, *args):
"""search for activities by name and optionally within a date range"""
args = args or []
search = ""
if args:
search = args[0]
(start_time, end_time), __ = dt.Range.parse(" ".join(args[1:]))
start_time = start_time or dt.datetime.combine(dt.date.today(), dt.time())
end_time = end_time or start_time.replace(hour=23, minute=59, second=59)
self._list(start_time, end_time, search)
def _list(self, start_time, end_time, search=""):
"""Print a listing of activities"""
facts = self.storage.get_facts(start_time, end_time, search)
headers = {'activity': _("Activity"),
'category': _("Category"),
'tags': _("Tags"),
'description': _("Description"),
'start': _("Start"),
'end': _("End"),
'duration': _("Duration")}
# print date if it is not the same day
print_with_date = start_time.date() != end_time.date()
cols = 'start', 'end', 'duration', 'activity', 'category'
widths = dict([(col, len(headers[col])) for col in cols])
for fact in facts:
fact = fact_dict(fact, print_with_date)
for col in cols:
widths[col] = max(widths[col], len(fact[col]))
cols = ["{{{col}: <{len}}}".format(col=col, len=widths[col]) for col in cols]
fact_line = " | ".join(cols)
row_width = sum(val + 3 for val in list(widths.values()))
print()
print(fact_line.format(**headers))
print("-" * min(row_width, 80))
by_cat = {}
for fact in facts:
cat = fact.category or _("Unsorted")
by_cat.setdefault(cat, dt.timedelta(0))
by_cat[cat] += fact.delta
pretty_fact = fact_dict(fact, print_with_date)
print(fact_line.format(**pretty_fact))
if pretty_fact['description']:
for line in word_wrap(pretty_fact['description'], 76):
print(" {}".format(line))
if pretty_fact['tags']:
for line in word_wrap(pretty_fact['tags'], 76):
print(" {}".format(line))
print("-" * min(row_width, 80))
cats = []
total_duration = dt.timedelta()
for cat, duration in sorted(by_cat.items(), key=lambda x: x[1], reverse=True):
cats.append("{}: {}".format(cat, duration.format()))
total_duration += duration
for line in word_wrap(", ".join(cats), 80):
print(line)
print("Total: ", total_duration.format())
print()
def version(self):
print(hamster.__version__)
if __name__ == '__main__':
from hamster.lib import i18n
i18n.setup_i18n()
usage = _(
"""
Actions:
* add [activity [start-time [end-time]]]: Add an activity
* stop: Stop tracking current activity.
* list [start-date [end-date]]: List activities
* search [terms] [start-date [end-date]]: List activities matching a search
term
* export [html|tsv|ical|xml] [start-date [end-date]]: Export activities with
the specified format
* current: Print current activity
* activities: List all the activities names, one per line.
* categories: List all the categories names, one per line.
* overview / preferences / add / about: launch specific window
* version: Show the Hamster version
Time formats:
* 'YYYY-MM-DD hh:mm': If start-date is missing, it will default to today.
If end-date is missing, it will default to start-date.
* '-minutes': Relative time in minutes from the current date and time.
Note:
* For list/search/export a "hamster day" starts at the time set in the
preferences (default 05:00) and ends one minute earlier the next day.
Activities are reported for each "hamster day" in the interval.
Example usage:
hamster start bananas -20
start activity 'bananas' with start time 20 minutes ago
hamster search pancakes 2012-08-01 2012-08-30
look for an activity matching terms 'pancakes` between 1st and 30st
August 2012. Will check against activity, category, description and tags
""")
hamster_client = HamsterCli()
app = Hamster()
logger.debug("app instanciated")
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL) # gtk3 screws up ctrl+c
parser = argparse.ArgumentParser(
description="Time tracking utility",
epilog=usage,
formatter_class=argparse.RawDescriptionHelpFormatter)
# cf. https://stackoverflow.com/a/28611921/3565696
parser.add_argument("--log", dest="log_level",
choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
default='WARNING',
help="Set the logging level (default: %(default)s)")
parser.add_argument("action", nargs="?", default="overview")
parser.add_argument('action_args', nargs=argparse.REMAINDER, default=[])
args, unknown_args = parser.parse_known_args()
# logger for current script
logger.setLevel(args.log_level)
# hamster_logger for the rest
hamster_logger.setLevel(args.log_level)
if not hamster.installed:
logger.info("Running in devel mode")
if args.action in ("start", "track"):
action = "add" # alias
elif args.action == "prefs":
# for backward compatibility
action = "preferences"
else:
action = args.action
if action in ("about", "add", "edit", "overview", "preferences"):
if action == "add" and args.action_args:
assert not unknown_args, "unknown options: {}".format(unknown_args)
# directly add fact from arguments
id_ = hamster_client.start(*args.action_args)
assert id_ > 0, "failed to add fact"
sys.exit(0)
else:
app.register()
if action == "edit":
assert len(args.action_args) == 1, (
"edit requires exactly one argument, got {}"
.format(args.action_args))
id_ = int(args.action_args[0])
assert id_ > 0, "received non-positive id : {}".format(id_)
action_data = glib.Variant.new_int32(id_)
else:
action_data = None
app.activate_action(action, action_data)
run_args = [sys.argv[0]] + unknown_args
logger.debug("run {}".format(run_args))
status = app.run(run_args)
logger.debug("app exited")
sys.exit(status)
elif hasattr(hamster_client, action):
getattr(hamster_client, action)(*args.action_args)
else:
sys.exit(usage % {'prog': sys.argv[0]})
| 18,772 | Python | .py | 408 | 36.691176 | 102 | 0.611111 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,534 | hamster-windows-service.py | projecthamster_hamster/src/hamster-windows-service.py | #!/usr/bin/env python3
# nicked off hamster-service
import dbus
import dbus.service
import os.path
import subprocess
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib as glib
import hamster
DBusGMainLoop(set_as_default=True)
loop = glib.MainLoop()
if "org.gnome.Hamster.WindowServer" in dbus.SessionBus().list_names():
print("Found hamster-window-service already running, exiting")
quit()
# Legacy server. Still used by the shell-extension.
# New code _could_ access the org.gnome.Hamster.GUI actions directly,
# although the exact action names/data are subject to change.
# http://lazka.github.io/pgi-docs/Gio-2.0/classes/Application.html#Gio.Application
# > The actions are also exported on the session bus,
# and GIO provides the Gio.DBusActionGroup wrapper
# to conveniently access them remotely.
class WindowServer(dbus.service.Object):
__dbus_object_path__ = "/org/gnome/Hamster/WindowServer"
def __init__(self, loop):
self.app = True
self.mainloop = loop
self.bus = dbus.SessionBus()
bus_name = dbus.service.BusName("org.gnome.Hamster.WindowServer", bus=self.bus)
dbus.service.Object.__init__(self, bus_name, self.__dbus_object_path__)
@dbus.service.method("org.gnome.Hamster")
def Quit(self):
"""Shutdown the service"""
self.mainloop.quit()
def _open_window(self, name):
if hamster.installed:
base_cmd = "hamster"
else:
# both scripts are at the same place in the source tree
cwd = os.path.dirname(__file__)
base_cmd = "python3 {}/hamster-cli.py".format(cwd)
cmd = "{} {} &".format(base_cmd, name)
subprocess.run(cmd, shell=True)
@dbus.service.method("org.gnome.Hamster.WindowServer")
def edit(self, id: int = 0):
"""Edit fact, given its id (int) in the database.
For backward compatibility, if id is 0, create a brand new fact.
"""
if id:
# {:d} restrict the string format. Too many safeguards cannot hurt.
self._open_window("edit {:d}".format(id))
else:
self._open_window("add")
@dbus.service.method("org.gnome.Hamster.WindowServer")
def overview(self):
self._open_window("overview")
@dbus.service.method("org.gnome.Hamster.WindowServer")
def about(self):
self._open_window("about")
@dbus.service.method("org.gnome.Hamster.WindowServer")
def preferences(self):
self._open_window("prefs")
if __name__ == '__main__':
from hamster.lib import i18n
i18n.setup_i18n()
glib.set_prgname(str(_("hamster-windows-service")))
window_server = WindowServer(loop)
print("hamster-window-service up")
loop.run()
| 2,777 | Python | .py | 68 | 34.808824 | 87 | 0.67473 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,535 | hamster-service.py | projecthamster_hamster/src/hamster-service.py | #!/usr/bin/env python3
# nicked off gwibber
import dbus
import dbus.service
from gi.repository import GLib as glib
from gi.repository import Gio as gio
import hamster
from hamster import logger as hamster_logger
from hamster.lib import i18n
i18n.setup_i18n() # noqa: E402
from hamster.storage import db
from hamster.lib import datetime as dt
from hamster.lib import default_logger
from hamster.lib.dbus import (
DBusMainLoop,
fact_signature,
from_dbus_date,
from_dbus_fact,
from_dbus_fact_json,
from_dbus_range,
to_dbus_fact,
to_dbus_fact_json
)
from hamster.lib.fact import Fact, FactError
logger = default_logger(__file__)
DBusMainLoop(set_as_default=True)
loop = glib.MainLoop()
if "org.gnome.Hamster" in dbus.SessionBus().list_names():
print("Found hamster-service already running, exiting")
quit()
class Storage(db.Storage, dbus.service.Object):
__dbus_object_path__ = "/org/gnome/Hamster"
def __init__(self, loop):
self.bus = dbus.SessionBus()
bus_name = dbus.service.BusName("org.gnome.Hamster", bus=self.bus)
dbus.service.Object.__init__(self, bus_name, self.__dbus_object_path__)
db.Storage.__init__(self, unsorted_localized="")
self.mainloop = loop
self.__file = gio.File.new_for_path(__file__)
self.__monitor = self.__file.monitor_file(gio.FileMonitorFlags.WATCH_MOUNTS | \
gio.FileMonitorFlags.SEND_MOVED,
None)
self.__monitor.connect("changed", self._on_us_change)
def run_fixtures(self):
"""we start with an empty database and then populate with default
values. This way defaults can be localized!"""
super(Storage, self).run_fixtures()
# defaults
defaults = [
(_("Work"), [_("Reading news"),
_("Checking stocks"),
_("Super secret project X"),
_("World domination")]),
(_("Day-to-day"), [_("Lunch"),
_("Watering flowers"),
_("Doing handstands")])
]
if not self.get_categories():
for category, activities in defaults:
cat_id = self.add_category(category)
for activity in activities:
self.add_activity(activity, cat_id)
# stop service when we have been updated (will be brought back in next call)
# anyway. should make updating simpler
def _on_us_change(self, monitor, gio_file, event_uri, event):
if event == gio.FileMonitorEvent.CHANGES_DONE_HINT:
print("`{}` has changed. Quitting!".format(__file__))
self.Quit()
@dbus.service.signal("org.gnome.Hamster")
def TagsChanged(self): pass
def tags_changed(self):
self.TagsChanged()
@dbus.service.signal("org.gnome.Hamster")
def FactsChanged(self): pass
def facts_changed(self):
self.FactsChanged()
@dbus.service.signal("org.gnome.Hamster")
def ActivitiesChanged(self): pass
def activities_changed(self):
self.ActivitiesChanged()
@dbus.service.signal("org.gnome.Hamster")
def ToggleCalled(self): pass
def toggle_called(self):
self.toggle_called()
def dispatch_overwrite(self):
self.TagsChanged()
self.FactsChanged()
self.ActivitiesChanged()
@dbus.service.method("org.gnome.Hamster")
def Quit(self):
"""
Shutdown the service
example:
import dbus
obj = dbus.SessionBus().get_object("org.gnome.Hamster", "/org/gnome/Hamster")
service = dbus.Interface(obj, "org.gnome.Hamster")
service.Quit()
"""
#log.logger.info("Hamster Service is being shutdown")
self.mainloop.quit()
@dbus.service.method("org.gnome.Hamster")
def Toggle(self):
"""Toggle visibility of the main application window.
If several instances are available, it will toggle them all.
"""
#log.logger.info("Hamster Service is being shutdown")
self.ToggleCalled()
# facts
@dbus.service.method("org.gnome.Hamster", in_signature='siib', out_signature='i')
def AddFact(self, fact_str, start_time, end_time, temporary):
"""Add fact specified by a string.
If the parsed fact has no start, then now is used.
To fully use the hamster fact parser, as on the cmdline,
just pass 0 for start_time and end_time.
Args:
fact_str (str): string to be parsed.
start_time (int): Start datetime ovveride timestamp (ignored if 0).
-1 means None.
end_time (int): datetime ovveride timestamp (ignored if 0).
-1 means None.
#temporary (boolean): historical mystery, ignored, but needed to
keep the method signature stable.
Do not forget to pass something (e.g. False)!
Returns:
fact id (int), 0 means failure.
Note: see datetime.utcfromtimestamp documentation
for the precise meaning of timestamps.
"""
fact = Fact.parse(fact_str)
# default value if none found
if not fact.start_time:
fact.start_time = dt.datetime.now()
if start_time == -1:
fact.start_time = None
elif start_time != 0:
fact.start_time = dt.datetime.utcfromtimestamp(start_time)
if end_time == -1:
fact.end_time = None
elif end_time != 0:
fact.end_time = dt.datetime.utcfromtimestamp(end_time)
return self.add_fact(fact)
@dbus.service.method("org.gnome.Hamster", in_signature='s', out_signature='i')
def AddFactJSON(self, dbus_fact):
"""Add fact given in JSON format.
This is the preferred method if the fact fields are known separately,
as activity, category, description and tags are passed "verbatim".
Only datetimes are interpreted
(2020-01-20: JSON does not know datetimes).
Args:
dbus_fact (str): fact in JSON format (cf. from_dbus_fact_json).
Returns:
fact id (int), 0 means failure.
"""
fact = from_dbus_fact_json(dbus_fact)
return self.add_fact(fact)
@dbus.service.method("org.gnome.Hamster",
in_signature="si",
out_signature='bs')
def CheckFact(self, dbus_fact, dbus_default_day):
"""Check fact validity.
Useful to determine in advance whether the fact
can be included in the database.
Args:
dbus_fact (str): fact in JSON format (cf. AddFactJSON)
Returns:
success (boolean): True upon success.
message (str): what's wrong.
"""
fact = from_dbus_fact_json(dbus_fact)
dd = from_dbus_date(dbus_default_day)
try:
self.check_fact(fact, default_day=dd)
success = True
message = ""
except FactError as error:
success = False
message = str(error)
return success, message
@dbus.service.method("org.gnome.Hamster",
in_signature='i',
out_signature=fact_signature)
def GetFact(self, fact_id):
"""Get fact by id. For output format see GetFacts"""
fact = self.get_fact(fact_id)
return to_dbus_fact(fact)
@dbus.service.method("org.gnome.Hamster",
in_signature='i',
out_signature="s")
def GetFactJSON(self, fact_id):
"""Get fact by id.
Return fact in JSON format (cf. to_dbus_fact_json)
"""
fact = self.get_fact(fact_id)
return to_dbus_fact_json(fact)
@dbus.service.method("org.gnome.Hamster", in_signature='isiib', out_signature='i')
def UpdateFact(self, fact_id, fact, start_time, end_time, temporary):
start_time = start_time or None
if start_time:
start_time = dt.datetime.utcfromtimestamp(start_time)
end_time = end_time or None
if end_time:
end_time = dt.datetime.utcfromtimestamp(end_time)
return self.update_fact(fact_id, fact, start_time, end_time, temporary)
@dbus.service.method("org.gnome.Hamster",
in_signature='is',
out_signature='i')
def UpdateFactJSON(self, fact_id, dbus_fact):
"""Update fact.
Args:
fact_id (int): fact id in the database.
dbus_fact (str): new fact content, in JSON format.
Returns:
int: new id (0 means failure)
"""
fact = from_dbus_fact_json(dbus_fact)
return self.update_fact(fact_id, fact)
@dbus.service.method("org.gnome.Hamster", in_signature='i')
def StopTracking(self, end_time):
"""Stops tracking the current activity"""
end_time = end_time or None
if end_time:
end_time = dt.datetime.utcfromtimestamp(end_time)
return self.stop_tracking(end_time)
@dbus.service.method("org.gnome.Hamster")
def StopOrRestartTracking(self):
"""Stops or restarts tracking the last activity"""
return self.stop_or_restart_tracking()
@dbus.service.method("org.gnome.Hamster", in_signature='i')
def RemoveFact(self, fact_id):
"""Remove fact from storage by it's ID"""
return self.remove_fact(fact_id)
@dbus.service.method("org.gnome.Hamster",
in_signature='uus',
out_signature='a{}'.format(fact_signature))
def GetFacts(self, start_date, end_date, search_terms):
"""Gets facts between the day of start_date and the day of end_date.
Parameters:
i start_date: Seconds since epoch (timestamp). Use 0 for today
i end_date: Seconds since epoch (timestamp). Use 0 for today
s search_terms: Bleh. If starts with "not ", the search terms will be reversed
Returns an array of D-Bus fact structures.
Legacy. To be superceded by GetFactsJSON at some point.
"""
#TODO: Assert start > end ?
start = dt.date.today()
if start_date:
start = dt.datetime.utcfromtimestamp(start_date).date()
end = None
if end_date:
end = dt.datetime.utcfromtimestamp(end_date).date()
return [to_dbus_fact(fact) for fact in self.get_facts(start, end, search_terms)]
@dbus.service.method("org.gnome.Hamster",
in_signature='ss',
out_signature='as')
def GetFactsJSON(self, dbus_range, search_terms):
"""Gets facts between the day of start and the day of end.
Args:
dbus_range (str): same format as on the command line.
(cf. dt.Range.parse)
search_terms (str): If starts with "not ",
the search terms will be reversed
Return:
array of D-Bus facts in JSON format.
(cf. to_dbus_fact_json)
This will be the preferred way to get facts.
"""
range = from_dbus_range(dbus_range)
return [to_dbus_fact_json(fact)
for fact in self.get_facts(range, search_terms=search_terms)]
@dbus.service.method("org.gnome.Hamster", out_signature='a{}'.format(fact_signature))
def GetTodaysFacts(self):
"""Gets facts of today,
respecting hamster midnight. See GetFacts for return info.
Legacy, to be superceded by GetTodaysFactsJSON at some point.
"""
return [to_dbus_fact(fact) for fact in self.get_todays_facts()]
@dbus.service.method("org.gnome.Hamster", out_signature='as')
def GetTodaysFactsJSON(self):
"""Gets facts of the current hamster day.
Return an array of facts in JSON format.
"""
return [to_dbus_fact_json(fact) for fact in self.get_todays_facts()]
# categories
@dbus.service.method("org.gnome.Hamster", in_signature='s', out_signature = 'i')
def AddCategory(self, name):
return self.add_category(name)
@dbus.service.method("org.gnome.Hamster", in_signature='s', out_signature='i')
def GetCategoryId(self, category):
return self.get_category_id(category)
@dbus.service.method("org.gnome.Hamster", in_signature='is')
def UpdateCategory(self, id, name):
self.update_category(id, name)
@dbus.service.method("org.gnome.Hamster", in_signature='i')
def RemoveCategory(self, id):
self.remove_category(id)
@dbus.service.method("org.gnome.Hamster", out_signature='a(is)')
def GetCategories(self):
return [(category['id'], category['name']) for category in self.get_categories()]
# activities
@dbus.service.method("org.gnome.Hamster", in_signature='si', out_signature = 'i')
def AddActivity(self, name, category_id):
return self.add_activity(name, category_id)
@dbus.service.method("org.gnome.Hamster", in_signature='isi')
def UpdateActivity(self, id, name, category_id):
self.update_activity(id, name, category_id)
@dbus.service.method("org.gnome.Hamster", in_signature='i')
def RemoveActivity(self, id):
return self.remove_activity(id)
@dbus.service.method("org.gnome.Hamster", in_signature='i', out_signature='a(isis)')
def GetCategoryActivities(self, category_id):
return [(row['id'],
row['name'],
row['category_id'],
row['category'] or '') for row in
self.get_category_activities(category_id = category_id)]
@dbus.service.method("org.gnome.Hamster", in_signature='s', out_signature='a(ss)')
def GetActivities(self, search = ""):
return [(row['name'], row['category'] or '') for row in self.get_activities(search)]
@dbus.service.method("org.gnome.Hamster", in_signature='ii', out_signature = 'b')
def ChangeCategory(self, id, category_id):
return self.change_category(id, category_id)
@dbus.service.method("org.gnome.Hamster", in_signature='sib', out_signature='a{sv}')
def GetActivityByName(self, activity, category_id, resurrect = True):
category_id = category_id or None
if activity:
return dict(self.get_activity_by_name(activity, category_id, resurrect) or {})
else:
return {}
# tags
@dbus.service.method("org.gnome.Hamster", in_signature='b', out_signature='a(isb)')
def GetTags(self, only_autocomplete):
return [(tag['id'], tag['name'], tag['autocomplete']) for tag in self.get_tags(only_autocomplete)]
@dbus.service.method("org.gnome.Hamster", in_signature='as', out_signature='a(isb)')
def GetTagIds(self, tags):
return [(tag['id'], tag['name'], tag['autocomplete']) for tag in self.get_tag_ids(tags)]
@dbus.service.method("org.gnome.Hamster", in_signature='s')
def SetTagsAutocomplete(self, tags):
self.update_autocomplete_tags(tags)
@dbus.service.method("org.gnome.Hamster", out_signature='s')
def Version(self):
return hamster.__version__
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description="Hamster time tracker D-Bus service")
# cf. https://stackoverflow.com/a/28611921/3565696
parser.add_argument("--log", dest="log_level",
choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
default='WARNING',
help="Set the logging level (default: %(default)s)")
args = parser.parse_args()
# logger for current script
logger.setLevel(args.log_level)
# hamster_logger for the rest
hamster_logger.setLevel(args.log_level)
print("hamster-service up")
storage = Storage(loop)
loop.run()
| 16,133 | Python | .py | 357 | 35.254902 | 106 | 0.613161 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,536 | client.py | projecthamster_hamster/src/hamster/client.py | # - coding: utf-8 -
# Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org>
# Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import dbus
import logging
logger = logging.getLogger(__name__) # noqa: E402
import sys
from calendar import timegm
from gi.repository import GObject as gobject
from textwrap import dedent
import hamster
from hamster.lib.dbus import (
DBusMainLoop,
from_dbus_fact_json,
to_dbus_date,
to_dbus_fact,
to_dbus_fact_json,
to_dbus_range,
)
from hamster.lib.fact import Fact, FactError
from hamster.lib import datetime as dt
class Storage(gobject.GObject):
"""Hamster client class, communicating to hamster storage daemon via d-bus.
Subscribe to the `tags-changed`, `facts-changed` and `activities-changed`
signals to be notified when an appropriate factoid of interest has been
changed.
In storage a distinguishment is made between the classificator of
activities and the event in tracking log.
When talking about the event we use term 'fact'. For the classificator
we use term 'activity'.
The relationship is - one activity can be used in several facts.
The rest is hopefully obvious. But if not, please file bug reports!
"""
__gsignals__ = {
"tags-changed": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, ()),
"facts-changed": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, ()),
"activities-changed": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, ()),
"toggle-called": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self):
gobject.GObject.__init__(self)
DBusMainLoop(set_as_default=True)
self.bus = dbus.SessionBus()
self._connection = None # will be initiated on demand
self.bus.add_signal_receiver(self._on_tags_changed, 'TagsChanged', 'org.gnome.Hamster')
self.bus.add_signal_receiver(self._on_facts_changed, 'FactsChanged', 'org.gnome.Hamster')
self.bus.add_signal_receiver(self._on_activities_changed, 'ActivitiesChanged', 'org.gnome.Hamster')
self.bus.add_signal_receiver(self._on_toggle_called, 'ToggleCalled', 'org.gnome.Hamster')
self.bus.add_signal_receiver(self._on_dbus_connection_change, 'NameOwnerChanged',
'org.freedesktop.DBus', arg0='org.gnome.Hamster')
@staticmethod
def _to_dict(columns, result_list):
return [dict(zip(columns, row)) for row in result_list]
@property
def conn(self):
if not self._connection:
self._connection = dbus.Interface(self.bus.get_object('org.gnome.Hamster',
'/org/gnome/Hamster'),
dbus_interface='org.gnome.Hamster')
server_version = self._connection.Version()
client_version = hamster.__version__
if server_version != client_version:
logger.warning(dedent(
"""\
Server and client version mismatch:
server: {}
client: {}
This is sometimes used during bisections,
but generally calls for trouble.
Remember to kill hamster daemons after any version change
(this is safe):
pkill -f hamster-service
pkill -f hamster-windows-service
see also:
https://github.com/projecthamster/hamster#kill-hamster-daemons
""".format(server_version, client_version)
)
)
return self._connection
def _on_dbus_connection_change(self, name, old, new):
self._connection = None
def _on_tags_changed(self):
self.emit("tags-changed")
def _on_facts_changed(self):
self.emit("facts-changed")
def _on_activities_changed(self):
self.emit("activities-changed")
def _on_toggle_called(self):
self.emit("toggle-called")
def toggle(self):
"""toggle visibility of the main application window if any"""
self.conn.Toggle()
def get_todays_facts(self):
"""returns facts of the current date, respecting hamster midnight
hamster midnight is stored in gconf, and presented in minutes
"""
return [from_dbus_fact_json(fact) for fact in self.conn.GetTodaysFactsJSON()]
def get_facts(self, start, end=None, search_terms=""):
"""Returns facts for the time span matching the optional filter criteria.
In search terms comma (",") translates to boolean OR and space (" ")
to boolean AND.
Filter is applied to tags, categories, activity names and description
"""
range = dt.Range.from_start_end(start, end)
dbus_range = to_dbus_range(range)
return [from_dbus_fact_json(fact)
for fact in self.conn.GetFactsJSON(dbus_range, search_terms)]
def get_activities(self, search = ""):
"""returns list of activities name matching search criteria.
results are sorted by most recent usage.
search is case insensitive
"""
return self._to_dict(('name', 'category'), self.conn.GetActivities(search))
def get_categories(self):
"""returns list of categories"""
return self._to_dict(('id', 'name'), self.conn.GetCategories())
def get_tags(self, only_autocomplete = False):
"""returns list of all tags. by default only those that have been set for autocomplete"""
return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete))
def get_tag_ids(self, tags):
"""find tag IDs by name. tags should be a list of labels
if a requested tag had been removed from the autocomplete list, it
will be ressurrected. if tag with such label does not exist, it will
be created.
on database changes the `tags-changed` signal is emitted.
"""
return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTagIds(tags))
def update_autocomplete_tags(self, tags):
"""update list of tags that should autocomplete. this list replaces
anything that is currently set"""
self.conn.SetTagsAutocomplete(tags)
def get_fact(self, id):
"""returns fact by it's ID"""
return from_dbus_fact_json(self.conn.GetFactJSON(id))
def check_fact(self, fact, default_day=None):
"""Check Fact validity for inclusion in the storage.
default_day (date): Default hamster day,
used to simplify some hint messages
(remove unnecessary dates).
None is safe (always show dates).
"""
if not fact.start_time:
# Do not even try to pass fact through D-Bus as
# conversions would fail in this case.
raise FactError("Missing start time")
dbus_fact = to_dbus_fact_json(fact)
dbus_day = to_dbus_date(default_day)
success, message = self.conn.CheckFact(dbus_fact, dbus_day)
if not success:
raise FactError(message)
return success, message
def add_fact(self, fact, temporary_activity = False):
"""Add fact (Fact)."""
assert fact.activity, "missing activity"
if not fact.start_time:
logger.info("Adding fact without any start_time is deprecated")
fact.start_time = dt.datetime.now()
dbus_fact = to_dbus_fact_json(fact)
new_id = self.conn.AddFactJSON(dbus_fact)
return new_id
def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment"""
end_time = timegm((end_time or dt.datetime.now()).timetuple())
return self.conn.StopTracking(end_time)
def stop_or_restart_tracking(self):
"""Stop or restart tracking last activity."""
return self.conn.StopOrRestartTracking(0)
def remove_fact(self, fact_id):
"delete fact from database"
self.conn.RemoveFact(fact_id)
def update_fact(self, fact_id, fact, temporary_activity = False):
"""Update fact values. See add_fact for rules.
Update is performed via remove/insert, so the
fact_id after update should not be used anymore. Instead use the ID
from the fact dict that is returned by this function"""
dbus_fact = to_dbus_fact_json(fact)
new_id = self.conn.UpdateFactJSON(fact_id, dbus_fact)
return new_id
def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryActivities(category_id))
def get_category_id(self, category_name):
"""returns category id by name"""
return self.conn.GetCategoryId(category_name)
def get_activity_by_name(self, activity, category_id = None, resurrect = True):
"""returns activity dict by name and optionally filtering by category.
if activity is found but is marked as deleted, it will be resurrected
unless told otherwise in the resurrect param
"""
category_id = category_id or 0
return self.conn.GetActivityByName(activity, category_id, resurrect)
# category and activity manipulations (normally just via preferences)
def remove_activity(self, id):
self.conn.RemoveActivity(id)
def remove_category(self, id):
self.conn.RemoveCategory(id)
def change_category(self, id, category_id):
return self.conn.ChangeCategory(id, category_id)
def update_activity(self, id, name, category_id):
return self.conn.UpdateActivity(id, name, category_id)
def add_activity(self, name, category_id = -1):
return self.conn.AddActivity(name, category_id)
def update_category(self, id, name):
return self.conn.UpdateCategory(id, name)
def add_category(self, name):
return self.conn.AddCategory(name)
| 11,182 | Python | .py | 220 | 41.154545 | 117 | 0.647685 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,537 | about.py | projecthamster_hamster/src/hamster/about.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007, 2008 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from os.path import join
from hamster.lib.configuration import runtime
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
class About(object):
def __init__(self, parent=None):
about = gtk.AboutDialog(parent=parent)
self.window = about
infos = {
"program-name" : "Hamster",
"version" : runtime.version,
"comments" : _("Project Hamster — track your time"),
"copyright" : _("Copyright © 2007–2010 Toms Bauģis and others"),
"website" : "https://github.com/projecthamster/hamster/wiki/",
"website-label" : _("Project Hamster Website"),
"title": _("About Time Tracker"),
"wrap-license": True
}
about.set_authors(["Toms Bauģis <toms.baugis@gmail.com>",
"Patryk Zawadzki <patrys@pld-linux.org>",
"Pēteris Caune <cuu508@gmail.com>",
"Juanje Ojeda <jojeda@emergya.es>"])
about.set_artists(["Kalle Persson <kalle@kallepersson.se>"])
about.set_translator_credits(_("translator-credits"))
for prop, val in infos.items():
about.set_property(prop, val)
about.set_logo_icon_name("org.gnome.Hamster.GUI")
about.connect("response", lambda self, *args: self.destroy())
about.show_all()
def present(self):
self.window.present()
| 2,216 | Python | .py | 44 | 42.181818 | 76 | 0.656119 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,538 | edit_activity.py | projecthamster_hamster/src/hamster/edit_activity.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007-2009, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
import time
""" TODO: hook into notifications and refresh our days if some evil neighbour
edit fact window has dared to edit facts
"""
from hamster import widgets
from hamster.lib import datetime as dt
from hamster.lib.configuration import Controller, runtime, load_ui_file
from hamster.lib.fact import Fact, FactError
from hamster.lib.stuff import escape_pango
class CustomFactController(Controller):
"""Controller for a Fact edition window.
Args:
action (str): "add", "clone", "edit"
fact_id (int): used for "clone" and "edit"
"""
def __init__(self, action, fact_id=None):
Controller.__init__(self)
self._date = None # for the date property
self._gui = load_ui_file("edit_activity.ui")
self.window = self.get_widget('custom_fact_window')
self.window.set_size_request(600, 200)
self.action = action
self.fact_id = fact_id
self.category_entry = widgets.CategoryEntry(widget=self.get_widget('category'))
self.activity_entry = widgets.ActivityEntry(widget=self.get_widget('activity'),
category_widget=self.category_entry)
self.cmdline = widgets.CmdLineEntry(parent=self.get_widget("cmdline box"))
self.cmdline.connect("focus_in_event", self.on_cmdline_focus_in_event)
self.cmdline.connect("focus_out_event", self.on_cmdline_focus_out_event)
self.dayline = widgets.DayLine()
self._gui.get_object("day_preview").add(self.dayline)
self.description_box = self.get_widget('description')
self.description_buffer = self.description_box.get_buffer()
self.end_date = widgets.Calendar(widget=self.get_widget("end date"),
expander=self.get_widget("end date expander"))
self.end_time = widgets.TimeInput(parent=self.get_widget("end time box"))
self.start_date = widgets.Calendar(widget=self.get_widget("start date"),
expander=self.get_widget("start date expander"))
self.start_time = widgets.TimeInput(parent=self.get_widget("start time box"))
self.tags_entry = widgets.TagsEntry(parent=self.get_widget("tags box"))
self.save_button = self.get_widget("save_button")
# this will set self.master_is_cmdline
self.cmdline.grab_focus()
title = _("Update activity") if action == "edit" else _("Add activity")
self.window.set_title(title)
self.get_widget("delete_button").set_sensitive(action == "edit")
if action == "edit":
self.fact = runtime.storage.get_fact(fact_id)
elif action == "clone":
base_fact = runtime.storage.get_fact(fact_id)
self.fact = base_fact.copy(start_time=dt.datetime.now(),
end_time=None)
else:
self.fact = Fact(start_time=dt.datetime.now())
original_fact = self.fact
# TODO: should use hday, not date.
self.date = self.fact.date
self.update_fields()
self.update_cmdline(select=True)
self.cmdline.original_fact = original_fact
# This signal should be emitted only after a manual modification,
# not at init time when cmdline might not always be fully parsable.
self.cmdline.connect("changed", self.on_cmdline_changed)
self.description_buffer.connect("changed", self.on_description_changed)
self.start_time.connect("changed", self.on_start_time_changed)
self.start_date.connect("day-selected", self.on_start_date_changed)
self.start_date.expander.connect("activate",
self.on_start_date_expander_activated)
self.end_time.connect("changed", self.on_end_time_changed)
self.end_date.connect("day-selected", self.on_end_date_changed)
self.end_date.expander.connect("activate",
self.on_end_date_expander_activated)
self.activity_entry.connect("changed", self.on_activity_changed)
self.category_entry.connect("changed", self.on_category_changed)
self.tags_entry.connect("changed", self.on_tags_changed)
self._gui.connect_signals(self)
self.validate_fields()
self.window.show_all()
@property
def date(self):
"""Default hamster day."""
return self._date
@date.setter
def date(self, value):
self._date = value
self.cmdline.default_day = value
def on_prev_day_clicked(self, button):
self.increment_date(-1)
def on_next_day_clicked(self, button):
self.increment_date(+1)
def draw_preview(self, start_time, end_time=None):
day_facts = runtime.storage.get_facts(self.date)
self.dayline.plot(self.date, day_facts, start_time, end_time)
def get_widget(self, name):
""" skip one variable (huh) """
return self._gui.get_object(name)
def increment_date(self, days):
delta = dt.timedelta(days=days)
self.date += delta
self.fact.date = self.date
self.update_fields()
def show(self):
self.window.show()
def figure_description(self):
buf = self.description_buffer
description = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), 0)
return description.strip()
def on_activity_changed(self, widget):
if not self.master_is_cmdline:
self.fact.activity = self.activity_entry.get_text()
self.validate_fields()
self.update_cmdline()
def on_category_changed(self, widget):
if not self.master_is_cmdline:
self.fact.category = self.category_entry.get_text()
self.validate_fields()
self.update_cmdline()
def on_cmdline_changed(self, widget):
if self.master_is_cmdline:
fact = Fact.parse(self.cmdline.get_text(), default_day=self.date)
previous_cmdline_fact = self.cmdline_fact
# copy the entered fact before any modification
self.cmdline_fact = fact.copy()
if fact.start_time is None:
fact.start_time = dt.datetime.now()
if fact.description == previous_cmdline_fact.description:
# no change to description here, keep the main one
fact.description = self.fact.description
self.fact = fact
self.update_fields()
def on_cmdline_focus_in_event(self, widget, event):
self.master_is_cmdline = True
def on_cmdline_focus_out_event(self, widget, event):
self.master_is_cmdline = False
def on_description_changed(self, text):
if not self.master_is_cmdline:
self.fact.description = self.figure_description()
self.validate_fields()
self.update_cmdline()
def on_end_date_changed(self, widget):
if not self.master_is_cmdline:
if self.fact.end_time:
time = self.fact.end_time.time()
self.fact.end_time = dt.datetime.combine(self.end_date.date, time)
self.validate_fields()
self.update_cmdline()
elif self.end_date.date:
# No end time means on-going, hence date would be meaningless.
# And a default end date may be provided when end time is set,
# so there should never be a date without time.
self.end_date.date = None
def on_end_date_expander_activated(self, widget):
# state has not changed yet, toggle also start_date calendar visibility
previous_state = self.end_date.expander.get_expanded()
self.start_date.expander.set_expanded(not previous_state)
def on_end_time_changed(self, widget):
if not self.master_is_cmdline:
# self.end_time.start_time() was given a datetime,
# so self.end_time.time is a datetime too.
end = self.end_time.time
self.fact.end_time = end
self.end_date.date = end.date() if end else None
self.validate_fields()
self.update_cmdline()
def on_start_date_changed(self, widget):
if not self.master_is_cmdline:
if self.fact.start_time:
previous_date = self.fact.start_time.date()
new_date = self.start_date.date
delta = new_date - previous_date
self.fact.start_time += delta
if self.fact.end_time:
# preserve fact duration
self.fact.end_time += delta
self.end_date.date = self.fact.end_time
self.date = self.fact.date or dt.hday.today()
self.validate_fields()
self.update_cmdline()
def on_start_date_expander_activated(self, widget):
# state has not changed yet, toggle also end_date calendar visibility
previous_state = self.start_date.expander.get_expanded()
self.end_date.expander.set_expanded(not previous_state)
def on_start_time_changed(self, widget):
if not self.master_is_cmdline:
# note: resist the temptation to preserve duration here;
# for instance, end time might be at the beginning of next fact.
new_time = self.start_time.time
if new_time:
if self.fact.start_time:
new_start_time = dt.datetime.combine(self.fact.start_time.date(),
new_time)
else:
# date not specified; result must fall in current hamster_day
new_start_time = dt.datetime.from_day_time(dt.hday.today(), new_time)
else:
new_start_time = None
self.fact.start_time = new_start_time
# let start_date extract date or handle None
self.start_date.date = new_start_time
self.validate_fields()
self.update_cmdline()
def on_tags_changed(self, widget):
if not self.master_is_cmdline:
self.fact.tags = self.tags_entry.get_tags()
self.update_cmdline()
def present(self):
self.window.present()
def update_cmdline(self, select=None):
"""Update the cmdline entry content."""
self.cmdline_fact = self.fact.copy(description=None)
label = self.cmdline_fact.serialized(default_day=self.date)
with self.cmdline.handler_block(self.cmdline.checker):
self.cmdline.set_text(label)
if select:
# select the range string exactly (without separator)
__, rest = dt.Range.parse(label, position="head", separator="")
self.cmdline.select_region(0, len(label) - len(rest))
def update_fields(self):
"""Update gui fields content."""
self.start_time.time = self.fact.start_time
self.end_time.time = self.fact.end_time
self.end_time.set_start_time(self.fact.start_time)
self.start_date.date = self.fact.start_time
self.end_date.date = self.fact.end_time
self.activity_entry.set_text(self.fact.activity)
self.category_entry.set_text(self.fact.category)
self.description_buffer.set_text(self.fact.description)
self.tags_entry.set_tags(self.fact.tags)
self.validate_fields()
def update_status(self, status, markup):
"""Set save button sensitivity and tooltip."""
self.save_button.set_tooltip_markup(markup)
if status == "looks good":
self.save_button.set_label("gtk-save")
self.save_button.set_sensitive(True)
elif status == "warning":
self.save_button.set_label("gtk-dialog-warning")
self.save_button.set_sensitive(True)
elif status == "wrong":
self.save_button.set_label("gtk-save")
self.save_button.set_sensitive(False)
else:
raise ValueError("unknown status: '{}'".format(status))
def validate_fields(self):
"""Check fields information.
Update gui status about entry and description validity.
Try to merge date, activity and description informations.
Return the consolidated fact if successful, or None.
"""
fact = self.fact
now = dt.datetime.now()
self.get_widget("button-next-day").set_sensitive(self.date < now.date())
if self.date == now.date():
default_dt = now
else:
default_dt = dt.datetime.combine(self.date, now.time())
self.draw_preview(fact.start_time or default_dt,
fact.end_time or default_dt)
try:
runtime.storage.check_fact(fact, default_day=self.date)
except FactError as error:
self.update_status(status="wrong", markup=str(error))
return None
roundtrip_fact = Fact.parse(fact.serialized(), default_day=self.date)
if roundtrip_fact != fact:
self.update_status(status="wrong", markup="Fact could not be parsed back")
return None
# nothing unusual
self.update_status(status="looks good", markup="")
return fact
def on_delete_clicked(self, button):
runtime.storage.remove_fact(self.fact_id)
self.close_window()
def on_cancel_clicked(self, button):
self.close_window()
def on_close(self, widget, event):
self.close_window()
def on_save_button_clicked(self, button):
if self.action == "edit":
runtime.storage.update_fact(self.fact_id, self.fact)
else:
runtime.storage.add_fact(self.fact)
self.close_window()
def on_window_key_pressed(self, tree, event_key):
popups = (self.cmdline.popup.get_property("visible")
or self.start_time.popup.get_property("visible")
or self.end_time.popup.get_property("visible")
or self.tags_entry.popup.get_property("visible"))
if (event_key.keyval == gdk.KEY_Escape or \
(event_key.keyval == gdk.KEY_w and event_key.state & gdk.ModifierType.CONTROL_MASK)):
if popups:
return False
self.close_window()
elif event_key.keyval in (gdk.KEY_Return, gdk.KEY_KP_Enter):
if popups:
return False
if self.description_box.has_focus():
return False
if self.validate_fields():
self.on_save_button_clicked(None)
| 15,579 | Python | .py | 316 | 38.427215 | 96 | 0.624523 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,539 | overview.py | projecthamster_hamster/src/hamster/overview.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import sys
import bisect
import itertools
import webbrowser
from collections import defaultdict
from math import ceil
from gi.repository import GLib as glib
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import GObject as gobject
from gi.repository import PangoCairo as pangocairo
from gi.repository import Pango as pango
import cairo
import hamster.client
from hamster.lib import datetime as dt
from hamster.lib import graphics
from hamster.lib import layout
from hamster import reports
from hamster.lib import stuff
from hamster import widgets
from hamster.lib.configuration import Controller
from hamster.lib.pytweener import Easing
from hamster.widgets.dates import RangePick
from hamster.widgets.facttree import FactTree
class HeaderBar(gtk.HeaderBar):
def __init__(self):
gtk.HeaderBar.__init__(self)
self.set_show_close_button(True)
box = gtk.Box(False)
self.time_back = gtk.Button.new_from_icon_name("go-previous-symbolic", gtk.IconSize.MENU)
self.time_forth = gtk.Button.new_from_icon_name("go-next-symbolic", gtk.IconSize.MENU)
box.add(self.time_back)
box.add(self.time_forth)
gtk.StyleContext.add_class(box.get_style_context(), "linked")
self.pack_start(box)
self.range_pick = RangePick(dt.hday.today())
self.pack_start(self.range_pick)
self.system_button = gtk.MenuButton()
self.system_button.set_image(gtk.Image.new_from_icon_name(
"open-menu-symbolic", gtk.IconSize.MENU))
self.system_button.set_tooltip_markup(_("Menu"))
self.pack_end(self.system_button)
self.search_button = gtk.ToggleButton()
self.search_button.set_image(gtk.Image.new_from_icon_name(
"edit-find-symbolic", gtk.IconSize.MENU))
self.search_button.set_tooltip_markup(_("Filter activities"))
self.pack_end(self.search_button)
self.stop_button = gtk.Button()
self.stop_button.set_image(gtk.Image.new_from_icon_name(
"process-stop-symbolic", gtk.IconSize.MENU))
self.stop_button.set_tooltip_markup(_("Stop tracking (Ctrl-SPACE)"))
self.pack_end(self.stop_button)
self.add_activity_button = gtk.Button()
self.add_activity_button.set_image(gtk.Image.new_from_icon_name(
"list-add-symbolic", gtk.IconSize.MENU))
self.add_activity_button.set_tooltip_markup(_("Add activity (Ctrl-+)"))
self.pack_end(self.add_activity_button)
self.system_menu = gtk.Menu()
self.system_button.set_popup(self.system_menu)
self.menu_export = gtk.MenuItem(label=_("Export..."))
self.system_menu.append(self.menu_export)
self.menu_prefs = gtk.MenuItem(label=_("Tracking Settings"))
self.system_menu.append(self.menu_prefs)
self.menu_help = gtk.MenuItem(label=_("Help"))
self.system_menu.append(self.menu_help)
self.system_menu.show_all()
self.time_back.connect("clicked", self.on_time_back_click)
self.time_forth.connect("clicked", self.on_time_forth_click)
self.connect("button-press-event", self.on_button_press)
def on_button_press(self, bar, event):
"""swallow clicks on the interactive parts to avoid triggering
switch to full-window"""
return True
def on_time_back_click(self, button):
self.range_pick.prev_range()
def on_time_forth_click(self, button):
self.range_pick.next_range()
class StackedBar(layout.Widget):
def __init__(self, width=0, height=0, vertical=None, **kwargs):
layout.Widget.__init__(self, **kwargs)
#: orientation, horizontal by default
self.vertical = vertical or False
#: allocated width
self.width = width
#: allocated height
self.height = height
self._items = []
self.connect("on-render", self.on_render)
#: color scheme to use, graphics.colors.category10 by default
self.colors = graphics.Colors.category10
self.colors = ["#95CACF", "#A2CFB6", "#D1DEA1", "#E4C384", "#DE9F7B"]
self._seen_keys = []
def set_items(self, items):
"""expects a list of key, value to work with"""
res = []
max_value = max(sum((rec[1] for rec in items)), 1)
for key, val in items:
res.append((key, val, val * 1.0 / max_value))
self._items = res
def _take_color(self, key):
if key in self._seen_keys:
index = self._seen_keys.index(key)
else:
self._seen_keys.append(key)
index = len(self._seen_keys) - 1
return self.colors[index % len(self.colors)]
def on_render(self, sprite):
if not self._items:
self.graphics.clear()
return
max_width = self.alloc_w - 1 * len(self._items)
for i, (key, val, normalized) in enumerate(self._items):
color = self._take_color(key)
width = int(normalized * max_width)
self.graphics.rectangle(0, 0, width, self.height)
self.graphics.fill(color)
self.graphics.translate(width + 1, 0)
class Label(object):
"""a much cheaper label that would be suitable for cellrenderer"""
def __init__(self, x=0, y=0, color=None, use_markup=False):
self.x = x
self.y = y
self.color = color
self.use_markup = use_markup
def _set_text(self, text):
if self.use_markup:
self.layout.set_markup(text)
else:
self.layout.set_text(text, -1)
def _show(self, g):
if self.color:
g.set_color(self.color)
pangocairo.show_layout(g.context, self.layout)
def show(self, g, text, x=0, y=0):
g.save_context()
g.move_to(x or self.x, y or self.y)
self._set_text(text)
self._show(g)
g.restore_context()
class HorizontalBarChart(graphics.Sprite):
def __init__(self, **kwargs):
graphics.Sprite.__init__(self, **kwargs)
self.x_align = 0
self.y_align = 0
self.values = []
self._label_context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
self.layout = pangocairo.create_layout(self._label_context)
self.layout.set_font_description(pango.FontDescription(graphics._font_desc))
self.layout.set_markup("Hamster") # dummy
# ellipsize the middle because depending on the use case,
# the distinctive information can be either at the beginning or the end.
self.layout.set_ellipsize(pango.EllipsizeMode.MIDDLE)
self.layout.set_justify(True)
self.layout.set_alignment(pango.Alignment.RIGHT)
self.label_height = self.layout.get_pixel_size()[1]
# should be updated by the parent
self.label_color = gdk.RGBA()
self.bar_color = gdk.RGBA()
self._max = dt.timedelta(0)
def set_values(self, values):
"""expects a list of 2-tuples"""
self.values = values
self.height = len(self.values) * 14
self._max = max(rec[1] for rec in values) if values else dt.timedelta(0)
def _draw(self, context, opacity, matrix):
g = graphics.Graphics(context)
g.save_context()
g.translate(self.x, self.y)
# arbitrary 3/4 total width for label, 1/4 for histogram
hist_width = self.alloc_w // 4;
margin = 10 # pixels
label_width = self.alloc_w - hist_width - margin
self.layout.set_width(label_width * pango.SCALE)
label_h = self.label_height
bar_start_x = label_width + margin
for i, (label, value) in enumerate(self.values):
g.set_color(self.label_color)
duration_str = value.format(fmt="HH:MM")
markup_label = stuff.escape_pango(str(label))
markup_duration = stuff.escape_pango(duration_str)
self.layout.set_markup("{}, <i>{}</i>".format(markup_label, markup_duration))
y = int(i * label_h * 1.5)
g.move_to(0, y)
pangocairo.show_layout(context, self.layout)
if self._max > dt.timedelta(0):
w = ceil(hist_width * value.total_seconds() /
self._max.total_seconds())
else:
w = 1
g.rectangle(bar_start_x, y, int(w), int(label_h))
g.fill(self.bar_color)
g.restore_context()
class Totals(graphics.Scene):
def __init__(self):
graphics.Scene.__init__(self)
self.set_size_request(200, 70)
self.category_totals = layout.Label(overflow=pango.EllipsizeMode.END,
x_align=0,
expand=False)
self.stacked_bar = StackedBar(height=25, x_align=0, expand=False)
box = layout.VBox(padding=10, spacing=5)
self.add_child(box)
box.add_child(self.category_totals, self.stacked_bar)
self.totals = {}
self.mouse_cursor = gdk.CursorType.HAND2
self.instructions_label = layout.Label(_("Click to see stats"),
color=self._style.get_color(gtk.StateFlags.NORMAL),
padding=10,
expand=False)
box.add_child(self.instructions_label)
self.collapsed = True
main = layout.HBox(padding_top=10)
box.add_child(main)
self.stub_label = layout.Label(markup="<b>Here be stats,\ntune in laters!</b>",
color="#bbb",
size=60)
self.activities_chart = HorizontalBarChart()
self.categories_chart = HorizontalBarChart()
self.tag_chart = HorizontalBarChart()
main.add_child(self.activities_chart, self.categories_chart, self.tag_chart)
# for use in animation
self.height_proxy = graphics.Sprite(x=0)
self.height_proxy.height = 70
self.add_child(self.height_proxy)
self.connect("on-click", self.on_click)
self.connect("enter-notify-event", self.on_mouse_enter)
self.connect("leave-notify-event", self.on_mouse_leave)
self.connect("state-flags-changed", self.on_state_flags_changed)
self.connect("style-updated", self.on_style_changed)
def set_facts(self, facts):
totals = defaultdict(lambda: defaultdict(dt.timedelta))
for fact in facts:
for key in ('category', 'activity'):
totals[key][getattr(fact, key)] += fact.delta
for tag in fact.tags:
totals["tag"][tag] += fact.delta
for key, group in totals.items():
totals[key] = sorted(group.items(), key=lambda x: x[1], reverse=True)
self.totals = totals
self.activities_chart.set_values(totals['activity'])
self.categories_chart.set_values(totals['category'])
self.tag_chart.set_values(totals['tag'])
self.stacked_bar.set_items([(cat, delta.total_seconds() / 60.0) for cat, delta in totals['category']])
grand_total = sum(delta.total_seconds() / 60
for __, delta in totals['activity'])
self.category_totals.markup = "<b>Total: </b>%s; " % stuff.format_duration(grand_total)
self.category_totals.markup += ", ".join("<b>%s:</b> %s" % (stuff.escape_pango(cat), stuff.format_duration(hours)) for cat, hours in totals['category'])
def on_click(self, scene, sprite, event):
self.collapsed = not self.collapsed
if self.collapsed:
self.change_height(70)
self.instructions_label.visible = True
self.instructions_label.opacity = 0
self.instructions_label.animate(opacity=1, easing=Easing.Expo.ease_in)
else:
self.change_height(300)
self.instructions_label.visible = False
self.mouse_cursor = gdk.CursorType.HAND2 if self.collapsed else None
def on_mouse_enter(self, scene, event):
if not self.collapsed:
return
def delayed_leave(sprite):
self.change_height(100)
self.height_proxy.animate(x=50, delay=0.5, duration=0,
on_complete=delayed_leave,
on_update=lambda sprite: sprite.redraw())
def on_mouse_leave(self, scene, event):
if not self.collapsed:
return
def delayed_leave(sprite):
self.change_height(70)
self.height_proxy.animate(x=50, delay=0.5, duration=0,
on_complete=delayed_leave,
on_update=lambda sprite: sprite.redraw())
def on_state_flags_changed(self, previous_state, _):
self.update_colors()
def on_style_changed(self, _):
self.update_colors()
def change_height(self, new_height):
self.stop_animation(self.height_proxy)
def on_update_dummy(sprite):
self.set_size_request(200, sprite.height)
self.animate(self.height_proxy,
height=new_height,
on_update=on_update_dummy,
easing=Easing.Expo.ease_out)
def update_colors(self):
color = self._style.get_color(self.get_state())
self.instructions_label.color = color
self.category_totals.color = color
self.activities_chart.label_color = color
self.categories_chart.label_color = color
self.tag_chart.label_color = color
bg_color = self._style.get_background_color(self.get_state())
bar_color = self.colors.mix(bg_color, color, 0.6)
self.activities_chart.bar_color = bar_color
self.categories_chart.bar_color = bar_color
self.tag_chart.bar_color = bar_color
class Overview(Controller):
def __init__(self):
Controller.__init__(self)
self.prefs_dialog = None # preferences dialog controller
self.window.set_position(gtk.WindowPosition.CENTER)
self.window.set_default_icon_name("org.gnome.Hamster.GUI")
self.window.set_default_size(700, 500)
self.storage = hamster.client.Storage()
self.storage.connect("facts-changed", self.on_facts_changed)
self.storage.connect("activities-changed", self.on_facts_changed)
self.header_bar = HeaderBar()
self.window.set_titlebar(self.header_bar)
main = gtk.Box(orientation=1)
self.window.add(main)
self.report_chooser = None
self.search_box = gtk.Revealer()
space = gtk.Box(border_width=5)
self.search_box.add(space)
self.filter_entry = gtk.Entry()
self.filter_entry.set_icon_from_icon_name(gtk.EntryIconPosition.PRIMARY,
"edit-find-symbolic")
self.filter_entry.connect("changed", self.on_search_changed)
self.filter_entry.connect("icon-press", self.on_search_icon_press)
space.pack_start(self.filter_entry, True, True, 0)
main.pack_start(self.search_box, False, True, 0)
window = gtk.ScrolledWindow()
window.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC)
self.fact_tree = FactTree()
self.fact_tree.connect("on-activate-row", self.on_row_activated)
self.fact_tree.connect("on-delete-called", self.on_row_delete_called)
window.add(self.fact_tree)
main.pack_start(window, True, True, 1)
self.totals = Totals()
main.pack_start(self.totals, False, True, 1)
# FIXME: should store and recall date_range from hamster.lib.configuration.conf
hamster_day = dt.hday.today()
self.header_bar.range_pick.set_range(hamster_day)
self.header_bar.range_pick.connect("range-selected", self.on_range_selected)
self.header_bar.add_activity_button.connect("clicked", self.on_add_activity_clicked)
self.header_bar.stop_button.connect("clicked", self.on_stop_clicked)
self.header_bar.search_button.connect("toggled", self.on_search_toggled)
self.header_bar.menu_prefs.connect("activate", self.on_prefs_clicked)
self.header_bar.menu_export.connect("activate", self.on_export_clicked)
self.header_bar.menu_help.connect("activate", self.on_help_clicked)
self.window.connect("key-press-event", self.on_key_press)
self.facts = []
self.find_facts()
# update every minute (necessary if an activity is running)
gobject.timeout_add_seconds(60, self.on_timeout)
self.window.show_all()
def on_key_press(self, window, event):
if self.filter_entry.has_focus():
if event.keyval == gdk.KEY_Escape:
self.filter_entry.set_text("")
self.header_bar.search_button.set_active(False)
return True
elif event.keyval in (gdk.KEY_Up, gdk.KEY_Down,
gdk.KEY_Home, gdk.KEY_End,
gdk.KEY_Page_Up, gdk.KEY_Page_Down,
gdk.KEY_Return, gdk.KEY_Delete):
# These keys should work even when fact_tree does not have focus
self.fact_tree.on_key_press(self, event)
return True # stop event propagation
elif event.keyval == gdk.KEY_Left:
self.header_bar.time_back.emit("clicked")
return True
elif event.keyval == gdk.KEY_Right:
self.header_bar.time_forth.emit("clicked")
return True
if self.fact_tree.has_focus() or self.totals.has_focus():
if event.keyval == gdk.KEY_Tab:
pass # TODO - deal with tab as our scenes eat up navigation
if event.state & gdk.ModifierType.CONTROL_MASK:
# the ctrl+things
if event.keyval == gdk.KEY_f:
self.header_bar.search_button.set_active(True)
elif event.keyval == gdk.KEY_n:
self.start_new_fact(clone_selected=False)
elif event.keyval == gdk.KEY_r:
# Resume/run; clear separation between Ctrl-R and Ctrl-N
self.start_new_fact(clone_selected=True, fallback=False)
elif event.keyval == gdk.KEY_space:
self.storage.stop_or_restart_tracking()
elif event.keyval in (gdk.KEY_KP_Add, gdk.KEY_plus):
# same as pressing the + icon
self.start_new_fact(clone_selected=True, fallback=True)
if event.keyval == gdk.KEY_Escape:
self.close_window()
def find_facts(self, scroll_to_top=False):
start, end = self.header_bar.range_pick.get_range()
search_active = self.header_bar.search_button.get_active()
search = "" if not search_active else self.filter_entry.get_text()
search = "%s*" % search if search else "" # search anywhere
self.facts = self.storage.get_facts(start, end, search_terms=search)
self.fact_tree.set_facts(self.facts, scroll_to_top=scroll_to_top)
self.totals.set_facts(self.facts)
self.header_bar.stop_button.set_sensitive(
self.facts and not self.facts[-1].end_time)
def on_range_selected(self, button, range_type, start, end):
self.find_facts(scroll_to_top=True)
def on_search_changed(self, entry):
if entry.get_text():
self.filter_entry.set_icon_from_icon_name(gtk.EntryIconPosition.SECONDARY,
"edit-clear-symbolic")
else:
self.filter_entry.set_icon_from_icon_name(gtk.EntryIconPosition.SECONDARY,
None)
self.find_facts(scroll_to_top=True)
def on_search_icon_press(self, entry, position, event):
if position == gtk.EntryIconPosition.SECONDARY:
self.filter_entry.set_text("")
def on_facts_changed(self, event):
self.find_facts()
def on_add_activity_clicked(self, button):
self.start_new_fact(clone_selected=True, fallback=True)
def on_stop_clicked(self, button):
self.storage.stop_tracking()
def on_row_activated(self, tree, day, fact):
self.present_fact_controller("edit", fact_id=fact.id)
def on_row_delete_called(self, tree, fact):
self.storage.remove_fact(fact.id)
self.find_facts()
def on_search_toggled(self, button):
active = button.get_active()
self.search_box.set_reveal_child(active)
if active:
self.filter_entry.grab_focus()
def on_timeout(self):
# TODO: should update only the running FactTree row (if any), and totals
self.find_facts()
# The timeout will stop if returning False
return True
def on_help_clicked(self, menu):
uri = "help:hamster"
try:
gtk.show_uri(None, uri, gdk.CURRENT_TIME)
except glib.Error:
msg = sys.exc_info()[1].args[0]
dialog = gtk.MessageDialog(self.window, 0, gtk.MessageType.ERROR,
gtk.ButtonsType.CLOSE,
_("Failed to open {}").format(uri))
fmt = _('Error: "{}" - is a help browser installed on this computer?')
dialog.format_secondary_text(fmt.format(msg))
dialog.run()
dialog.destroy()
def on_prefs_clicked(self, menu):
app = self.window.get_property("application")
app.activate_action("preferences")
def on_export_clicked(self, menu):
if self.report_chooser:
self.report_chooser.present()
return
start, end = self.header_bar.range_pick.get_range()
def on_report_chosen(widget, format, path):
self.report_chooser = None
reports.simple(self.facts, start, end, format, path)
if format == ("html"):
webbrowser.open_new("file://%s" % path)
else:
try:
gtk.show_uri(None, "file://%s" % path, gdk.CURRENT_TIME)
except:
pass # bug 626656 - no use in capturing this one i think
def on_report_chooser_closed(widget):
self.report_chooser = None
self.report_chooser = widgets.ReportChooserDialog()
self.report_chooser.connect("report-chosen", on_report_chosen)
self.report_chooser.connect("report-chooser-closed", on_report_chooser_closed)
self.report_chooser.show(start, end)
def present_fact_controller(self, action, fact_id=0):
app = self.window.get_property("application")
app.present_fact_controller(action, fact_id=fact_id)
def start_new_fact(self, clone_selected=True, fallback=True):
"""Start now a new fact.
clone_selected (bool): whether to start a clone of currently
selected fact or to create a new fact from scratch.
fallback (bool): if True, fall back to creating from scratch
in case of no selected fact.
"""
if not clone_selected:
self.present_fact_controller("add")
elif self.fact_tree.current_fact:
self.present_fact_controller("clone",
fact_id=self.fact_tree.current_fact.id)
elif fallback:
self.present_fact_controller("add")
def close_window(self):
self.window.destroy()
self.window = None
self._gui = None
self.emit("on-close")
| 24,442 | Python | .py | 502 | 37.960159 | 160 | 0.61951 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,540 | reports.py | projecthamster_hamster/src/hamster/reports.py | # - coding: utf-8 -
# Copyright (C) 2008-2012 Toms Bauģis <toms.baugis at gmail.com>
# Copyright (C) 2008 Nathan Samson <nathansamson at gmail dot com>
# Copyright (C) 2008 Giorgos Logiotatidis <seadog at sealabs dot net>
# Copyright (C) 2012 Ted Smith <tedks at cs.umd.edu>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import os, sys
from xml.dom.minidom import Document
import csv
import copy
import itertools
import re
import codecs
import html
from string import Template
from textwrap import dedent
from hamster.lib import datetime as dt
from hamster.lib.configuration import runtime
from hamster.lib import stuff
from hamster.lib.i18n import C_
try:
import json
except ImportError:
# fallback for python < 2.6
json_dumps = lambda s: s
else:
json_dumps = json.dumps
from calendar import timegm
from io import StringIO, IOBase
def simple(facts, start_date, end_date, format, path = None):
facts = copy.deepcopy(facts) # dont want to do anything bad to the input
report_path = stuff.locale_from_utf8(path)
if format == "tsv":
writer = TSVWriter(report_path)
elif format == "xml":
writer = XMLWriter(report_path)
elif format == "ical":
writer = ICalWriter(report_path)
else: #default to HTML
writer = HTMLWriter(report_path, start_date, end_date)
writer.write_report(facts)
return writer
class ReportWriter(object):
#a tiny bit better than repeating the code all the time
def __init__(self, path = None, datetime_format = "%Y-%m-%d %H:%M:%S"):
# if path is empty or None, print to stdout
self.file = open(path, "w") if path else StringIO()
self.path = path
self.datetime_format = datetime_format
def write_report(self, facts):
try:
for fact in facts:
fact.description = (fact.description or "")
fact.category = (fact.category or _("Unsorted"))
self._write_fact(fact)
self._finish(facts)
finally:
if not self.path:
# print the full report to stdout
print(self.file.getvalue())
self.file.close()
def _start(self, facts):
raise NotImplementedError
def _write_fact(self, fact):
raise NotImplementedError
def _finish(self, facts):
raise NotImplementedError
class ICalWriter(ReportWriter):
"""a lame ical writer, could not be bothered with finding a library"""
def __init__(self, path):
ReportWriter.__init__(self, path, datetime_format = "%Y%m%dT%H%M%S")
self.file.write("BEGIN:VCALENDAR\nVERSION:1.0\n")
def _write_fact(self, fact):
#for now we will skip ongoing facts
if not fact.end_time: return
if fact.category == _("Unsorted"):
fact.category = None
event_str = """\
BEGIN:VEVENT
CATEGORIES:{fact.category}
DTSTART:{fact.start_time}
DTEND:{fact.end_time}
SUMMARY:{fact.activity}
DESCRIPTION:{fact.description}
END:VEVENT
""".format(fact=fact)
self.file.write(dedent(event_str))
def _finish(self, facts):
self.file.write("END:VCALENDAR\n")
class TSVWriter(ReportWriter):
def __init__(self, path):
ReportWriter.__init__(self, path)
self.csv_writer = csv.writer(self.file, dialect='excel-tab')
headers = [# column title in the TSV export format
_("activity"),
# column title in the TSV export format
_("start time"),
# column title in the TSV export format
_("end time"),
# column title in the TSV export format
_("duration minutes"),
# column title in the TSV export format
_("category"),
# column title in the TSV export format
_("description"),
# column title in the TSV export format
_("tags")]
self.csv_writer.writerow([h for h in headers])
def _write_fact(self, fact):
self.csv_writer.writerow([fact.activity,
fact.start_time,
fact.end_time,
str(stuff.duration_minutes(fact.delta)),
fact.category,
fact.description,
", ".join(fact.tags)])
def _finish(self, facts):
pass
class XMLWriter(ReportWriter):
def __init__(self, path):
ReportWriter.__init__(self, path)
self.doc = Document()
self.activity_list = self.doc.createElement("activities")
def _write_fact(self, fact):
activity = self.doc.createElement("activity")
activity.setAttribute("name", fact.activity)
activity.setAttribute("start_time", str(fact.start_time))
activity.setAttribute("end_time", str(fact.end_time))
activity.setAttribute("duration_minutes", str(stuff.duration_minutes(fact.delta)))
activity.setAttribute("category", fact.category)
activity.setAttribute("description", fact.description)
activity.setAttribute("tags", ", ".join(fact.tags))
self.activity_list.appendChild(activity)
def _finish(self, facts):
self.doc.appendChild(self.activity_list)
self.file.write(self.doc.toxml())
class HTMLWriter(ReportWriter):
def __init__(self, path, start_date, end_date):
ReportWriter.__init__(self, path, datetime_format = None)
self.start_date, self.end_date = start_date, end_date
dates_dict = stuff.dateDict(start_date, "start_")
dates_dict.update(stuff.dateDict(end_date, "end_"))
if start_date.year != end_date.year:
self.title = _("Activity report for %(start_B)s %(start_d)s, %(start_Y)s – %(end_B)s %(end_d)s, %(end_Y)s") % dates_dict
elif start_date.month != end_date.month:
self.title = _("Activity report for %(start_B)s %(start_d)s – %(end_B)s %(end_d)s, %(end_Y)s") % dates_dict
elif start_date == end_date:
self.title = _("Activity report for %(start_B)s %(start_d)s, %(start_Y)s") % dates_dict
else:
self.title = _("Activity report for %(start_B)s %(start_d)s – %(end_d)s, %(end_Y)s") % dates_dict
# read the template, allow override
self.override = os.path.exists(os.path.join(runtime.home_data_dir, "report_template.html"))
if self.override:
template = os.path.join(runtime.home_data_dir, "report_template.html")
else:
template = os.path.join(runtime.data_dir, "report_template.html")
self.main_template = ""
with open(template, 'r') as f:
self.main_template =f.read()
self.fact_row_template = self._extract_template('all_activities')
self.by_date_row_template = self._extract_template('by_date_activity')
self.by_date_template = self._extract_template('by_date')
self.fact_rows = []
def _extract_template(self, name):
pattern = re.compile('<%s>(.*)</%s>' % (name, name), re.DOTALL)
match = pattern.search(self.main_template)
if match:
self.main_template = self.main_template.replace(match.group(), "$%s_rows" % name)
return match.groups()[0]
return ""
def _write_fact(self, fact):
# no having end time is fine
end_time_str, end_time_iso_str = "", ""
if fact.end_time:
end_time_str = fact.end_time.strftime('%H:%M')
end_time_iso_str = fact.end_time.isoformat()
category = ""
if fact.category != _("Unsorted"): #do not print "unsorted" in list
category = fact.category
data = dict(
date = fact.date.strftime(
# date column format for each row in HTML report
# Using python datetime formatting syntax. See:
# http://docs.python.org/library/time.html#time.strftime
C_("html report","%b %d, %Y")),
date_iso = fact.date.isoformat(),
activity = html.escape(fact.activity),
category = html.escape(category),
tags = html.escape(", ".join(fact.tags)),
start = fact.start_time.strftime('%H:%M'),
start_iso = fact.start_time.isoformat(),
end = end_time_str,
end_iso = end_time_iso_str,
duration = fact.delta.format(),
duration_minutes = "%d" % (stuff.duration_minutes(fact.delta)),
duration_decimal = "%.2f" % (stuff.duration_minutes(fact.delta) / 60.0),
# not only escape html characters, but ensure \n is respected in output
description = html.escape(fact.description).replace('\n', '<br />') or ""
)
self.fact_rows.append(Template(self.fact_row_template).safe_substitute(data))
def _finish(self, facts):
# group by date
by_date = []
for date, date_facts in itertools.groupby(facts, lambda fact:fact.date):
by_date.append((date, [fact.as_dict() for fact in date_facts]))
by_date = dict(by_date)
date_facts = []
date = min(by_date.keys())
while date <= self.end_date:
str_date = date.strftime(
# date column format for each row in HTML report
# Using python datetime formatting syntax. See:
# http://docs.python.org/library/time.html#time.strftime
C_("html report","%b %d, %Y"))
date_facts.append([str_date, by_date.get(date, [])])
date += dt.timedelta(days=1)
data = dict(
title = self.title,
totals_by_day_title = _("Totals by Day"),
activity_log_title = _("Activity Log"),
totals_title = _("Totals"),
activity_totals_heading = _("activities"),
category_totals_heading = _("categories"),
tag_totals_heading = _("tags"),
show_prompt = _("Distinguish:"),
header_date = _("Date"),
header_activity = _("Activity"),
header_category = _("Category"),
header_tags = _("Tags"),
header_start = _("Start"),
header_end = _("End"),
header_duration = _("Duration"),
header_description = _("Description"),
data_dir = runtime.data_dir,
show_template = _("Show template"),
template_instructions = _("You can override it by storing your version in %(home_folder)s") % {'home_folder': runtime.home_data_dir},
start_date = timegm(self.start_date.timetuple()),
end_date = timegm(self.end_date.timetuple()),
facts = json_dumps([fact.as_dict() for fact in facts]),
date_facts = json_dumps(date_facts),
all_activities_rows = "\n".join(self.fact_rows)
)
for key, val in data.items():
if isinstance(val, str):
data[key] = val
self.file.write(Template(self.main_template).safe_substitute(data))
return
| 12,055 | Python | .py | 257 | 36.303502 | 145 | 0.5921 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,541 | __init__.py | projecthamster_hamster/src/hamster/__init__.py | import gi
gi.require_version('Gtk', '3.0') # noqa: E402
gi.require_version('PangoCairo', '1.0') # noqa: E402
# for some reason performance is improved by importing Gtk early
from gi.repository import Gtk as gtk
from hamster.lib import default_logger
from hamster.version import get_version
logger = default_logger(__name__)
(__version__, installed) = get_version()
# cleanup namespace
del get_version
del default_logger
del gtk # performance is retained
| 462 | Python | .py | 13 | 34.153846 | 64 | 0.774775 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,542 | preferences.py | projecthamster_hamster/src/hamster/preferences.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007, 2008, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import GObject as gobject
from hamster import widgets
from hamster.lib import datetime as dt
from hamster.lib import stuff
from hamster.lib.configuration import Controller, runtime, conf
def get_prev(selection, model):
(model, iter) = selection.get_selected()
#previous item
path = model.get_path(iter)[0] - 1
if path >= 0:
return model.get_iter_from_string(str(path))
else:
return None
class CategoryStore(gtk.ListStore):
def __init__(self):
#id, name, color_code, order
gtk.ListStore.__init__(self, int, str)
def load(self):
category_list = runtime.storage.get_categories()
for category in category_list:
self.append([category['id'], category['name']])
self.unsorted_category = self.append([-1, _("Unsorted")]) # all activities without category
class ActivityStore(gtk.ListStore):
def __init__(self):
#id, name, category_id, order
gtk.ListStore.__init__(self, int, str, int)
def load(self, category_id):
self.clear()
if category_id is None:
return
activity_list = runtime.storage.get_category_activities(category_id)
for activity in activity_list:
self.append([activity['id'],
activity['name'],
activity['category_id']])
class PreferencesEditor(Controller):
TARGETS = [
('MY_TREE_MODEL_ROW', gtk.TargetFlags.SAME_WIDGET, 0),
('MY_TREE_MODEL_ROW', gtk.TargetFlags.SAME_APP, 0),
]
def __init__(self):
Controller.__init__(self, ui_file="preferences.ui")
# create and fill activity tree
self.activity_tree = self.get_widget('activity_list')
self.get_widget("activities_label").set_mnemonic_widget(self.activity_tree)
self.activity_store = ActivityStore()
self.external_listeners = []
self.activityColumn = gtk.TreeViewColumn(_("Name"))
self.activityColumn.set_expand(True)
self.activityCell = gtk.CellRendererText()
self.external_listeners.extend([
(self.activityCell, self.activityCell.connect('edited', self.activity_name_edited_cb, self.activity_store))
])
self.activityColumn.pack_start(self.activityCell, True)
self.activityColumn.set_attributes(self.activityCell, text=1)
self.activityColumn.set_sort_column_id(1)
self.activity_tree.append_column(self.activityColumn)
self.activity_tree.set_model(self.activity_store)
self.selection = self.activity_tree.get_selection()
self.external_listeners.extend([
(self.selection, self.selection.connect('changed', self.activity_changed, self.activity_store))
])
# create and fill category tree
self.category_tree = self.get_widget('category_list')
self.get_widget("categories_label").set_mnemonic_widget(self.category_tree)
self.category_store = CategoryStore()
self.categoryColumn = gtk.TreeViewColumn(_("Category"))
self.categoryColumn.set_expand(True)
self.categoryCell = gtk.CellRendererText()
self.external_listeners.extend([
(self.categoryCell, self.categoryCell.connect('edited', self.category_edited_cb, self.category_store))
])
self.categoryColumn.pack_start(self.categoryCell, True)
self.categoryColumn.set_attributes(self.categoryCell, text=1)
self.categoryColumn.set_sort_column_id(1)
self.categoryColumn.set_cell_data_func(self.categoryCell, self.unsorted_painter)
self.category_tree.append_column(self.categoryColumn)
self.category_store.load()
self.category_tree.set_model(self.category_store)
selection = self.category_tree.get_selection()
self.external_listeners.extend([
(selection, selection.connect('changed', self.category_changed_cb, self.category_store))
])
self.day_start = widgets.TimeInput(dt.time(5,30), parent=self.get_widget("day_start_placeholder"))
self.load_config()
# Allow enable drag and drop of rows including row move
self.activity_tree.enable_model_drag_source(gdk.ModifierType.BUTTON1_MASK,
self.TARGETS,
gdk.DragAction.DEFAULT|
gdk.DragAction.MOVE)
self.category_tree.enable_model_drag_dest(self.TARGETS,
gdk.DragAction.MOVE)
self.activity_tree.connect("drag_data_get", self.drag_data_get_data)
self.category_tree.connect("drag_data_received", self.on_category_drop)
#select first category
selection = self.category_tree.get_selection()
selection.select_path((0,))
self.prev_selected_activity = None
self.prev_selected_category = None
self.external_listeners.extend([
(self.day_start, self.day_start.connect("time-entered", self.on_day_start_changed))
])
self.show()
def show(self):
self.get_widget("notebook1").set_current_page(0)
self.window.show_all()
def load_config(self, *args):
self.day_start.time = conf.day_start
self.tags = [tag["name"] for tag in runtime.storage.get_tags(only_autocomplete=True)]
self.get_widget("autocomplete_tags").set_text(", ".join(self.tags))
def on_autocomplete_tags_view_focus_out_event(self, view, event):
buf = self.get_widget("autocomplete_tags")
updated_tags = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), 0)
if updated_tags == self.tags:
return
self.tags = updated_tags
runtime.storage.update_autocomplete_tags(updated_tags)
def drag_data_get_data(self, treeview, context, selection, target_id,
etime):
treeselection = treeview.get_selection()
model, iter = treeselection.get_selected()
data = model.get_value(iter, 0) #get activity ID
selection.set(selection.target, 0, str(data))
def select_activity(self, id):
model = self.activity_tree.get_model()
i = 0
for row in model:
if row[0] == id:
self.activity_tree.set_cursor((i, ))
i += 1
def select_category(self, id):
model = self.category_tree.get_model()
i = 0
for row in model:
if row[0] == id:
self.category_tree.set_cursor((i, ))
i += 1
def on_category_list_drag_motion(self, treeview, drag_context, x, y, eventtime):
self.prev_selected_category = None
try:
target_path, drop_position = treeview.get_dest_row_at_pos(x, y)
model, source = treeview.get_selection().get_selected()
except:
return
drop_yes = ("drop_yes", gtk.TargetFlags.SAME_APP, 0)
drop_no = ("drop_no", gtk.TargetFlags.SAME_APP, 0)
if drop_position != gtk.TREE_VIEW_DROP_AFTER and \
drop_position != gtk.TREE_VIEW_DROP_BEFORE:
treeview.enable_model_drag_dest(self.TARGETS, gdk.DragAction.MOVE)
else:
treeview.enable_model_drag_dest([drop_no], gdk.DragAction.MOVE)
def on_category_drop(self, treeview, context, x, y, selection,
info, etime):
model = self.category_tree.get_model()
data = selection.data
drop_info = treeview.get_dest_row_at_pos(x, y)
if drop_info:
path, position = drop_info
iter = model.get_iter(path)
changed = runtime.storage.change_category(int(data), model[iter][0])
context.finish(changed, True, etime)
else:
context.finish(False, True, etime)
return
# callbacks
def category_edited_cb(self, cell, path, new_text, model):
id = model[path][0]
if id == -1:
return False #ignoring unsorted category
#look for dupes
categories = runtime.storage.get_categories()
for category in categories:
if category['name'].lower() == new_text.lower():
if id == -2: # that was a new category
self.category_store.remove(model.get_iter(path))
self.select_category(category['id'])
return False
if id == -2: #new category
id = runtime.storage.add_category(new_text)
model[path][0] = id
else:
runtime.storage.update_category(id, new_text)
model[path][1] = new_text
def activity_name_edited_cb(self, cell, path, new_text, model):
id = model[path][0]
category_id = model[path][2]
activities = runtime.storage.get_category_activities(category_id)
prev = None
for activity in activities:
if id == activity['id']:
prev = activity['name']
else:
# avoid two activities in same category with same name
if activity['name'].lower() == new_text.lower():
if id == -1: # that was a new activity
self.activity_store.remove(model.get_iter(path))
self.select_activity(activity['id'])
return False
if id == -1: #new activity -> add
model[path][0] = runtime.storage.add_activity(new_text, category_id)
else: #existing activity -> update
new = new_text
runtime.storage.update_activity(id, new, category_id)
model[path][1] = new_text
return True
def category_changed_cb(self, selection, model):
""" enables and disables action buttons depending on selected item """
(model, iter) = selection.get_selected()
id = 0
if iter is None:
self.activity_store.clear()
else:
self.prev_selected_activity = None
id = model[iter][0]
self.activity_store.load(model[iter][0])
#start with nothing
self.get_widget('activity_edit').set_sensitive(False)
self.get_widget('activity_remove').set_sensitive(False)
return True
def _get_selected_category(self):
selection = self.get_widget('category_list').get_selection()
(model, iter) = selection.get_selected()
return model[iter][0] if iter else None
def activity_changed(self, selection, model):
""" enables and disables action buttons depending on selected item """
(model, iter) = selection.get_selected()
# treat any selected case
unsorted_selected = self._get_selected_category() == -1
self.get_widget('activity_edit').set_sensitive(iter != None)
self.get_widget('activity_remove').set_sensitive(iter != None)
def _del_selected_row(self, tree):
selection = tree.get_selection()
(model, iter) = selection.get_selected()
next_row = model.iter_next(iter)
if next_row:
selection.select_iter(next_row)
else:
path = model.get_path(iter)[0] - 1
if path > 0:
selection.select_path(path)
removable_id = model[iter][0]
model.remove(iter)
return removable_id
def unsorted_painter(self, column, cell, model, iter, data):
cell_id = model.get_value(iter, 0)
cell_text = model.get_value(iter, 1)
if cell_id == -1:
text = '<span color="#555" style="italic">%s</span>' % cell_text # TODO - should get color from theme
cell.set_property('markup', text)
else:
cell.set_property('text', cell_text)
return
def on_activity_list_button_pressed(self, tree, event):
self.activityCell.set_property("editable", False)
def on_activity_list_button_released(self, tree, event):
if event.button == 1 and tree.get_path_at_pos(int(event.x), int(event.y)):
# Get treeview path.
path, column, x, y = tree.get_path_at_pos(int(event.x), int(event.y))
if self.prev_selected_activity == path:
self.activityCell.set_property("editable", True)
tree.set_cursor_on_cell(path, self.activityColumn, self.activityCell, True)
self.prev_selected_activity = path
def on_category_list_button_pressed(self, tree, event):
self.activityCell.set_property("editable", False)
def on_category_list_button_released(self, tree, event):
if event.button == 1 and tree.get_path_at_pos(int(event.x), int(event.y)):
# Get treeview path.
path, column, x, y = tree.get_path_at_pos(int(event.x), int(event.y))
if self.prev_selected_category == path and \
self._get_selected_category() != -1: #do not allow to edit unsorted
self.categoryCell.set_property("editable", True)
tree.set_cursor_on_cell(path, self.categoryColumn, self.categoryCell, True)
else:
self.categoryCell.set_property("editable", False)
self.prev_selected_category = path
def on_activity_remove_clicked(self, button):
self.remove_current_activity()
def on_activity_edit_clicked(self, button):
self.activityCell.set_property("editable", True)
selection = self.activity_tree.get_selection()
(model, iter) = selection.get_selected()
path = model.get_path(iter)
self.activity_tree.set_cursor_on_cell(path, self.activityColumn, self.activityCell, True)
"""keyboard events"""
def on_activity_list_key_pressed(self, tree, event_key):
key = event_key.keyval
selection = tree.get_selection()
(model, iter) = selection.get_selected()
if (event_key.keyval == gdk.KEY_Delete):
self.remove_current_activity()
elif key == gdk.KEY_F2 :
self.activityCell.set_property("editable", True)
path = model.get_path(iter)
tree.set_cursor_on_cell(path, self.activityColumn, self.activityCell, True)
def remove_current_activity(self):
selection = self.activity_tree.get_selection()
(model, iter) = selection.get_selected()
runtime.storage.remove_activity(model[iter][0])
self._del_selected_row(self.activity_tree)
def on_category_remove_clicked(self, button):
self.remove_current_category()
def on_category_edit_clicked(self, button):
self.categoryCell.set_property("editable", True)
selection = self.category_tree.get_selection()
(model, iter) = selection.get_selected()
path = model.get_path(iter)
self.category_tree.set_cursor_on_cell(path, self.categoryColumn, self.categoryCell, True)
def on_category_list_key_pressed(self, tree, event_key):
key = event_key.keyval
if self._get_selected_category() == -1:
return #ignoring unsorted category
selection = tree.get_selection()
(model, iter) = selection.get_selected()
if key == gdk.KEY_Delete:
self.remove_current_category()
elif key == gdk.KEY_F2:
self.categoryCell.set_property("editable", True)
path = model.get_path(iter)
tree.set_cursor_on_cell(path, self.categoryColumn, self.categoryCell, True)
def remove_current_category(self):
selection = self.category_tree.get_selection()
(model, iter) = selection.get_selected()
id = model[iter][0]
if id != -1:
runtime.storage.remove_category(id)
self._del_selected_row(self.category_tree)
def on_preferences_window_key_press(self, widget, event):
# ctrl+w means close window
if (event.keyval == gdk.KEY_w \
and event.state & gdk.ModifierType.CONTROL_MASK):
self.close_window()
# escape can mean several things
if event.keyval == gdk.KEY_Escape:
#check, maybe we are editing stuff
if self.activityCell.get_property("editable"):
self.activityCell.set_property("editable", False)
return
if self.categoryCell.get_property("editable"):
self.categoryCell.set_property("editable", False)
return
self.close_window()
"""button events"""
def on_category_add_clicked(self, button):
""" appends row, jumps to it and allows user to input name """
new_category = self.category_store.insert_before(self.category_store.unsorted_category,
[-2, _("New category")])
model = self.category_tree.get_model()
self.categoryCell.set_property("editable", True)
self.category_tree.set_cursor_on_cell(model.get_path(new_category),
focus_column = self.category_tree.get_column(0),
focus_cell = None,
start_editing = True)
def on_activity_add_clicked(self, button):
""" appends row, jumps to it and allows user to input name """
category_id = self._get_selected_category()
new_activity = self.activity_store.append([-1, _("New activity"), category_id])
(model, iter) = self.selection.get_selected()
self.activityCell.set_property("editable", True)
self.activity_tree.set_cursor_on_cell(model.get_path(new_activity),
focus_column = self.activity_tree.get_column(0),
focus_cell = None,
start_editing = True)
def on_activity_remove_clicked(self, button):
removable_id = self._del_selected_row(self.activity_tree)
runtime.storage.remove_activity(removable_id)
def on_day_start_changed(self, widget):
day_start = self.day_start.time
if day_start is None:
return
day_start = day_start.hour * 60 + day_start.minute
conf.set("day-start-minutes", day_start)
def on_close_button_clicked(self, button):
self.close_window()
| 19,247 | Python | .py | 388 | 38.664948 | 119 | 0.619149 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,543 | version.py | projecthamster_hamster/src/hamster/version.py | # Should not normally be used directly, use hamster.__version__ and
# hamster.installed instead
def get_installed_version():
try:
# defs.py is created by waf from defs.py.in
from hamster import defs
return defs.VERSION
except ImportError:
# if defs is not there, we are running from sources
return None
def get_uninstalled_version():
# If available, prefer the git version, otherwise fall back to
# the VERSION file (which is meaningful only in released
# versions)
from subprocess import getstatusoutput
rc, output = getstatusoutput("git describe --tags --always --dirty=+")
if rc == 0:
import re
# Strip "v" prefix that is used in git tags
return re.sub(r'^v', '', output.strip())
else:
from pathlib import Path
with open(Path(__file__).parent / 'VERSION', 'r') as f:
return f.read().strip()
def get_version():
"""
Figure out the hamster version.
Returns a tuple with the version string and wether we are installed or not.
"""
version = get_installed_version()
if version is not None:
return (version, True)
version = get_uninstalled_version()
return ("{} (uninstalled)".format(version), False)
if __name__ == '__main__':
import sys
# Intended to be called by waf when installing, so only return
# uninstalled version
sys.stdout.write(get_uninstalled_version())
| 1,456 | Python | .py | 39 | 31.410256 | 79 | 0.661462 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,544 | facttree.py | projecthamster_hamster/src/hamster/widgets/facttree.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2009, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import bisect
import cairo
from collections import defaultdict
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import PangoCairo as pangocairo
from gi.repository import Pango as pango
from hamster.lib import datetime as dt
from hamster.lib import graphics
from hamster.lib import stuff
from hamster.lib.fact import Fact
class ActionRow(graphics.Sprite):
def __init__(self):
graphics.Sprite.__init__(self)
self.visible = False
self.restart = graphics.Icon("view-refresh-symbolic", size=18,
interactive=True,
mouse_cursor=gdk.CursorType.HAND1,
y=4)
self.add_child(self.restart)
self.width = 50 # Simon says
class TotalFact(Fact):
"""An extension of Fact that is used for daily totals.
Instances of this class are rendered differently than instances
of Fact.
A TotalFact doesn't have a meaningful start and an end, but a
total duration (delta).
FIXME: Ideally, we should have a common parent for Fact and Total Fact
so we don't need to have nonsensical start and end properties here.
"""
def __init__(self, activity, duration):
super().__init__(activity=activity, start=dt.datetime.now(), end=dt.datetime.now())
self.duration = duration
@property
def delta(self):
return self.duration
class Label(object):
"""a much cheaper label that would be suitable for cellrenderer"""
def __init__(self, x=0, y=0, color=None):
self.x = x
self.y = y
self.color = color
self._label_context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
self.layout = pangocairo.create_layout(self._label_context)
self.layout.set_font_description(pango.FontDescription(graphics._font_desc))
self.set_text("00:00 - 00:00") # dummy time_label for finding width
@property
def height(self):
"""Label height in pixels."""
return self.layout.get_pixel_size()[1]
def set_text(self, text):
self.text = text
self.layout.set_markup(text)
def get_text(self):
return self.text
def show(self, g, text=None, x=None, y=None):
"""Show the label.
If text is given, it overrides any previous set_text().
x and y can be passed to temporary override the position.
(self.x and self.y will not be changed)
"""
g.save_context()
# fallback to self.x
if x is None:
x = self.x
if y is None:
y = self.y
g.move_to(x, y)
if text is not None:
self.set_text(text)
if self.color:
g.set_color(self.color)
pangocairo.show_layout(g.context, self.layout)
g.restore_context()
class TagLabel(Label):
"""Tag label, with small text."""
def set_text(self, text):
Label.set_text(self, "<small>{}</small>".format(text))
class FactRow(object):
def __init__(self):
self.time_label = Label()
x = self.time_label.layout.get_pixel_size()[0] + 10
self.activity_label = Label(x=x)
self.category_label = Label()
self.description_label = Label()
self.tag_label = TagLabel()
self.duration_label = Label()
self.duration_label.layout.set_alignment(pango.Alignment.RIGHT)
self.duration_label.layout.set_width(90 * pango.SCALE)
self.width = 0
# margins (in pixels)
self.tag_row_margin_H = 2.5
self.tag_row_margin_V = 2.5
self.tag_inner_margin_H = 3
self.tag_inner_margin_V = 2
self.inter_tag_margin = 4
self.row_margin_H = 5
self.row_margin_V = 2
self.category_offset_V = self.category_label.height * 0.1
@property
def height(self):
res = self.activity_label.height + 2 * 3
if self.fact.description:
res += self.description_label.height
if self.fact.tags:
res += (self.tag_label.height
+ self.tag_inner_margin_V * 2
+ self.tag_row_margin_V * 2)
res += self.row_margin_V * 2
return res
def set_fact(self, fact):
"""Set current fact."""
self.fact = fact
time_label = fact.start_time.strftime("%H:%M -")
if fact.end_time:
time_label += fact.end_time.strftime(" %H:%M")
self.time_label.set_text(time_label)
self.activity_label.set_text(stuff.escape_pango(fact.activity))
category_text = " - {}".format(stuff.escape_pango(fact.category)) if fact.category else ""
self.category_label.set_text(category_text)
text = stuff.escape_pango(fact.description)
description_text = "<small><i>{}</i></small>".format(text) if fact.description else ""
self.description_label.set_text(description_text)
if fact.tags:
# for now, tags are on a single line.
# The first one is enough to determine the height.
self.tag_label.set_text(stuff.escape_pango(fact.tags[0]))
def _show_tags(self, g, color, bg):
label = self.tag_label
label.color = bg
g.save_context()
g.translate(self.tag_row_margin_H, self.tag_row_margin_V)
for tag in self.fact.tags:
label.set_text(stuff.escape_pango(tag))
w, h = label.layout.get_pixel_size()
rw = w + self.tag_inner_margin_H * 2
rh = h + self.tag_inner_margin_V * 2
g.rectangle(0, 0, rw, rh, 2)
g.fill(color, 0.5)
label.show(g, x=self.tag_inner_margin_H, y=self.tag_inner_margin_V)
g.translate(rw + self.inter_tag_margin, 0)
g.restore_context()
def show(self, g, colors, fact=None, is_selected=False):
"""Display the fact row.
If fact is given, the fact attribute is updated.
"""
g.save_context()
if fact is not None:
# before the selection highlight, to get the correct height
self.set_fact(fact)
color, bg = colors["normal"], colors["normal_bg"]
if is_selected:
color, bg = colors["selected"], colors["selected_bg"]
g.fill_area(0, 0, self.width, self.height, bg)
g.translate(self.row_margin_H, self.row_margin_V)
g.set_color(color)
# Do not show the start/end time for Totals
if not isinstance(self.fact, TotalFact):
self.time_label.show(g)
self.activity_label.show(g, self.activity_label.get_text() if not isinstance(self.fact, TotalFact) else "<b>{}</b>".format(self.activity_label.get_text()))
if self.fact.category:
g.save_context()
category_color = graphics.ColorUtils.mix(bg, color, 0.57)
g.set_color(category_color)
x = self.activity_label.x + self.activity_label.layout.get_pixel_size()[0]
self.category_label.show(g, x=x, y=self.category_offset_V)
g.restore_context()
if self.fact.description or self.fact.tags:
g.save_context()
g.translate(self.activity_label.x, self.activity_label.height + 3)
if self.fact.tags:
self._show_tags(g, color, bg)
tag_height = (self.tag_label.height
+ self.tag_inner_margin_V * 2
+ self.tag_row_margin_V * 2)
g.translate(0, tag_height)
if self.fact.description:
self.description_label.show(g)
g.restore_context()
self.duration_label.show(g, self.fact.delta.format() if not isinstance(self.fact, TotalFact) else "<b>{}</b>".format(self.fact.delta.format()), x=self.width - 105)
g.restore_context()
class FactTree(graphics.Scene, gtk.Scrollable):
"""
The fact tree is a painter.
It does not change facts by itself, only sends signals.
Facts get updated only through `set_facts`.
It maintains scroll state and shows what we can see.
That means it does not show all the facts there are,
but rather only those that you can see.
It's also painter as it reuses labels.
Caching is futile, we do all the painting every time
ASCII Art!
| Weekday | Start - End | Activity - category [actions]| Duration |
| Month, Day | | tags, description | |
| | Start - End | Activity - category | Duration |
| | | Total | Total Duration |
Inline edit?
"""
__gsignals__ = {
# enter or double-click, passes in current day and fact
'on-activate-row': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
'on-delete-called': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
hadjustment = gobject.property(type=gtk.Adjustment, default=None)
hscroll_policy = gobject.property(type=gtk.ScrollablePolicy, default=gtk.ScrollablePolicy.MINIMUM)
vadjustment = gobject.property(type=gtk.Adjustment, default=None)
vscroll_policy = gobject.property(type=gtk.ScrollablePolicy, default=gtk.ScrollablePolicy.MINIMUM)
def __init__(self):
graphics.Scene.__init__(self, style_class=gtk.STYLE_CLASS_VIEW)
self.date_label = Label(10, 3)
fontdesc = pango.FontDescription(graphics._font_desc)
fontdesc.set_weight(pango.Weight.BOLD)
self.date_label.layout.set_alignment(pango.Alignment.RIGHT)
self.date_label.layout.set_width(80 * pango.SCALE)
self.date_label.layout.set_font_description(fontdesc)
self.fact_row = FactRow()
self.action_row = ActionRow()
# self.add_child(self.action_row)
self.row_positions = []
self.row_heights = []
self.y = 0
self.day_padding = 20
self.hover_day = None
self.hover_fact = None
self.current_fact = None
self.style = self._style
self.visible_range = None
self.set_size_request(500, 400)
self.connect("on-mouse-scroll", self.on_scroll)
self.connect("on-mouse-move", self.on_mouse_move)
self.connect("on-mouse-down", self.on_mouse_down)
self.connect("on-resize", self.on_resize)
self.connect("on-key-press", self.on_key_press)
self.connect("notify::vadjustment", self._on_vadjustment_change)
self.connect("on-enter-frame", self.on_enter_frame)
self.connect("on-double-click", self.on_double_click)
@property
def current_fact_index(self):
"""Current fact index in the self.facts list."""
facts_ids = [fact.id for fact in self.facts]
return facts_ids.index(self.current_fact.id)
def on_mouse_down(self, scene, event):
self.on_mouse_move(None, event)
self.grab_focus()
if self.hover_fact:
# match either content or id
if (self.hover_fact == self.current_fact
or (self.hover_fact
and self.current_fact
and self.hover_fact.id == self.current_fact.id)
):
self.unset_current_fact()
# Totals can't be selected
elif not isinstance(self.hover_fact, TotalFact):
self.set_current_fact(self.hover_fact)
def activate_row(self, day, fact):
self.emit("on-activate-row", day, fact)
def delete_row(self, fact):
self.emit("on-delete-called", fact)
def on_double_click(self, scene, event):
if self.hover_fact and not isinstance(self.hover_fact, TotalFact):
self.activate_row(self.hover_day, self.hover_fact)
def on_key_press(self, scene, event):
# all keys should appear also in the Overview.on_key_press
# to be forwarded here even without focus.
if event.keyval == gdk.KEY_Up:
if self.facts:
if self.current_fact:
idx = max(0, self.current_fact_index - 1)
else:
# enter from below
idx = len(self.facts) - 1
self.set_current_fact(self.facts[idx])
elif event.keyval == gdk.KEY_Down:
if self.facts:
if self.current_fact:
idx = min(len(self.facts) - 1, self.current_fact_index + 1)
else:
# enter from top
idx = 0
self.set_current_fact(self.facts[idx])
elif event.keyval == gdk.KEY_Home:
if self.facts:
self.set_current_fact(self.facts[0])
elif event.keyval == gdk.KEY_End:
if self.facts:
self.set_current_fact(self.facts[-1])
elif event.keyval == gdk.KEY_Page_Down:
self.y += self.height * 0.8
self.on_scroll()
elif event.keyval == gdk.KEY_Page_Up:
self.y -= self.height * 0.8
self.on_scroll()
elif event.keyval == gdk.KEY_Return:
if self.current_fact:
self.activate_row(self.hover_day, self.current_fact)
elif event.keyval == gdk.KEY_Delete:
if self.current_fact:
self.delete_row(self.current_fact)
def set_current_fact(self, fact):
self.current_fact = fact
if fact.y < self.y:
self.y = fact.y
if (fact.y + fact.height) > (self.y + self.height):
self.y = fact.y + fact.height - self.height
self.on_scroll()
def unset_current_fact(self):
"""Deselect fact."""
self.current_fact = None
self.on_scroll()
def get_visible_range(self):
start, end = (bisect.bisect(self.row_positions, self.y) - 1,
bisect.bisect(self.row_positions, self.y + self.height))
y = self.y
return [{"i": start + i, "y": pos - y, "h": height, "day": day, "facts": facts}
for i, (pos, height, (day, facts)) in enumerate(zip(self.row_positions[start:end],
self.row_heights[start:end],
self.days[start:end]))]
def on_mouse_move(self, tree, event):
hover_day, hover_fact = None, None
for rec in self.visible_range:
if rec['y'] <= event.y <= (rec['y'] + rec['h']):
hover_day = rec
break
if hover_day != self.hover_day:
# Facts are considered equal if their content is the same,
# even if their id is different.
# redraw only cares about content, not id.
self.redraw()
# make sure it is always fully updated, including facts ids.
self.hover_day = hover_day
if self.hover_day:
for fact in self.hover_day.get('facts', []):
if (fact.y - self.y) <= event.y <= (fact.y - self.y + fact.height):
hover_fact = fact
break
if (hover_fact
and self.hover_fact
and hover_fact.id != self.hover_fact.id
):
self.move_actions()
# idem, always update hover_fact, not just if they appear different
self.hover_fact = hover_fact
def move_actions(self):
if self.hover_fact:
self.action_row.visible = True
self.action_row.x = self.width - 80 - self.action_row.width
self.action_row.y = self.hover_fact.y - self.y
else:
self.action_row.visible = False
def _on_vadjustment_change(self, scene, vadjustment):
if not self.vadjustment:
return
self.vadjustment.connect("value_changed", self.on_scroll_value_changed)
self.set_size_request(500, 300)
def set_facts(self, facts, scroll_to_top=False):
# FactTree adds attributes to its facts. isolate these side effects
# copy the id too; most of the checks are based on id here.
self.facts = [fact.copy(id=fact.id) for fact in facts]
del facts # make sure facts is not used by inadvertance below.
# If we get an entirely new set of facts, scroll back to the top
if scroll_to_top:
self.y = 0
self.hover_fact = None
if self.vadjustment:
self.vadjustment.set_value(self.y)
if self.facts:
start = self.facts[0].date
end = self.facts[-1].date
else:
start = end = dt.hday.today()
by_date = defaultdict(list)
delta_by_date = defaultdict(dt.timedelta)
for fact in self.facts:
by_date[fact.date].append(fact)
delta_by_date[fact.date] += fact.delta
# Add a TotalFact at the end of each day if we are
# displaying more than one day.
if len(by_date) > 1:
for key in by_date:
total_by_date = TotalFact(_("Total"), delta_by_date[key])
by_date[key].append(total_by_date)
days = []
for i in range((end - start).days + 1):
current_date = start + dt.timedelta(days=i)
if current_date in by_date:
days.append((current_date, by_date[current_date]))
self.days = days
self.set_row_heights()
if (self.current_fact
and self.current_fact.id in (fact.id for fact in self.facts)
):
self.on_scroll()
else:
# will also trigger an on_scroll
self.unset_current_fact()
def set_row_heights(self):
"""
the row height is defined by following factors:
* how many facts are there in the day
* does the fact have description / tags
This func creates a list of row start positions to be able to
quickly determine what to display
"""
if not self.height:
return
y, pos, heights = 0, [], []
for date, facts in self.days:
height = 0
for fact in facts:
self.fact_row.set_fact(fact)
fact_height = self.fact_row.height
fact.y = y + height
fact.height = fact_height
height += fact.height
height += self.day_padding
height = max(height, 60)
pos.append(y)
heights.append(height)
y += height
self.row_positions, self.row_heights = pos, heights
maxy = max(y, 1)
if self.vadjustment:
self.vadjustment.set_lower(0)
self.vadjustment.set_upper(max(maxy, self.height))
self.vadjustment.set_page_size(self.height)
def on_resize(self, scene, event):
self.set_row_heights()
self.fact_row.width = self.width - 105
self.on_scroll()
def on_scroll_value_changed(self, scroll):
self.y = int(scroll.get_value())
self.on_scroll()
def on_scroll(self, scene=None, event=None):
if not self.height:
return
y_pos = self.y
direction = 0
if event and event.direction == gdk.ScrollDirection.UP:
direction = -1
elif event and event.direction == gdk.ScrollDirection.DOWN:
direction = 1
y_pos += 15 * direction
if self.vadjustment:
y_pos = max(0, min(self.vadjustment.get_upper() - self.height, y_pos))
self.vadjustment.set_value(y_pos)
self.y = y_pos
self.move_actions()
self.redraw()
self.visible_range = self.get_visible_range()
def on_enter_frame(self, scene, context):
has_focus = self.get_toplevel().has_toplevel_focus()
if has_focus:
colors = {
"normal": self.style.get_color(gtk.StateFlags.NORMAL),
"normal_bg": self.style.get_background_color(gtk.StateFlags.NORMAL),
"selected": self.style.get_color(gtk.StateFlags.SELECTED),
"selected_bg": self.style.get_background_color(gtk.StateFlags.SELECTED),
}
else:
colors = {
"normal": self.style.get_color(gtk.StateFlags.BACKDROP),
"normal_bg": self.style.get_background_color(gtk.StateFlags.BACKDROP),
"selected": self.style.get_color(gtk.StateFlags.BACKDROP),
"selected_bg": self.style.get_background_color(gtk.StateFlags.BACKDROP),
}
if not self.height:
return
g = graphics.Graphics(context)
g.set_line_style(1)
g.translate(0.5, 0.5)
date_bg_color = self.colors.mix(colors["normal_bg"], colors["normal"], 0.15)
g.fill_area(0, 0, 105, self.height, date_bg_color)
y = int(self.y)
for rec in self.visible_range:
g.save_context()
g.translate(0, rec['y'])
g.set_color(colors["normal"])
self.date_label.show(g, rec['day'].strftime("%A\n%b %d"))
g.translate(105, 0)
for fact in rec['facts']:
is_selected = (self.current_fact is not None
and fact.id == self.current_fact.id)
self.fact_row.set_fact(fact)
self.fact_row.show(g, colors, is_selected=is_selected)
g.translate(0, self.fact_row.height)
g.restore_context()
| 22,557 | Python | .py | 501 | 34.243513 | 171 | 0.587959 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,545 | tags.py | projecthamster_hamster/src/hamster/widgets/tags.py | # - coding: utf-8 -
# Copyright (C) 2009 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject as gobject
from gi.repository import Gdk as gdk
from gi.repository import Gtk as gtk
from gi.repository import Pango as pango
import cairo
from math import pi
from hamster.lib import graphics, stuff
from hamster.lib.configuration import runtime
class TagsEntry(gtk.Entry):
__gsignals__ = {
'tags-selected': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self, *, parent):
gtk.Entry.__init__(self, parent=parent)
self.ac_tags = None # "autocomplete" tags
self.filter = None # currently applied filter string
self.filter_tags = [] #filtered tags
self.popup = gtk.Window(type = gtk.WindowType.POPUP)
self.popup.set_attached_to(self)
self.popup.set_transient_for(self.get_ancestor(gtk.Window))
self.scroll_box = gtk.ScrolledWindow()
self.scroll_box.set_shadow_type(gtk.ShadowType.IN)
self.scroll_box.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC)
viewport = gtk.Viewport()
viewport.set_shadow_type(gtk.ShadowType.NONE)
self.tag_box = TagBox()
self.tag_box.connect("tag-selected", self.on_tag_selected)
self.tag_box.connect("tag-unselected", self.on_tag_unselected)
viewport.add(self.tag_box)
self.scroll_box.add(viewport)
self.popup.add(self.scroll_box)
self.set_icon_from_icon_name(gtk.EntryIconPosition.SECONDARY, "go-down-symbolic")
self.connect("icon-press", self._on_icon_press)
self.connect("key-press-event", self._on_key_press_event)
self.connect("focus-out-event", self._on_focus_out_event)
self._parent_click_watcher = None # bit lame but works
self.external_listeners = [
(runtime.storage, runtime.storage.connect('tags-changed', self.refresh_ac_tags))
]
self.show()
self.populate_suggestions()
self.connect("destroy", self.on_destroy)
def on_destroy(self, window):
for obj, handler in self.external_listeners:
obj.disconnect(handler)
self.popup.destroy()
self.popup = None
def refresh_ac_tags(self, event):
self.ac_tags = None
def get_tags(self):
# splits the string by comma and filters out blanks
return [tag.strip() for tag in self.get_text().split(",") if tag.strip()]
def on_tag_selected(self, tag_box, tag):
cursor_tag = self.get_cursor_tag()
if cursor_tag and tag.lower().startswith(cursor_tag.lower()):
self.replace_tag(cursor_tag, tag)
tags = self.get_tags()
else:
tags = self.get_tags()
tags.append(tag)
self.tag_box.selected_tags = tags
self.set_tags(tags)
self.update_tagsline(add=True)
self.populate_suggestions()
self.show_popup()
def on_tag_unselected(self, tag_box, tag):
tags = self.get_tags()
while tag in tags: #it could be that dear user is mocking us and entering same tag over and over again
tags.remove(tag)
self.tag_box.selected_tags = tags
self.set_tags(tags)
self.update_tagsline(add=True)
def hide_popup(self):
self.popup.hide()
if self._parent_click_watcher and self.get_toplevel().handler_is_connected(self._parent_click_watcher):
self.get_toplevel().disconnect(self._parent_click_watcher)
self._parent_click_watcher = None
def show_popup(self):
if not self.filter_tags:
self.popup.hide()
return
if not self._parent_click_watcher:
self._parent_click_watcher = self.get_toplevel().connect("button-press-event", self._on_focus_out_event)
alloc = self.get_allocation()
_, x, y = self.get_parent_window().get_origin()
self.popup.move(x + alloc.x,y + alloc.y + alloc.height)
w = alloc.width
height = self.tag_box.count_height(w)
self.scroll_box.set_size_request(w, height)
self.popup.resize(w, height)
self.popup.show_all()
def refresh_activities(self):
# scratch activities and categories so that they get repopulated on demand
self.activities = None
self.categories = None
def populate_suggestions(self):
self.ac_tags = self.ac_tags or [tag["name"] for tag in
runtime.storage.get_tags(only_autocomplete=True)]
cursor_tag = self.get_cursor_tag()
self.filter = cursor_tag
entered_tags = self.get_tags()
self.tag_box.selected_tags = entered_tags
self.filter_tags = [tag for tag in self.ac_tags
if (tag or "").lower().startswith((self.filter or "").lower())]
self.tag_box.draw(self.filter_tags)
def _on_focus_out_event(self, widget, event):
self.hide_popup()
def _on_icon_press(self, entry, icon_pos, event):
# otherwise Esc could not hide popup
self.grab_focus()
# toggle popup
if self.popup.get_visible():
# remove trailing comma if any
self.update_tagsline(add=False)
self.hide_popup()
else:
# add trailing comma
self.update_tagsline(add=True)
self.populate_suggestions()
self.show_popup()
def get_cursor_tag(self):
#returns the tag on which the cursor is on right now
if self.get_selection_bounds():
cursor = self.get_selection_bounds()[0]
else:
cursor = self.get_position()
text = self.get_text()
return text[text.rfind(",", 0, cursor)+1:max(text.find(",", cursor+1)+1, len(text))].strip()
def replace_tag(self, old_tag, new_tag):
tags = self.get_tags()
if old_tag in tags:
tags[tags.index(old_tag)] = new_tag
if self.get_selection_bounds():
cursor = self.get_selection_bounds()[0]
else:
cursor = self.get_position()
self.set_tags(tags)
self.set_position(len(self.get_text()))
def set_tags(self, tags):
self.tags = tags
self.update_tagsline()
def update_tagsline(self, add=False):
"""Update tags line text.
If add is True, prepare to add tags to the list:
a comma is appended and the popup is displayed.
"""
text = ", ".join(self.tags)
if add and text:
text = "{}, ".format(text)
self.set_text(text)
self.set_position(len(self.get_text()))
def _on_key_press_event(self, entry, event):
if event.keyval == gdk.KEY_Tab:
if self.popup.get_property("visible"):
#we have to replace
if self.get_text() and self.get_cursor_tag() != self.filter_tags[0]:
self.replace_tag(self.get_cursor_tag(), self.filter_tags[0])
return True
else:
return False
else:
return False
elif event.keyval in (gdk.KEY_Return, gdk.KEY_KP_Enter):
if self.popup.get_property("visible"):
if self.get_text():
self.hide_popup()
return True
else:
if self.get_text():
self.emit("tags-selected")
return False
elif event.keyval == gdk.KEY_Escape:
if self.popup.get_property("visible"):
self.hide_popup()
return True
else:
return False
else:
self.populate_suggestions()
self.show_popup()
return False
class TagBox(graphics.Scene):
__gsignals__ = {
'tag-selected': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str,)),
'tag-unselected': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str,)),
}
def __init__(self, interactive = True):
graphics.Scene.__init__(self)
self.interactive = interactive
self.hover_tag = None
self.tags = []
self.selected_tags = []
self.layout = None
if self.interactive:
self.connect("on-mouse-over", self.on_mouse_over)
self.connect("on-mouse-out", self.on_mouse_out)
self.connect("on-click", self.on_tag_click)
self.connect("on-enter-frame", self.on_enter_frame)
def on_mouse_over(self, area, tag):
tag.color = tag.graphics.colors.darker(tag.color, -20)
def on_mouse_out(self, area, tag):
if tag.text in self.selected_tags:
tag.color = (242, 229, 97)
else:
tag.color = (241, 234, 170)
def on_tag_click(self, area, event, tag):
if not tag: return
if tag.text in self.selected_tags:
self.emit("tag-unselected", tag.text)
else:
self.emit("tag-selected", tag.text)
self.on_mouse_out(area, tag) #paint
self.redraw()
def draw(self, tags):
new_tags = []
for label in tags:
tag = Tag(label)
if label in self.selected_tags:
tag.color = (242, 229, 97)
new_tags.append(tag)
for tag in self.tags:
self.sprites.remove(tag)
self.add_child(*new_tags)
self.tags = new_tags
self.show()
self.redraw()
def count_height(self, width):
# reposition tags and see how much space we take up
self.width = width
w, h = self.on_enter_frame(None, None)
return h + 6
def on_enter_frame(self, scene, context):
cur_x, cur_y = 4, 4
tag = None
for tag in self.tags:
if cur_x + tag.width >= self.width - 5: #if we do not fit, we wrap
cur_x = 5
cur_y += tag.height + 6
tag.x = cur_x
tag.y = cur_y
cur_x += tag.width + 6 #some padding too, please
if tag:
cur_y += tag.height + 2 # the last one
return cur_x, cur_y
class Tag(graphics.Sprite):
def __init__(self, text, interactive = True, color = "#F1EAAA"):
graphics.Sprite.__init__(self, interactive = interactive)
self.width, self.height = 0,0
font = gtk.Style().font_desc
font_size = int(font.get_size() * 0.8 / pango.SCALE) # 80% of default
self.label = graphics.Label(text, size = font_size, color = (30, 30, 30), y = 1)
self.color = color
self.add_child(self.label)
self.corner = int((self.label.height + 3) / 3) + 0.5
self.label.x = self.corner + 6
self.text = stuff.escape_pango(text)
self.connect("on-render", self.on_render)
def __setattr__(self, name, value):
graphics.Sprite.__setattr__(self, name, value)
if name == 'text' and hasattr(self, 'label'):
self.label.text = value
self.__dict__['width'], self.__dict__['height'] = int(self.label.x + self.label.width + self.label.height * 0.3), self.label.height + 3
def on_render(self, sprite):
self.graphics.set_line_style(width=1)
self.graphics.move_to(0.5, self.corner)
self.graphics.line_to([(self.corner, 0.5),
(self.width + 0.5, 0.5),
(self.width + 0.5, self.height - 0.5),
(self.corner, self.height - 0.5),
(0.5, self.height - self.corner)])
self.graphics.close_path()
self.graphics.fill_stroke(self.color, "#b4b4b4")
self.graphics.circle(6, self.height / 2, 2)
self.graphics.fill_stroke("#fff", "#b4b4b4")
| 12,521 | Python | .py | 287 | 33.58885 | 147 | 0.596376 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,546 | activityentry.py | projecthamster_hamster/src/hamster/widgets/activityentry.py | # - coding: utf-8 -
# Copyright (C) 2008-2009 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import logging
logger = logging.getLogger(__name__) # noqa: E402
import bisect
import cairo
import re
from gi.repository import Gdk as gdk
from gi.repository import Gtk as gtk
from gi.repository import GObject as gobject
from gi.repository import PangoCairo as pangocairo
from gi.repository import Pango as pango
from collections import defaultdict
from copy import deepcopy
from hamster import client
from hamster.lib import datetime as dt
from hamster.lib import stuff
from hamster.lib import graphics
from hamster.lib.configuration import runtime
from hamster.lib.fact import Fact
# note: Still experimenting in this module.
# Code redundancy to be removed later.
def extract_search(text):
fact = Fact.parse(text)
search = fact.activity
if fact.category:
search += "@%s" % fact.category
if fact.tags:
search += " #%s" % (" #".join(fact.tags))
return search
class DataRow(object):
"""want to split out visible label, description, activity data
and activity data with time (full_data)"""
def __init__(self, label, data=None, full_data=None, description=None):
self.label = label
self.data = data or label
self.full_data = full_data or data or label
self.description = description or ""
class Label(object):
"""a much cheaper label that would be suitable for cellrenderer"""
def __init__(self, x=0, y=0):
self.x, self.y = x, y
self._label_context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
self.layout = pangocairo.create_layout(self._label_context)
self.layout.set_font_description(pango.FontDescription(graphics._font_desc))
self.layout.set_markup("Hamster") # dummy
self.height = self.layout.get_pixel_size()[1]
def show(self, g, text, color=None):
g.move_to(self.x, self.y)
self.layout.set_markup(text)
g.save_context()
if color:
g.set_color(color)
pangocairo.show_layout(g.context, self.layout)
g.restore_context()
class CompleteTree(graphics.Scene):
"""
ASCII Art
| Icon | Activity - description |
"""
__gsignals__ = {
# enter or double-click, passes in current day and fact
'on-select-row': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self):
graphics.Scene.__init__(self, style_class=gtk.STYLE_CLASS_VIEW)
self.set_can_focus(False)
self.row_positions = []
self.current_row = None
self.rows = []
self.style = self._style
self.label = Label(x=5, y=3)
self.row_height = self.label.height + 10
self.connect("on-key-press", self.on_key_press)
self.connect("on-enter-frame", self.on_enter_frame)
self.connect("on-mouse-move", self.on_mouse_move)
self.connect("on-mouse-down", self.on_mouse_down)
def _get_mouse_row(self, event):
hover_row = None
for row, y in zip(self.rows, self.row_positions):
if y <= event.y <= (y + self.row_height):
hover_row = row
break
return hover_row
def on_mouse_move(self, scene, event):
row = self._get_mouse_row(event)
if row:
self.current_row = row
self.redraw()
def on_mouse_down(self, scene, event):
row = self._get_mouse_row(event)
if row:
self.set_current_row(self.rows.index(row))
def on_key_press(self, scene, event):
if event.keyval == gdk.KEY_Up:
idx = self.rows.index(self.current_row) if self.current_row else 1
self.set_current_row(idx - 1)
elif event.keyval == gdk.KEY_Down:
idx = self.rows.index(self.current_row) if self.current_row else -1
self.set_current_row(idx + 1)
def set_current_row(self, idx):
idx = max(0, min(len(self.rows) - 1, idx))
row = self.rows[idx]
self.current_row = row
self.redraw()
self.emit("on-select-row", row)
def set_rows(self, rows):
self.current_row = None
self.rows = rows
self.set_row_positions()
def set_row_positions(self):
"""creates a list of row positions for simpler manipulation"""
self.row_positions = [i * self.row_height for i in range(len(self.rows))]
self.set_size_request(0, self.row_positions[-1] + self.row_height if self.row_positions else 0)
def on_enter_frame(self, scene, context):
if not self.height:
return
colors = {
"normal": self.style.get_color(gtk.StateFlags.NORMAL),
"normal_bg": self.style.get_background_color(gtk.StateFlags.NORMAL),
"selected": self.style.get_color(gtk.StateFlags.SELECTED),
"selected_bg": self.style.get_background_color(gtk.StateFlags.SELECTED),
}
g = graphics.Graphics(context)
g.set_line_style(1)
g.translate(0.5, 0.5)
for row, y in zip(self.rows, self.row_positions):
g.save_context()
g.translate(0, y)
color, bg = colors["normal"], colors["normal_bg"]
if row == self.current_row:
color, bg = colors["selected"], colors["selected_bg"]
g.fill_area(0, 0, self.width, self.row_height, bg)
label = row.label
if row.description:
description_color = graphics.Colors.mix(bg, color, 0.75)
description_color_str = graphics.Colors.hex(description_color)
label = '{} <span color="{}">[{}]</span>'.format(label,
description_color_str,
row.description)
self.label.show(g, label, color=color)
g.restore_context()
class CmdLineEntry(gtk.Entry):
def __init__(self, *, parent, **kwargs):
gtk.Entry.__init__(self, parent=parent, **kwargs)
# default day for times without date
self.default_day = None
# to be set by the caller, if editing an existing fact
self.original_fact = None
self.popup = gtk.Window(type = gtk.WindowType.POPUP)
self.popup.set_type_hint(gdk.WindowTypeHint.COMBO) # why not
self.popup.set_attached_to(self) # attributes
self.popup.set_transient_for(self.get_ancestor(gtk.Window)) # position
box = gtk.Frame()
box.set_shadow_type(gtk.ShadowType.IN)
self.popup.add(box)
self.complete_tree = CompleteTree()
self.tree_checker = self.complete_tree.connect("on-select-row", self.on_tree_select_row)
self.complete_tree.connect("on-click", self.on_tree_click)
box.add(self.complete_tree)
self.storage = client.Storage()
self.load_suggestions()
self.ignore_stroke = False
self.set_icon_from_icon_name(gtk.EntryIconPosition.SECONDARY, "go-down-symbolic")
self.checker = self.connect("changed", self.on_changed)
self.connect("key-press-event", self.on_key_press)
self.connect("focus-out-event", self.on_focus_out)
self.connect("icon-press", self.on_icon_press)
def on_changed(self, entry):
text = self.get_text()
with self.complete_tree.handler_block(self.tree_checker):
self.show_suggestions(text)
if self.ignore_stroke:
self.ignore_stroke = False
return
def complete():
text, suffix = self.complete_first()
if suffix:
#self.ignore_stroke = True
with self.handler_block(self.checker):
self.update_entry("%s%s" % (text, suffix))
self.select_region(len(text), -1)
gobject.timeout_add(0, complete)
def on_focus_out(self, entry, event):
self.popup.hide()
def on_icon_press(self, entry, icon, event):
if self.popup.get_visible():
self.popup.hide()
else:
self.grab_focus()
self.show_suggestions(self.get_text())
def on_key_press(self, entry, event=None):
if event.keyval in (gdk.KEY_BackSpace, gdk.KEY_Delete):
self.ignore_stroke = True
elif event.keyval in (gdk.KEY_Return, gdk.KEY_KP_Enter, gdk.KEY_Escape):
self.popup.hide()
self.set_position(-1)
elif event.keyval in (gdk.KEY_Up, gdk.KEY_Down):
if not self.popup.get_visible():
self.show_suggestions(self.get_text())
self.complete_tree.on_key_press(self, event)
return True
def on_tree_click(self, entry, tree, event):
self.popup.hide()
def on_tree_select_row(self, tree, row):
with self.handler_block(self.checker):
label = row.full_data
self.update_entry(label)
self.set_position(-1)
def load_suggestions(self):
self.todays_facts = self.storage.get_todays_facts()
# list of facts of last month
now = dt.datetime.now()
last_month = self.storage.get_facts(now - dt.timedelta(days=30), now)
# naive recency and frequency rank
# score is as simple as you get 30-days_ago points for each occurence
suggestions = defaultdict(int)
for fact in last_month:
days = 30 - (now - dt.datetime.combine(fact.date, dt.time())).total_seconds() / 60 / 60 / 24
label = fact.activity
if fact.category:
label += "@%s" % fact.category
suggestions[label] += days
if fact.tags:
label += " #%s" % (" #".join(fact.tags))
suggestions[label] += days
for rec in self.storage.get_activities():
label = rec["name"]
if rec["category"]:
label += "@%s" % rec["category"]
suggestions[label] += 0
# list of (label, score), higher scores first
self.suggestions = sorted(suggestions.items(), key=lambda x: x[1], reverse=True)
def complete_first(self):
text = self.get_text()
fact = Fact.parse(text)
search = extract_search(text)
if not self.complete_tree.rows or not fact.activity:
return text, None
label = self.complete_tree.rows[0].data
if label.startswith(search):
return text, label[len(search):]
return text, None
def update_entry(self, text):
self.set_text(text or "")
def update_suggestions(self, text=""):
"""
* from previous activity | set time | minutes ago | start now
* to ongoing | set time
* activity
* [@category]
* #tags, #tags, #tags
* we will leave description for later
all our magic is space separated, strictly, start-end can be just dash
phases:
[start_time] | [-end_time] | activity | [@category] | [#tag]
"""
res = []
fact = Fact.parse(text)
now = dt.datetime.now()
# figure out what we are looking for
# time -> activity[@category] -> tags -> description
# presence of an attribute means that we are not looking for the previous one
# we still might be looking for the current one though
looking_for = "start_time"
fields = ["start_time", "end_time", "activity", "category", "tags", "description", "done"]
for field in reversed(fields):
if getattr(fact, field, None):
looking_for = field
if text[-1] == " ":
looking_for = fields[fields.index(field)+1]
break
fragments = [f for f in re.split("[\s|#]", text)]
current_fragment = fragments[-1] if fragments else ""
search = extract_search(text)
matches = []
for match, score in self.suggestions:
if search in match:
if match.startswith(search):
score += 10**8 # boost beginnings
matches.append((match, score))
# need to limit these guys, sorry
matches = sorted(matches, key=lambda x: x[1], reverse=True)[:7]
for match, score in matches:
label = (fact.start_time or now).strftime("%H:%M")
if fact.end_time:
label += fact.end_time.strftime("-%H:%M")
markup_label = label + " " + (stuff.escape_pango(match).replace(search, "<b>%s</b>" % search) if search else match)
label += " " + match
res.append(DataRow(markup_label, match, label))
# list of tuples (description, variant)
variants = []
variant_fact = None
if fact.end_time is None:
description = "stop now"
variant_fact = fact.copy()
variant_fact.end_time = now
elif self.todays_facts and fact == self.todays_facts[-1]:
# that one is too dangerous, except for the last entry
description = "keep up"
# Do not use Fact(..., end_time=None): it would be a no-op
variant_fact = fact.copy()
variant_fact.end_time = None
if variant_fact:
variant_fact.description = None
variant = variant_fact.serialized(default_day=self.default_day)
variants.append((description, variant))
if fact.start_time is None:
description = "start now"
variant = now.strftime("%H:%M ")
variants.append((description, variant))
prev_fact = self.todays_facts[-1] if self.todays_facts else None
if prev_fact and prev_fact.end_time:
since = (now - prev_fact.end_time).format()
description = "from previous activity, %s ago" % since
variant = prev_fact.end_time.strftime("%H:%M ")
variants.append((description, variant))
description = "start activity -n minutes ago (1 or 3 digits allowed)"
variant = "-"
variants.append((description, variant))
text = text.strip()
if text:
description = "clear"
variant = ""
variants.append((description, variant))
for (description, variant) in variants:
res.append(DataRow(variant, description=description))
self.complete_tree.set_rows(res)
def show_suggestions(self, text):
if not self.get_window():
return
entry_alloc = self.get_allocation()
entry_x, entry_y = self.get_window().get_origin()[1:]
x, y = entry_x + entry_alloc.x, entry_y + entry_alloc.y + entry_alloc.height
self.popup.show_all()
self.update_suggestions(text)
tree_w, tree_h = self.complete_tree.get_size_request()
self.popup.move(x, y)
self.popup.resize(entry_alloc.width, tree_h)
self.popup.show_all()
class ActivityEntry():
"""Activity entry widget.
widget (gtk.Entry): the associated activity entry
category_widget (gtk.Entry): the associated category entry
"""
def __init__(self, widget=None, category_widget=None, **kwds):
# widget and completion may be defined already
# e.g. in the glade edit_activity.ui file
self.widget = widget
if not self.widget:
self.widget = gtk.Entry(**kwds)
self.category_widget = category_widget
# internal list of actions added to the suggestions
self._action_list = []
self.completion = self.widget.get_completion()
if not self.completion:
self.completion = gtk.EntryCompletion()
self.widget.set_completion(self.completion)
# text to display/filter on, activity, category
self.text_column = 0
self.activity_column = 1
self.category_column = 2
# whether the category choice limit the activity suggestions
self.filter_on_category = True if self.category_widget else False
self.model = gtk.ListStore(str, str, str)
self.completion.set_model(self.model)
self.completion.set_text_column(self.text_column)
self.completion.set_match_func(self.match_func, None)
# enable selection with up and down arrow
self.completion.set_inline_selection(True)
# It is not possible to change actions later dynamically;
# once actions are removed,
# they can not be added back (they are not visible).
# => nevermind, showing all actions.
self.add_action("show all", "Show all activities")
self.add_action("filter on category", "Filter on selected category")
self.connect("icon-release", self.on_icon_release)
self.connect("focus-in-event", self.on_focus_in_event)
self.completion.connect('match-selected', self.on_match_selected)
self.completion.connect("action_activated", self.on_action_activated)
def add_action(self, name, text):
"""Add an action to the suggestions.
name (str): unique label, use to retrieve the action index.
text (str): text used to display the action.
"""
markup = "<i>{}</i>".format(stuff.escape_pango(text))
idx = len(self._action_list)
self.completion.insert_action_markup(idx, markup)
self._action_list.append(name)
def clear(self, notify=True):
self.widget.set_text("")
if notify:
self.emit("changed")
def match_func(self, completion, key, iter, *user_data):
if not key.strip():
# show all keys if entry is empty
return True
else:
# return whether the entered string is
# anywhere in the first column data
stripped_key = key.strip()
activities = self.model.get_value(iter, self.activity_column).lower()
categories = self.model.get_value(iter, self.category_column).lower()
key_in_activity = stripped_key in activities
key_in_category = stripped_key in categories
return key_in_activity or key_in_category
def on_action_activated(self, completion, index):
name = self._action_list[index]
if name == "clear":
self.clear(notify=False)
elif name == "show all":
self.filter_on_category = False
self.populate_completions()
elif name == "filter on category":
self.filter_on_category = True
self.populate_completions()
def on_focus_in_event(self, widget, event):
self.populate_completions()
def on_icon_release(self, entry, icon_pos, event):
self.grab_focus()
self.set_text("")
self.emit("changed")
def on_match_selected(self, entry, model, iter):
activity_name = model[iter][self.activity_column]
category_name = model[iter][self.category_column]
combined = model[iter][self.text_column]
if self.category_widget:
self.set_text(activity_name)
if not self.filter_on_category:
self.category_widget.set_text(category_name)
else:
self.set_text(combined)
return True # prevent the standard callback from overwriting text
def populate_completions(self):
self.model.clear()
if self.filter_on_category:
category_names = [self.category_widget.get_text()]
else:
category_names = [category['name']
for category in runtime.storage.get_categories()]
for category_name in category_names:
category_id = runtime.storage.get_category_id(category_name)
activities = runtime.storage.get_category_activities(category_id)
for activity in activities:
activity_name = activity["name"]
text = "{}@{}".format(activity_name, category_name)
self.model.append([text, activity_name, category_name])
def __getattr__(self, name):
return getattr(self.widget, name)
class CategoryEntry():
"""Category entry widget.
widget (gtk.Entry): the associated category entry
"""
def __init__(self, widget=None, **kwds):
# widget and completion are already defined
# e.g. in the glade edit_activity.ui file
self.widget = widget
if not self.widget:
self.widget = gtk.Entry(**kwds)
self.completion = self.widget.get_completion()
if not self.completion:
self.completion = gtk.EntryCompletion()
self.widget.set_completion(self.completion)
self.completion.insert_action_markup(0, "<i>Clear ({})</i>".format(_("Unsorted")))
self.unsorted_action_index = 0
self.model = gtk.ListStore(str)
self.completion.set_model(self.model)
self.completion.set_text_column(0)
self.completion.set_match_func(self.match_func, None)
self.widget.connect("icon-release", self.on_icon_release)
self.widget.connect("focus-in-event", self.on_focus_in_event)
self.completion.connect("action_activated", self.on_action_activated)
def clear(self, notify=True):
self.widget.set_text("")
if notify:
self.emit("changed")
def match_func(self, completion, key, iter, *user_data):
if not key.strip():
# show all keys if entry is empty
return True
else:
# return whether the entered string is
# anywhere in the first column data
return key.strip() in self.model.get_value(iter, 0).lower()
def on_action_activated(self, completion, index):
if index == self.unsorted_action_index:
self.clear(notify=False)
def on_focus_in_event(self, widget, event):
self.populate_completions()
def on_icon_release(self, entry, icon_pos, event):
self.widget.grab_focus()
# do not emit changed on the primary (clear) button
self.clear()
def populate_completions(self):
self.model.clear()
for category in runtime.storage.get_categories():
self.model.append([category['name']])
def __getattr__(self, name):
return getattr(self.widget, name)
| 23,206 | Python | .py | 510 | 35.523529 | 127 | 0.611621 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,547 | dayline.py | projecthamster_hamster/src/hamster/widgets/dayline.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import time
from gi.repository import Gtk as gtk
from gi.repository import GObject as gobject
from gi.repository import PangoCairo as pangocairo
from hamster.lib import datetime as dt
from hamster.lib import graphics, pytweener
from hamster.lib.configuration import conf
class Selection(graphics.Sprite):
def __init__(self, start_time = None, end_time = None):
graphics.Sprite.__init__(self, z_order = 100)
self.start_time, self.end_time = None, None
self.width, self.height = None, None
self.fill = None # will be set to proper theme color on render
self.fixed = False
self.start_label = graphics.Label("", 11, "#333", visible = False)
self.end_label = graphics.Label("", 11, "#333", visible = False)
self.duration_label = graphics.Label("", 11, "#FFF", visible = False)
self.add_child(self.start_label, self.end_label, self.duration_label)
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if not self.fill: # not ready yet
return
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.fill_preserve(self.fill, 0.3)
self.graphics.stroke(self.fill)
# adjust labels
self.start_label.visible = self.start_time is not None and self.start_time != self.end_time
if self.start_label.visible:
self.start_label.text = self.start_time.strftime("%H:%M")
if self.x - self.start_label.width - 5 > 0:
self.start_label.x = -self.start_label.width - 5
else:
self.start_label.x = 5
self.start_label.y = self.height + 2
self.end_label.visible = self.end_time is not None and self.start_time != self.end_time
if self.end_label.visible:
self.end_label.text = self.end_time.strftime("%H:%M")
self.end_label.x = self.width + 5
self.end_label.y = self.height + 2
duration = self.end_time - self.start_time
duration = int(duration.seconds / 60)
self.duration_label.text = "%02d:%02d" % (duration / 60, duration % 60)
self.duration_label.visible = self.duration_label.width < self.width
if self.duration_label.visible:
self.duration_label.y = (self.height - self.duration_label.height) / 2
self.duration_label.x = (self.width - self.duration_label.width) / 2
else:
self.duration_label.visible = False
class DayLine(graphics.Scene):
def __init__(self, start_time = None):
graphics.Scene.__init__(self)
self.set_can_focus(False) # no interaction
self.day_start = conf.day_start
start_time = start_time or dt.datetime.now()
self.view_time = start_time or dt.datetime.combine(start_time.date(), self.day_start)
self.scope_hours = 24
self.fact_bars = []
self.categories = []
self.connect("on-enter-frame", self.on_enter_frame)
self.plot_area = graphics.Sprite(y=15)
self.chosen_selection = Selection()
self.plot_area.add_child(self.chosen_selection)
self.drag_start = None
self.current_x = None
self.date_label = graphics.Label(color=self._style.get_color(gtk.StateFlags.NORMAL),
x=5, y=16)
self.add_child(self.plot_area, self.date_label)
def plot(self, date, facts, select_start, select_end = None):
for bar in self.fact_bars:
self.plot_area.sprites.remove(bar)
self.fact_bars = []
for fact in facts:
fact_bar = graphics.Rectangle(0, 0, fill="#aaa", stroke="#aaa") # dimensions will depend on screen situation
fact_bar.fact = fact
if fact.category in self.categories:
fact_bar.category = self.categories.index(fact.category)
else:
fact_bar.category = len(self.categories)
self.categories.append(fact.category)
self.plot_area.add_child(fact_bar)
self.fact_bars.append(fact_bar)
self.view_time = dt.datetime.combine(date, self.day_start)
self.date_label.text = self.view_time.strftime("%b %d")
self.chosen_selection.start_time = select_start
self.chosen_selection.end_time = select_end
self.chosen_selection.width = None
self.chosen_selection.fixed = True
self.chosen_selection.visible = True
self.redraw()
def on_enter_frame(self, scene, context):
g = graphics.Graphics(context)
self.plot_area.height = self.height - 30
vertical = min(self.plot_area.height / 5, 7)
minute_pixel = (self.scope_hours * 60.0 - 15) / self.width
g.set_line_style(width=1)
g.translate(0.5, 0.5)
colors = {
"normal": self._style.get_color(gtk.StateFlags.NORMAL),
"normal_bg": self._style.get_background_color(gtk.StateFlags.NORMAL),
"selected": self._style.get_color(gtk.StateFlags.SELECTED),
"selected_bg": self._style.get_background_color(gtk.StateFlags.SELECTED),
}
bottom = self.plot_area.y + self.plot_area.height
for bar in self.fact_bars:
bar.y = vertical * bar.category + 5
bar.height = vertical
bar_start_time = bar.fact.start_time - self.view_time
minutes = bar_start_time.seconds / 60 + bar_start_time.days * self.scope_hours * 60
bar.x = round(minutes / minute_pixel) + 0.5
bar.width = round((bar.fact.delta).seconds / 60 / minute_pixel)
if self.chosen_selection.start_time and self.chosen_selection.width is None:
# we have time but no pixels
minutes = round((self.chosen_selection.start_time - self.view_time).seconds / 60 / minute_pixel) + 0.5
self.chosen_selection.x = minutes
if self.chosen_selection.end_time:
self.chosen_selection.width = round((self.chosen_selection.end_time - self.chosen_selection.start_time).seconds / 60 / minute_pixel)
else:
self.chosen_selection.width = 0
self.chosen_selection.height = self.chosen_selection.parent.height
# use the oportunity to set proper colors too
self.chosen_selection.fill = colors['selected_bg']
self.chosen_selection.duration_label.color = colors['selected']
#time scale
g.set_color("#000")
background = colors["normal_bg"]
text = colors["normal"]
tick_color = g.colors.contrast(background, 80)
layout = g.create_layout(size = 10)
for i in range(self.scope_hours * 60):
time = (self.view_time + dt.timedelta(minutes=i))
g.set_color(tick_color)
if time.minute == 0:
g.move_to(round(i / minute_pixel), bottom - 15)
g.line_to(round(i / minute_pixel), bottom)
g.stroke()
elif time.minute % 15 == 0:
g.move_to(round(i / minute_pixel), bottom - 5)
g.line_to(round(i / minute_pixel), bottom)
g.stroke()
if time.minute == 0 and time.hour % 4 == 0:
if time.hour == 0:
g.move_to(round(i / minute_pixel), self.plot_area.y)
g.line_to(round(i / minute_pixel), bottom)
label_minutes = time.strftime("%b %d")
else:
label_minutes = time.strftime("%H<small><sup>%M</sup></small>")
g.set_color(text)
layout.set_markup(label_minutes)
g.move_to(round(i / minute_pixel) + 2, 0)
pangocairo.show_layout(context, layout)
#current time
if self.view_time < dt.datetime.now() < self.view_time + dt.timedelta(hours = self.scope_hours):
minutes = round((dt.datetime.now() - self.view_time).seconds / 60 / minute_pixel)
g.rectangle(minutes, 0, self.width, self.height)
g.fill(colors['normal_bg'], 0.7)
g.move_to(minutes, self.plot_area.y)
g.line_to(minutes, bottom)
g.stroke("#f00", 0.4)
| 9,083 | Python | .py | 171 | 42.163743 | 148 | 0.616072 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,548 | dates.py | projecthamster_hamster/src/hamster/widgets/dates.py | # - coding: utf-8 -
# Copyright (C) 2008-2009, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
from gi.repository import Pango as pango
import calendar
import re
from hamster.lib import datetime as dt
from hamster.lib import stuff
from hamster.lib.configuration import load_ui_file
class Calendar():
"""Python date interface to a Gtk.Calendar.
widget (Gtk.Calendar):
the associated Gtk widget.
expander (Gtk.expander):
An optional expander which contains the widget.
The expander label displays the date.
"""
def __init__(self, widget, expander=None):
self.widget = widget
self.expander = expander
self.widget.connect("day-selected", self.on_date_changed)
@property
def date(self):
"""Selected day, as datetime.date."""
year, month, day = self.widget.get_date()
# months start at 0 in Gtk.Calendar and at 1 in python date
month += 1
return dt.date(year=year, month=month, day=day) if day else None
@date.setter
def date(self, value):
"""Set date.
value can be a python date or datetime.
"""
if value is None:
# unselect day
self.widget.select_day(0)
else:
year = value.year
# months start at 0 in Gtk.Calendar and at 1 in python date
month = value.month - 1
day = value.day
self.widget.select_month(month, year)
self.widget.select_day(day)
def on_date_changed(self, widget):
if self.expander:
if self.date:
self.expander.set_label(self.date.strftime("%A %Y-%m-%d"))
else:
self.expander.set_label("")
def __getattr__(self, name):
return getattr(self.widget, name)
class RangePick(gtk.MenuButton):
""" a text entry widget with calendar popup"""
__gsignals__ = {
# day|week|month|manual, start, end
'range-selected': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
}
def __init__(self, today):
gtk.ToggleButton.__init__(self)
self._ui = load_ui_file("date_range.ui")
popup = self.get_widget("range_popup")
popup.connect("show", self.on_show)
self.set_popover(popup)
self.today = today
hbox = gtk.HBox()
hbox.set_spacing(3)
self.label = gtk.Label()
hbox.add(self.label)
hbox.add(gtk.Arrow(gtk.ArrowType.DOWN, gtk.ShadowType.ETCHED_IN))
self.add(hbox)
self.start_date, self.end_date = None, None
self.current_range = None
self._ui.connect_signals(self)
def set_range(self, start_date, end_date=None):
end_date = end_date or start_date
self.start_date, self.end_date = start_date, end_date
self.label.set_markup('<b>%s</b>' % stuff.format_range(start_date, end_date))
def get_range(self):
return self.start_date, self.end_date
def emit_range(self, range, start, end):
self.set_range(start, end)
self.emit("range-selected", range, start, end)
self.set_active(False)
def prev_range(self):
start, end = self.start_date, self.end_date
if self.current_range == "day":
start, end = start - dt.timedelta(1), end - dt.timedelta(1)
elif self.current_range == "week":
start, end = start - dt.timedelta(7), end - dt.timedelta(7)
elif self.current_range == "month":
end = start - dt.timedelta(1)
first_weekday, days_in_month = calendar.monthrange(end.year, end.month)
start = end - dt.timedelta(days_in_month - 1)
else:
# manual range - just jump to the next window
days = (end - start) + dt.timedelta(days = 1)
start = start - days
end = end - days
self.emit_range(self.current_range, start, end)
def next_range(self):
start, end = self.start_date, self.end_date
if self.current_range == "day":
start, end = start + dt.timedelta(1), end + dt.timedelta(1)
elif self.current_range == "week":
start, end = start + dt.timedelta(7), end + dt.timedelta(7)
elif self.current_range == "month":
start = end + dt.timedelta(1)
first_weekday, days_in_month = calendar.monthrange(start.year, start.month)
end = start + dt.timedelta(days_in_month - 1)
else:
# manual range - just jump to the next window
days = (end - start) + dt.timedelta(days = 1)
start = start + days
end = end + days
self.emit_range(self.current_range, start, end)
def get_widget(self, name):
""" skip one variable (huh) """
return self._ui.get_object(name)
def on_show(self, user_data):
self.get_widget("day_preview").set_text(stuff.format_range(self.today, self.today))
self.get_widget("week_preview").set_text(stuff.format_range(*stuff.week(self.today)))
self.get_widget("month_preview").set_text(stuff.format_range(*stuff.month(self.today)))
start_cal = self.get_widget("start_calendar")
start_cal.select_month(self.start_date.month - 1, self.start_date.year)
start_cal.select_day(self.start_date.day)
end_cal = self.get_widget("end_calendar")
end_cal.select_month(self.end_date.month - 1, self.end_date.year)
end_cal.select_day(self.end_date.day)
self.get_widget("day").grab_focus()
def on_day_clicked(self, button):
self.current_range = "day"
self.emit_range("day", self.today, self.today)
def on_week_clicked(self, button):
self.current_range = "week"
self.start_date, self.end_date = stuff.week(self.today)
self.emit_range("week", self.start_date, self.end_date)
def on_month_clicked(self, button):
self.current_range = "month"
self.start_date, self.end_date = stuff.month(self.today)
self.emit_range("month", self.start_date, self.end_date)
def on_manual_range_apply_clicked(self, button):
self.current_range = "manual"
# GtkCalendar January is 0, hence the + 1
year, month, day = self.get_widget("start_calendar").get_date()
self.start_date = dt.date(year, month + 1, day)
year, month, day = self.get_widget("end_calendar").get_date()
self.end_date = dt.date(year, month + 1, day)
# make sure we always have a valid range
if self.end_date < self.start_date:
self.start_date, self.end_date = self.end_date, self.start_date
self.emit_range("manual", self.start_date, self.end_date)
| 7,559 | Python | .py | 163 | 38.01227 | 142 | 0.634123 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,549 | __init__.py | projecthamster_hamster/src/hamster/widgets/__init__.py | # - coding: utf-8 -
# Copyright (C) 2007-2009 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import Pango as pango
from hamster.lib import datetime as dt
# import our children
from hamster.widgets.activityentry import (
ActivityEntry,
CategoryEntry,
CmdLineEntry,
)
from hamster.widgets.timeinput import TimeInput
from hamster.widgets.dayline import DayLine
from hamster.widgets.tags import Tag, TagBox, TagsEntry
from hamster.widgets.reportchooserdialog import ReportChooserDialog
from hamster.widgets.facttree import FactTree
from hamster.widgets.dates import Calendar, RangePick
# handy wrappers
def add_hint(entry, hint):
entry.hint = hint
def override_get_text(self):
#override get text so it does not return true when hint is in!
if self.real_get_text() == self.hint:
return ""
else:
return self.real_get_text()
def _set_hint(self, widget, event):
if self.get_text(): # do not mess with user entered text
return
self.modify_text(gtk.StateType.NORMAL, gdk.Color.parse("gray")[1])
hint_font = pango.FontDescription(self.get_style().font_desc.to_string())
hint_font.set_style(pango.Style.ITALIC)
self.modify_font(hint_font)
self.set_text(self.hint)
def _set_normal(self, widget, event):
#self.modify_text(gtk.StateType.NORMAL, self.get_style().fg[gtk.StateType.NORMAL])
hint_font = pango.FontDescription(self.get_style().font_desc.to_string())
hint_font.set_style(pango.Style.NORMAL)
self.modify_font(hint_font)
if self.real_get_text() == self.hint:
self.set_text("")
def _on_changed(self, widget):
if self.real_get_text() == "" and self.is_focus() == False:
self._set_hint(widget, None)
import types
instancemethod = types.MethodType
entry._set_hint = instancemethod(_set_hint, entry, gtk.Entry)
entry._set_normal = instancemethod(_set_normal, entry, gtk.Entry)
entry._on_changed = instancemethod(_on_changed, entry, gtk.Entry)
entry.real_get_text = entry.get_text
entry.get_text = instancemethod(override_get_text, entry, gtk.Entry)
entry.connect('focus-in-event', entry._set_normal)
entry.connect('focus-out-event', entry._set_hint)
entry.connect('changed', entry._on_changed)
entry._set_hint(entry, None)
| 3,157 | Python | .py | 67 | 41.940299 | 90 | 0.71987 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,550 | timeinput.py | projecthamster_hamster/src/hamster/widgets/timeinput.py | # - coding: utf-8 -
# Copyright (C) 2008-2009 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import calendar
import re
from gi.repository import Gdk as gdk
from gi.repository import Gtk as gtk
from gi.repository import GObject as gobject
from hamster.lib import datetime as dt
from hamster.lib.stuff import hamster_round
class TimeInput(gtk.Entry):
__gsignals__ = {
'time-entered': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self, time=None, start_time=None, *, parent, **kwargs):
gtk.Entry.__init__(self, parent=parent, **kwargs)
self.news = False
self.set_width_chars(7) #7 is like 11:24pm
self.time = time
self.set_start_time(start_time)
self.popup = gtk.Window(type = gtk.WindowType.POPUP)
self.popup.set_type_hint(gdk.WindowTypeHint.COMBO) # why not
self.popup.set_attached_to(self) # attributes
self.popup.set_transient_for(self.get_ancestor(gtk.Window)) # position
time_box = gtk.ScrolledWindow()
time_box.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.ALWAYS)
time_box.set_shadow_type(gtk.ShadowType.IN)
self.time_tree = gtk.TreeView()
self.time_tree.set_headers_visible(False)
self.time_tree.set_hover_selection(True)
self.time_tree.append_column(gtk.TreeViewColumn("Time",
gtk.CellRendererText(),
text=0))
self.time_tree.connect("button-press-event",
self._on_time_tree_button_press_event)
time_box.add(self.time_tree)
self.popup.add(time_box)
self.set_icon_from_icon_name(gtk.EntryIconPosition.PRIMARY, "edit-clear-all-symbolic")
self.connect("icon-release", self._on_icon_release)
self.connect("button-press-event", self._on_button_press_event)
self.connect("key-press-event", self._on_key_press_event)
self.connect("focus-in-event", self._on_focus_in_event)
self.connect("focus-out-event", self._on_focus_out_event)
self._parent_click_watcher = None # bit lame but works
self.connect("changed", self._on_text_changed)
self.show()
self.connect("destroy", self.on_destroy)
@property
def time(self):
"""Displayed time.
None,
or time type,
or datetime if start_time() was given a datetime.
"""
time = self.figure_time(self.get_text())
if self.start_date and time:
# recombine (since self.start_time contains only the time part)
start = dt.datetime.combine(self.start_date, self.start_time)
new = dt.datetime.combine(self.start_date, time)
if new < start:
# a bit hackish, valid only because
# duration can not be negative if start_time was given,
# and we accept that it can not exceed 24h.
# For longer durations,
# date will have to be changed subsequently.
return new + dt.timedelta(days=1)
else:
return new
else:
return time
@time.setter
def time(self, value):
time = hamster_round(value)
self.set_text(self._format_time(time))
return time
def on_destroy(self, window):
self.popup.destroy()
self.popup = None
def set_start_time(self, start_time):
""" Set the start time.
When start time is set, drop down list will start from start time,
and duration will be displayed in brackets.
self.time will have the same type as start_time.
"""
start_time = hamster_round(start_time)
if isinstance(start_time, dt.datetime):
self.start_date = start_time.date()
# timeinput works on time only
start_time = start_time.time()
else:
self.start_date = None
self.start_time = start_time
def _on_text_changed(self, widget):
self.news = True
def figure_time(self, str_time):
if not str_time:
return None
# strip everything non-numeric and consider hours to be first number
# and minutes - second number
numbers = re.split("\D", str_time)
numbers = [x for x in numbers if x!=""]
hours, minutes = None, None
if len(numbers) == 1 and len(numbers[0]) == 4:
hours, minutes = int(numbers[0][:2]), int(numbers[0][2:])
else:
if len(numbers) >= 1:
hours = int(numbers[0])
if len(numbers) >= 2:
minutes = int(numbers[1])
if (hours is None or minutes is None) or hours > 24 or minutes > 60:
return None # no can do
return dt.time(hours, minutes)
def _select_time(self, time_text):
#convert forth and back so we have text formated as we want
time = self.figure_time(time_text)
time_text = self._format_time(time)
self.set_text(time_text)
self.set_position(len(time_text))
self.hide_popup()
if self.news:
self.emit("time-entered")
self.news = False
def _format_time(self, time):
if time is None:
return ""
return time.strftime("%H:%M").lower()
def _on_focus_in_event(self, entry, event):
self.show_popup()
def _on_button_press_event(self, button, event):
self.show_popup()
def _on_focus_out_event(self, event, something):
self.hide_popup()
if self.news:
self.emit("time-entered")
self.news = False
def _on_icon_release(self, entry, icon_pos, event):
self.grab_focus()
self.set_text("")
self.emit("changed")
def hide_popup(self):
if self._parent_click_watcher and self.get_toplevel().handler_is_connected(self._parent_click_watcher):
self.get_toplevel().disconnect(self._parent_click_watcher)
self._parent_click_watcher = None
self.popup.hide()
def show_popup(self):
if not self._parent_click_watcher:
self._parent_click_watcher = self.get_toplevel().connect("button-press-event", self._on_focus_out_event)
# we will be adding things, need datetime
i_time_0 = dt.datetime.combine(self.start_date or dt.date.today(),
self.start_time or dt.time())
if self.start_time is None:
# full 24 hours
i_time = i_time_0
interval = dt.timedelta(minutes = 15)
end_time = i_time_0 + dt.timedelta(days = 1)
else:
# from start time to start time + 12 hours
interval = dt.timedelta(minutes = 15)
i_time = i_time_0 + interval
end_time = i_time_0 + dt.timedelta(hours = 12)
time = self.figure_time(self.get_text())
focus_time = dt.datetime.combine(dt.date.today(), time) if time else None
hours = gtk.ListStore(str)
i, focus_row = 0, None
while i_time < end_time:
row_text = self._format_time(i_time)
if self.start_time is not None:
delta_text = (i_time - i_time_0).format()
row_text += " (%s)" % delta_text
hours.append([row_text])
if focus_time and i_time <= focus_time < i_time + interval:
focus_row = i
i_time += interval
i += 1
self.time_tree.set_model(hours)
#focus on row
if focus_row != None:
selection = self.time_tree.get_selection()
selection.select_path(focus_row)
self.time_tree.scroll_to_cell(focus_row, use_align = True, row_align = 0.4)
#move popup under the widget
alloc = self.get_allocation()
w = alloc.width
self.time_tree.set_size_request(w, alloc.height * 5)
window = self.get_parent_window()
dmmy, x, y= window.get_origin()
self.popup.move(x + alloc.x,y + alloc.y + alloc.height)
self.popup.resize(*self.time_tree.get_size_request())
self.popup.show_all()
def toggle_popup(self):
if self.popup.get_property("visible"):
self.hide_popup()
else:
self.show_popup()
def _on_time_tree_button_press_event(self, tree, event):
model, iter = tree.get_selection().get_selected()
time = model.get_value(iter, 0)
self._select_time(time)
def _on_key_press_event(self, entry, event):
if event.keyval not in (gdk.KEY_Up, gdk.KEY_Down, gdk.KEY_Return, gdk.KEY_KP_Enter):
#any kind of other input
self.hide_popup()
return False
model, iter = self.time_tree.get_selection().get_selected()
if not iter:
return
i = model.get_path(iter)[0]
if event.keyval == gdk.KEY_Up:
i-=1
elif event.keyval == gdk.KEY_Down:
i+=1
elif (event.keyval == gdk.KEY_Return or
event.keyval == gdk.KEY_KP_Enter):
if self.popup.get_property("visible"):
self._select_time(self.time_tree.get_model()[i][0])
else:
self._select_time(entry.get_text())
elif (event.keyval == gdk.KEY_Escape):
self.hide_popup()
return
# keep it in sane limits
i = min(max(i, 0), len(self.time_tree.get_model()) - 1)
self.time_tree.set_cursor(i)
self.time_tree.scroll_to_cell(i, use_align = True, row_align = 0.4)
# if popup is not visible, display it on up and down
if event.keyval in (gdk.KEY_Up, gdk.KEY_Down) and self.popup.props.visible == False:
self.show_popup()
return True
| 10,598 | Python | .py | 238 | 34.268908 | 116 | 0.598075 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,551 | reportchooserdialog.py | projecthamster_hamster/src/hamster/widgets/reportchooserdialog.py | # - coding: utf-8 -
# Copyright (C) 2009 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import os
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
from hamster.lib.configuration import conf
class ReportChooserDialog(gtk.Dialog):
__gsignals__ = {
# format, path, start_date, end_date
'report-chosen': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
(gobject.TYPE_STRING, gobject.TYPE_STRING)),
'report-chooser-closed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self):
gtk.Dialog.__init__(self)
self.dialog = gtk.FileChooserDialog(title = _("Save Report — Time Tracker"),
parent = self,
action = gtk.FileChooserAction.SAVE,
buttons=(gtk.STOCK_CANCEL,
gtk.ResponseType.CANCEL,
gtk.STOCK_SAVE,
gtk.ResponseType.OK))
# try to set path to last known folder or fall back to home
report_folder = os.path.expanduser(conf.get("last-report-folder"))
if os.path.exists(report_folder):
self.dialog.set_current_folder(report_folder)
else:
self.dialog.set_current_folder(os.path.expanduser("~"))
self.filters = {}
filter = gtk.FileFilter()
filter.set_name(_("HTML Report"))
filter.add_mime_type("text/html")
filter.add_pattern("*.html")
filter.add_pattern("*.htm")
self.filters[filter] = "html"
self.dialog.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name(_("Tab-Separated Values (TSV)"))
filter.add_mime_type("text/plain")
filter.add_pattern("*.tsv")
filter.add_pattern("*.txt")
self.filters[filter] = "tsv"
self.dialog.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name(_("XML"))
filter.add_mime_type("text/xml")
filter.add_pattern("*.xml")
self.filters[filter] = "xml"
self.dialog.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name(_("iCal"))
filter.add_mime_type("text/calendar")
filter.add_pattern("*.ics")
self.filters[filter] = "ical"
self.dialog.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
self.dialog.add_filter(filter)
def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", "."),
"end": end_date.strftime("%x").replace("/", ".")}
if start_date != end_date:
filename = "%(title)s, %(start)s - %(end)s.html" % vars
else:
filename = "%(title)s, %(start)s.html" % vars
self.dialog.set_current_name(filename)
response = self.dialog.run()
if response != gtk.ResponseType.OK:
self.emit("report-chooser-closed")
self.dialog.destroy()
self.dialog = None
else:
self.on_save_button_clicked()
def present(self):
self.dialog.present()
def on_save_button_clicked(self):
path, format = None, None
format = "html"
if self.dialog.get_filter() in self.filters:
format = self.filters[self.dialog.get_filter()]
path = self.dialog.get_filename()
# append correct extension if it is missing
# TODO - proper way would be to change extension on filter change
# only pointer in web is http://www.mail-archive.com/pygtk@daa.com.au/msg08740.html
if path.endswith(".%s" % format) == False:
path = "%s.%s" % (path.rstrip("."), format)
categories = []
conf.set("last-report-folder", os.path.dirname(path))
# format, path, start_date, end_date
self.emit("report-chosen", format, path)
self.dialog.destroy()
self.dialog = None
| 5,060 | Python | .py | 108 | 36.12963 | 91 | 0.595567 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,552 | configuration.py | projecthamster_hamster/src/hamster/lib/configuration.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
"""
License: GPLv2
"""
import logging
logger = logging.getLogger(__name__) # noqa: E402
import os
from hamster.client import Storage
from gi.repository import Gdk as gdk
from gi.repository import Gio as gio
from gi.repository import GLib as glib
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
import hamster
from hamster.lib import datetime as dt
class Controller(gobject.GObject):
"""Window creator and handler."""
__gsignals__ = {
"on-close": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self, ui_file=""):
gobject.GObject.__init__(self)
if ui_file:
self._gui = load_ui_file(ui_file)
self.window = self.get_widget('window')
else:
self._gui = None
self.window = gtk.Window()
self.window.connect("delete-event", self.window_delete_event)
if self._gui:
self._gui.connect_signals(self)
def get_widget(self, name):
""" skip one variable (huh) """
return self._gui.get_object(name)
def window_delete_event(self, widget, event):
self.close_window()
def close_window(self):
# Do not try to just hide;
# dialogs are populated upon instanciation anyway
self.window.destroy()
self.window = None
self.emit("on-close")
def present(self):
"""Show window and bring it to the foreground."""
# workaround https://gitlab.gnome.org/GNOME/gtk/issues/624
# fixed in gtk-3.24.1 (2018-09-19)
# self.overview_controller.window.present()
self.window.present_with_time(glib.get_monotonic_time() / 1000)
def show(self):
"""Show window.
It might be obscurd by others though.
See also: presents
"""
self.window.show()
def __bool__(self):
return True if self.window else False
def load_ui_file(name):
"""loads interface from the glade file; sorts out the path business"""
ui = gtk.Builder()
ui.add_from_file(os.path.join(runtime.data_dir, name))
return ui
class Singleton(object):
def __new__(cls, *args, **kwargs):
if '__instance' not in vars(cls):
cls.__instance = object.__new__(cls, *args, **kwargs)
return cls.__instance
class RuntimeStore(Singleton):
"""XXX - kill"""
data_dir = ""
home_data_dir = ""
storage = None
def __init__(self):
self.version = hamster.__version__
if hamster.installed:
from hamster import defs # only available when running installed
self.data_dir = os.path.join(defs.DATA_DIR, "hamster")
else:
# running from sources
module_dir = os.path.dirname(os.path.realpath(__file__))
self.data_dir = os.path.join(module_dir, '..', '..', '..', 'data')
self.data_dir = os.path.realpath(self.data_dir)
self.storage = Storage()
self.home_data_dir = os.path.realpath(os.path.join(glib.get_user_data_dir(), "hamster"))
runtime = RuntimeStore()
class GSettingsStore(gobject.GObject, Singleton):
"""
Settings implementation which stores settings in GSettings
Snatched from the conduit project (http://live.gnome.org/Conduit)
"""
__gsignals__ = {
"changed": (gobject.SignalFlags.RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT))
}
def __init__(self):
gobject.GObject.__init__(self)
self._settings = gio.Settings(schema_id='org.gnome.Hamster')
def _key_changed(self, client, key, data=None):
"""
Callback when a GSettings key changes
"""
value = self._settings.get_value(key)
self.emit('changed', key, value)
def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in GSettings
"""
value = self._settings.get_value(key)
if value is None:
logger.warn("Unknown GSettings key: %s" % key)
return value.unpack()
def set(self, key, value):
"""
Sets the key value in GSettings and connects adds a signal
which is fired if the key changes
"""
logger.debug("Settings %s -> %s" % (key, value))
default = self._settings.get_default_value(key)
assert default is not None
self._settings.set_value(key, glib.Variant(default.get_type().dup_string(), value))
return True
def bind(self, key, obj, prop):
self._settings.bind(key, obj, prop, gio.SettingsBindFlags.DEFAULT)
@property
def day_start(self):
"""Start of the hamster day."""
day_start_minutes = self.get("day-start-minutes")
hours, minutes = divmod(day_start_minutes, 60)
return dt.time(hours, minutes)
conf = GSettingsStore()
| 5,681 | Python | .py | 141 | 33.510638 | 116 | 0.646534 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,553 | fact.py | projecthamster_hamster/src/hamster/lib/fact.py | # This file is part of Hamster
# Copyright (c) The Hamster time tracker developers
# SPDX-License-Identifier: GPL-3.0-or-later
"""Fact definition."""
import logging
logger = logging.getLogger(__name__) # noqa: E402
import calendar
from copy import deepcopy
from hamster.lib import datetime as dt
from hamster.lib.parsing import parse_fact, get_tags_from_description
class FactError(Exception):
"""Generic Fact error."""
class Fact(object):
def __init__(self, activity="", category=None, description=None, tags=None,
range=None, start=None, end=None, start_time=None, end_time=None,
id=None, activity_id=None):
"""Homogeneous chunk of activity.
The category, description and tags must be passed explicitly.
To provide the whole fact information as a single string,
please use Fact.parse(string).
range (dt.Range): time spanned by the fact. For convenience,
the `start` and `end` arguments can be given instead.
start (dt.datetime); Start of the fact range.
Mutually exclusive with `range`.
end (dt.datetime); End of the fact range.
Mutually exclusive with `range`.
start_time (dt.datetime): Deprecated. Same as start.
end_time (dt.datetime): Deprecated. Same as end.
id (int): id in the database.
Should be used with extreme caution, knowing exactly why.
(only for very specific direct database read/write)
"""
self.activity = activity
self.category = category
self.description = description
self.tags = tags or []
if range:
assert not start, "range already given"
assert not end, "range already given"
assert not start_time, "range already given"
assert not end_time, "range already given"
self.range = range
else:
if start_time:
assert not start, "use only start, not start_time"
start = start_time
if end_time:
assert not end, "use only end, not end_time"
end = end_time
self.range = dt.Range(start, end)
self.id = id
self.activity_id = activity_id
# TODO: might need some cleanup
def as_dict(self):
date = self.date
return {
'id': int(self.id) if self.id else "",
'activity': self.activity,
'category': self.category,
'description': self.description,
'tags': [tag.strip() for tag in self.tags],
'date': calendar.timegm(date.timetuple()) if date else "",
'start_time': self.range.start if isinstance(self.range.start, str) else calendar.timegm(self.range.start.timetuple()),
'end_time': self.range.end if isinstance(self.range.end, str) else calendar.timegm(self.range.end.timetuple()) if self.range.end else "",
'delta': self.delta.total_seconds() # ugly, but needed for report.py
}
@property
def activity(self):
"""Activity name."""
return self._activity
@activity.setter
def activity(self, value):
self._activity = value.strip() if value else ""
@property
def category(self):
return self._category
@category.setter
def category(self, value):
self._category = value.strip() if value else ""
def copy(self, **kwds):
"""Return an independent copy, with overrides as keyword arguments.
By default, only copy user-visible attributes.
To also copy the id, use fact.copy(id=fact.id)
"""
fact = deepcopy(self)
fact._set(**kwds)
return fact
@property
def date(self):
"""hamster day, determined from start_time.
Note: Setting date is a one-shot modification of
the start_time and end_time (if defined),
to match the given value.
Any subsequent modification of start_time
can result in different self.date.
"""
return self.range.start.hday() if self.range.start else None
@date.setter
def date(self, value):
if self.range.start:
previous_start_time = self.range.start
self.range.start = dt.datetime.from_day_time(value, self.range.start.time())
if self.range.end:
# start_time date prevails.
# Shift end_time to preserve the fact duration.
self.range.end += self.range.start - previous_start_time
elif self.range.end:
self.range.end = dt.datetime.from_day_time(value, self.range.end.time())
@property
def delta(self):
"""Duration (datetime.timedelta)."""
end_time = self.range.end if self.range.end else dt.datetime.now()
return end_time - self.range.start
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value.strip() if value else ""
@property
def end_time(self):
"""Fact range end.
Deprecated, use self.range.end instead.
"""
return self.range.end
@end_time.setter
def end_time(self, value):
self.range.end = value
@property
def start_time(self):
"""Fact range start.
Deprecated, use self.range.start instead.
"""
return self.range.start
@start_time.setter
def start_time(self, value):
self.range.start = value
@classmethod
def parse(cls, string, range_pos="head", default_day=None, ref="now"):
fact = Fact()
for key, val in parse_fact(string, range_pos=range_pos,
default_day=default_day, ref=ref).items():
setattr(fact, key, val)
return fact
def serialized_name(self):
res = self.activity
if self.category:
res += "@%s" % self.category
if self.description:
res += ', '
res += self.description
if self.tags:
# Don't duplicate tags that are already in the description
seen_tags = get_tags_from_description(self.description)
remaining_tags = [
tag for tag in self.tags if tag not in seen_tags
]
if remaining_tags:
res += ", %s" % " ".join("#%s" % tag for tag in remaining_tags)
return res
def serialized(self, range_pos="head", default_day=None):
"""Return a string fully representing the fact."""
name = self.serialized_name()
if range_pos == "head":
# Is activity starting range-like ?
subfact = Fact.parse(self.activity, range_pos=range_pos,
default_day=default_day)
need_explicit = bool(subfact.range)
else:
# TODO: should check last tag.
need_explicit = False
datetime = self.range.format(default_day=default_day,
explicit_none=need_explicit)
# no need for space if name or datetime is missing
space = " " if name and datetime else ""
assert range_pos in ("head", "tail")
if range_pos == "head":
return "{}{}{}".format(datetime, space, name)
else:
return "{}{}{}".format(name, space, datetime)
def _set(self, **kwds):
"""Modify attributes.
Private, used only in copy. It is more readable to be explicit, e.g.:
fact.range.start = ...
fact.range.end = ...
"""
for attr, value in kwds.items():
if not hasattr(self, attr):
raise AttributeError("'{attr}' not found".format(attr=attr))
else:
setattr(self, attr, value)
def __eq__(self, other):
return (isinstance(other, Fact)
and self.activity == other.activity
and self.category == other.category
and self.description == other.description
and self.range.end == other.range.end
and self.range.start == other.range.start
and self.tags == other.tags
)
def __repr__(self):
return self.serialized(default_day=None)
| 8,453 | Python | .py | 202 | 31.371287 | 149 | 0.587741 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,554 | datetime.py | projecthamster_hamster/src/hamster/lib/datetime.py | # This file is part of Hamster
# Copyright (c) The Hamster time tracker developers
# SPDX-License-Identifier: GPL-3.0-or-later
"""Hamster datetime.
Python datetime replacement, tuned for hamster use.
"""
import logging
logger = logging.getLogger(__name__) # noqa: E402
import datetime as pdt # standard datetime
import re
from collections import namedtuple
from textwrap import dedent
from functools import lru_cache
class datetime: # predeclaration for return type annotations
pass
class time: # predeclaration for return type annotations
pass
class date(pdt.date):
"""Hamster date.
Should replace the python datetime.date in any customer code.
Same as python date, with the addition of parse methods.
"""
FMT = "%Y-%m-%d" # ISO format
def __new__(cls, year, month, day):
return pdt.date.__new__(cls, year, month, day)
def __add__(self, other):
# python date.__add__ was not type stable prior to 3.8
return self.from_pdt(self.to_pdt() + other)
__radd__ = __add__
def __sub__(self, other):
# python date.__sub__ was not type stable prior to 3.8
if isinstance(other, pdt.timedelta):
return self.from_pdt(self.to_pdt() - other)
elif isinstance(other, pdt.date):
return timedelta.from_pdt(self.to_pdt() - other)
else:
return NotImplemented
@classmethod
def parse(cls, s):
"""Return date from string."""
m = cls.re.search(s)
return cls(year=int(m.group('year')),
month=int(m.group('month')),
day=int(m.group('day'))
)
@classmethod
def pattern(cls, detailed=True):
if detailed:
return dedent(r"""
(?P<year>\d{4}) # 4 digits
- # dash
(?P<month>\d{2}) # 2 digits
- # dash
(?P<day>\d{2}) # 2 digits
""")
else:
return r"""\d{4}-\d{2}-\d{2}"""
@classmethod
def from_pdt(cls, d):
"""Convert python date to hamster date."""
return cls(d.year, d.month, d.day)
def to_pdt(self):
"""Convert to python date."""
return pdt.date(self.year, self.month, self.day)
# For datetime that will need to be outside the class.
# Same here for consistency
date.re = re.compile(date.pattern(), flags=re.VERBOSE)
class hday(date):
"""Hamster day.
Same as date, but taking into account day-start.
A day starts at conf.day_start and ends when the next day starts.
"""
def __new__(cls, year, month, day):
return date.__new__(cls, year, month, day)
@property
def end(self) -> datetime:
"""Day end."""
return datetime.from_day_time(self + timedelta(days=1), self.start_time())
@property
def start(self) -> datetime:
"""Day start."""
return datetime.from_day_time(self, self.start_time())
@classmethod
def start_time(cls) -> time:
"""Day start time."""
# work around cyclic imports
from hamster.lib.configuration import conf
return conf.day_start
@classmethod
def today(cls):
"""Return the current hamster day."""
return datetime.now().hday()
class time(pdt.time):
"""Hamster time.
Should replace the python datetime.time in any customer code.
Specificities:
- rounded to minutes
- conversion to and from string facilities
"""
FMT = "%H:%M" # display format, e.g. 13:30
def __new__(cls,
hour=0, minute=0,
second=0, microsecond=0,
tzinfo=None, **kwargs):
# round down to zero seconds and microseconds
return pdt.time.__new__(cls,
hour=hour, minute=minute,
second=0, microsecond=0,
tzinfo=None, **kwargs)
@classmethod
def _extract_time(cls, match, h="hour", m="minute"):
"""Extract time from a time.re match.
Custom group names allow to use the same method
for two times in the same regexp (e.g. for range parsing)
h (str): name of the group containing the hour
m (str): name of the group containing the minute
seealso: time.parse
"""
h_str = match.group(h)
m_str = match.group(m)
if h_str and m_str:
hour = int(h_str)
minute = int(m_str)
return cls(hour, minute)
else:
return None
@classmethod
def parse(cls, s):
"""Parse time from string."""
m = cls.re.search(s)
return cls._extract_time(m) if m else None
# For datetime that must be a method.
# Same here for consistency.
@classmethod
def pattern(cls):
"""Return a time pattern with all group names."""
# remove the indentation for easier debugging.
return dedent(r"""
(?P<hour> # hour
[0-9](?=[,\.:]) # positive lookahead:
# allow a single digit only if
# followed by a colon, dot or comma
| [0-1][0-9] # 00 to 19
| [2][0-3] # 20 to 23
)
[,\.:]? # Separator can be colon,
# dot, comma, or nothing.
(?P<minute>[0-5][0-9]) # minute (2 digits, between 00 and 59)
(?!\d?-\d{2}-\d{2}) # Negative lookahead:
# avoid matching date by inadvertance.
# For instance 2019-12-05
# might be caught as 2:01.
# Requiring space or - would not work:
# 2019-2025 is the 20:19-20:25 range.
""")
# For datetime that will need to be outside the class.
# Same here for consistency
time.re = re.compile(time.pattern(), flags=re.VERBOSE)
class datetime(pdt.datetime):
"""Hamster datetime.
Should replace the python datetime.datetime in any customer code.
Specificities:
- rounded to minutes
- conversion to and from string facilities
"""
# display format, e.g. 2020-01-20 20:40
FMT = "{} {}".format(date.FMT, time.FMT)
def __new__(cls, year, month, day,
hour=0, minute=0,
second=0, microsecond=0,
tzinfo=None, **kwargs):
# round down to zero seconds and microseconds
return pdt.datetime.__new__(cls, year, month, day,
hour=hour, minute=minute,
second=0, microsecond=0,
tzinfo=None, **kwargs)
def __add__(self, other):
# python datetime.__add__ was not type stable prior to 3.8
return datetime.from_pdt(self.to_pdt() + other)
# similar to https://stackoverflow.com/q/51966126/3565696
# __getnewargs_ex__ did not work, brute force required
def __deepcopy__(self, memo):
kwargs = {}
if (hasattr(self, 'fold')):
kwargs['fold'] = self.fold
return datetime(self.year, self.month, self.day,
self.hour, self.minute,
self.second, self.microsecond,
self.tzinfo, **kwargs)
__radd__ = __add__
def __sub__(self, other):
# python datetime.__sub__ was not type stable prior to 3.8
if isinstance(other, timedelta):
return datetime.from_pdt(self.to_pdt() - other)
elif isinstance(other, datetime):
return timedelta.from_pdt(self.to_pdt() - other)
else:
return NotImplemented
def __str__(self):
if self.tzinfo:
raise NotImplementedError("Stay tuned...")
else:
return self.strftime(self.FMT)
@classmethod
def _extract_datetime(cls, match, d="date", h="hour", m="minute", r="relative",
default_day=None):
"""extract datetime from a datetime.pattern match.
Custom group names allow to use the same method
for two datetimes in the same regexp (e.g. for range parsing)
h (str): name of the group containing the hour
m (str): name of the group containing the minute
r (str): name of the group containing the relative time
default_day (dt.date): the datetime will belong to this hamster day if
date is missing.
"""
_time = time._extract_time(match, h, m)
if _time:
date_str = match.group(d)
if date_str:
_date = date.parse(date_str)
return datetime.combine(_date, _time)
else:
return datetime.from_day_time(default_day, _time)
else:
relative_str = match.group(r)
if relative_str and relative_str != "--":
return timedelta(minutes=int(relative_str))
else:
return None
# not a property, to match other extractions such as .date() or .time()
def hday(self) -> hday:
"""Return the day belonged to.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
_day = hday(self.year, self.month, self.day)
if self.time() < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
_day -= timedelta(days=1)
# return only the date
return _day
@classmethod
def from_day_time(cls, d: hday, t: time):
"""Return a datetime with time t belonging to day.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if t < conf.day_start:
# early morning, between midnight and day_start
# => the hamster day is the previous civil day
civil_date = d + timedelta(days=1)
else:
civil_date = d
return cls.combine(civil_date, t)
# Note: fromisoformat appears in python3.7
@classmethod
def from_pdt(cls, t):
"""Convert python datetime to hamster datetime."""
kwargs = {}
if (hasattr(t, 'fold')):
kwargs['fold'] = t.fold
return cls(t.year, t.month, t.day,
t.hour, t.minute,
t.second, t.microsecond,
t.tzinfo, **kwargs)
@classmethod
def now(cls):
"""Current datetime."""
return cls.from_pdt(pdt.datetime.now())
@classmethod
def parse(cls, s, default_day=None):
"""Parse a datetime from text.
default_day (dt.date):
If start is given without any date (e.g. just hh:mm),
put the corresponding datetime in default_day.
Defaults to today.
"""
# datetime.re is added below, after the class definition
# it will be found at runtime
m = datetime.re.search(s)
return cls._extract_datetime(m, default_day=default_day) if m else None
@classmethod
@lru_cache()
def pattern(cls, n=None):
"""Return a datetime pattern with all group names.
If n is given, all groups are suffixed with str(n).
"""
# remove the indentation => easier debugging.
base_pattern = dedent(r"""
(?P<whole>
# note: need to double the brackets
# for .format
(?<!\d{{2}}) # negative lookbehind,
# avoid matching 2019-12 or 2019-12-05
(?P<relative>
-- # double dash: None
| # or
[-+] # minus or plus: relative to ref
\d{{1,3}} # 1, 2 or 3 digits
)
| # or
(?P<date>{})? # maybe date
\s? # maybe one space
{} # time
)
""").format(date.pattern(), time.pattern())
if n is None:
return base_pattern
else:
to_replace = ("whole", "relative",
"year", "month", "day", "date", "tens", "hour", "minute")
specifics = ["{}{}".format(s, n) for s in to_replace]
res = base_pattern
for src, dest in zip(to_replace, specifics):
res = res.replace(src, dest)
return res
def to_pdt(self):
"""Convert to python datetime."""
kwargs = {}
if (hasattr(self, 'fold')):
kwargs['fold'] = self.fold
return pdt.datetime(self.year, self.month, self.day,
self.hour, self.minute,
self.second, self.microsecond,
self.tzinfo, **kwargs)
# outside class; need the class to be defined first
datetime.re = re.compile(datetime.pattern(), flags=re.VERBOSE)
class Range():
"""Time span between two datetimes."""
# slight memory optimization; no further attributes besides start or end.
__slots__ = ('start', 'end')
def __init__(self, start=None, end=None):
self.start = start
self.end = end
def __bool__(self):
return not (self.start is None and self.end is None)
def __eq__(self, other):
if isinstance(other, Range):
return self.start == other.start and self.end == other.end
else:
return False
# allow start, end = range
def __iter__(self):
return (self.start, self.end).__iter__()
def format(self, default_day=None, explicit_none=True):
"""Return a string representing the time range.
Start date is shown only if start does not belong to default_day.
End date is shown only if end does not belong to
the same hamster day as start (or to default_day if start is None).
"""
none_str = "--" if explicit_none else ""
if self.start:
if self.start.hday() != default_day:
start_str = self.start.strftime(datetime.FMT)
else:
start_str = self.start.strftime(time.FMT)
default_end_day = self.start.hday()
else:
start_str = none_str
default_end_day = default_day
if self.end:
if self.end.hday() != default_end_day:
end_str = self.end.strftime(datetime.FMT)
else:
end_str = self.end.strftime(time.FMT)
else:
end_str = none_str
if end_str:
return "{} - {}".format(start_str, end_str)
else:
return start_str
@classmethod
def parse(cls, text,
position="exact", separator="\s+", default_day=None, ref="now"):
"""Parse a start-end range from text.
position (str): "exact" to match exactly the full text
"head" to search only at the beginning of text, and
"tail" to search only at the end.
separator (str): regexp pattern (e.g. '\s+') meant to separate the datetime
from the rest. Discarded for "exact" position.
default_day (date): If start is given without any date (e.g. just hh:mm),
put the corresponding datetime in default_day.
Defaults to today.
Note: the default end day is always the start day, so
"2019-11-27 23:50 - 00:20" lasts 30 minutes.
ref (datetime): reference for relative times
(e.g. -15: quarter hour before ref).
For testing purposes only
(note: this will be removed later on,
and replaced with datetime.now mocking in pytest).
For users, it should be "now".
Return:
(range, rest)
range (Range): Range(None, None) if no match is found.
rest (str): remainder of the text.
"""
if ref == "now":
ref = datetime.now()
if default_day is None:
default_day = hday.today()
assert position in ("exact", "head", "tail"), "position unknown: '{}'".format(position)
if position == "exact":
p = "^{}$".format(cls.pattern())
elif position == "head":
# ( )?: require either only the range (no rest),
# or separator between range and rest,
# to avoid matching 10.00@cat
# .*? so rest is as little as possible
p = "^{}( {}(?P<rest>.*?) )?$".format(cls.pattern(), separator)
elif position == "tail":
p = "^( (?P<rest>.*?){} )? {}$".format(separator, cls.pattern())
# No need to compile, recent patterns are cached by re.
# DOTALL, so rest may contain newlines
# (important for multiline descriptions)
m = re.search(p, text, flags=re.VERBOSE | re.DOTALL)
if not m:
return Range(None, None), text
elif position == "exact":
rest = ""
else:
rest = m.group("rest") or ""
if m.group('firstday'):
# only day given for start
firstday = hday.parse(m.group('firstday'))
start = firstday.start
else:
firstday = None
start = datetime._extract_datetime(m, d="date1", h="hour1",
m="minute1", r="relative1",
default_day=default_day)
if isinstance(start, pdt.timedelta):
# relative to ref, actually
assert ref, "relative start needs ref"
start = ref + start
if m.group('lastday'):
lastday = hday.parse(m.group('lastday'))
end = lastday.end
elif firstday:
end = firstday.end
elif m.group('duration'):
duration = int(m.group('duration'))
end = start + timedelta(minutes=duration)
else:
end_default_day = start.hday() if start else default_day
end = datetime._extract_datetime(m, d="date2", h="hour2",
m="minute2", r="relative2",
default_day=end_default_day)
if isinstance(end, pdt.timedelta):
# relative to ref, actually
assert ref, "relative end needs ref"
end = ref + end
return Range(start, end), rest
@classmethod
@lru_cache()
def pattern(cls):
return dedent(r"""
( # start
{} # datetime: relative1 or (date1, hour1, and minute1)
| # or
(?P<firstday>{}) # date without time
)
(
(?P<separation> # (only needed if end time is given)
\s? # maybe one space
- # dash
\s? # maybe one space
| # or
\s # one space exactly
)
( # end
{} # datetime: relative2 or (date2, hour2, and minute2)
| # or
(?P<lastday>{}) # date without time
|
(?P<duration>
(?<![+-]) # negative lookbehind: no sign
\d{{1,3}} # 1, 2 or 3 digits
)
)
)? # end time is facultative
""".format(datetime.pattern(1), date.pattern(detailed=False),
datetime.pattern(2), date.pattern(detailed=False)))
@classmethod
def from_start_end(cls, start, end=None):
"""Return a Range from separate arguments.
Convenient to ease backward compatibility,
and to handle either hdays or datetimes.
"""
if isinstance(start, Range):
assert end is None, "end cannot be passed together with a Range"
return cls(start.start, start.end)
elif (start is None) or isinstance(start, datetime):
# This one must come first,
# because inheritance order is datetime < pdt.datetime < pdt.date.
pass
elif isinstance(start, hday):
# Idem, beware of the inheritance order;
# hday < date < pdt.date.
day = start
start = day.start
if end is None:
end = day.end
elif isinstance(start, pdt.date):
# transition from legacy
start = hday.from_pdt(start).start
else:
raise TypeError(
"\n First argument should be either Range, None, datetime or hday;"
"\n received {}".format(type(start))
)
if (end is None) or isinstance(end, datetime):
# same as above
pass
elif isinstance(end, hday):
end = end.end
elif isinstance(end, pdt.date):
# transition from legacy
end = hday.from_pdt(end).end
else:
raise TypeError(
"\n Second argument should be either None, datetime or hday;"
"\n received {}".format(type(start)))
return cls(start, end)
@classmethod
def today(cls):
_today = hday.today()
return cls(_today.start, _today.end)
class timedelta(pdt.timedelta):
"""Hamster timedelta.
Should replace the python datetime.timedelta in any customer code.
Specificities:
- conversion to and from string facilities
Note: granularity is the same as the original python timedelta
(only datetimes should be truncated).
"""
def __new__(cls, days=0, seconds=0, microseconds=0,
milliseconds=0, minutes=0, hours=0, weeks=0):
# Tempted to round down ? Resist. Not so useful + issues down the line.
return pdt.timedelta.__new__(cls,
days=days,
seconds=seconds,
microseconds=microseconds,
milliseconds=milliseconds,
minutes=minutes,
hours=hours,
weeks=weeks)
# timedelta subclassing is not type stable yet
def __add__(self, other):
return timedelta.from_pdt(self.to_pdt() + other)
__radd__ = __add__
def __sub__(self, other):
return timedelta.from_pdt(self.to_pdt() - other)
def __neg__(self):
return timedelta.from_pdt(-self.to_pdt())
@classmethod
def from_pdt(cls, delta):
"""Convert python timedelta to hamster timedelta."""
# Only days, seconds and microseconds are stored internally
return cls(days=delta.days,
seconds=delta.seconds,
microseconds=delta.microseconds)
def to_pdt(self):
"""Convert to python timedelta."""
return pdt.timedelta(days=self.days,
seconds=self.seconds,
microseconds=self.microseconds)
def format(self, fmt="human"):
"""Return a string representation, according to the format string fmt."""
allowed = ("human", "HH:MM")
# TODO: should use total_minutes
total_s = self.total_seconds()
if total_s < 0:
# return a warning
return "NEGATIVE"
hours = int(total_s // 3600)
minutes = int((total_s - 3600 * hours) // 60)
if fmt == "human":
if minutes % 60 == 0:
# duration in round hours
return "{}h".format(hours)
elif hours == 0:
# duration less than one hour
return "{}min".format(minutes)
else:
# x hours, y minutes
return "{}h {}min".format(hours, minutes)
elif fmt == "HH:MM":
return "{:02d}:{:02d}".format(hours, minutes)
else:
raise NotImplementedError(
"'{}' not in allowed formats: {}".format(fmt, allowed))
def total_minutes(self):
"""Return the duration in minutes (float)."""
return self.total_seconds() / 60
| 25,503 | Python | .py | 597 | 30.276382 | 95 | 0.517052 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,555 | pytweener.py | projecthamster_hamster/src/hamster/lib/pytweener.py | # pyTweener
#
# Tweening functions for python
#
# Heavily based on caurina Tweener: http://code.google.com/p/tweener/
#
# Released under M.I.T License - see above url
# Python version by Ben Harling 2009
# All kinds of slashing and dashing by Toms Baugis 2010, 2014
import math
import collections
import time
import re
from hamster.lib import datetime as dt
class Tweener(object):
def __init__(self, default_duration = None, tween = None):
"""Tweener
This class manages all active tweens, and provides a factory for
creating and spawning tween motions."""
self.current_tweens = collections.defaultdict(set)
self.default_easing = tween or Easing.Cubic.ease_in_out
self.default_duration = default_duration or 1.0
def has_tweens(self):
return len(self.current_tweens) > 0
def add_tween(self, obj, duration = None, easing = None, on_complete = None,
on_update = None, round = False, delay = None, **kwargs):
"""
Add tween for the object to go from current values to set ones.
Example: add_tween(sprite, x = 500, y = 200, duration = 0.4)
This will move the sprite to coordinates (500, 200) in 0.4 seconds.
For parameter "easing" you can use one of the pytweener.Easing
functions, or specify your own.
The tweener can handle numbers, dates and color strings in hex ("#ffffff").
This function performs overwrite style conflict solving - in case
if a previous tween operates on same attributes, the attributes in
question are removed from that tween.
"""
if duration is None:
duration = self.default_duration
easing = easing or self.default_easing
tw = Tween(obj, duration, delay, easing, on_complete, on_update, round, **kwargs )
if obj in self.current_tweens:
for current_tween in tuple(self.current_tweens[obj]):
prev_keys = set((key for (key, tweenable) in current_tween.tweenables))
dif = prev_keys & set(kwargs.keys())
for key, tweenable in tuple(current_tween.tweenables):
if key in dif:
current_tween.tweenables.remove((key, tweenable))
if not current_tween.tweenables:
current_tween.finish()
self.current_tweens[obj].remove(current_tween)
self.current_tweens[obj].add(tw)
return tw
def get_tweens(self, obj):
"""Get a list of all tweens acting on the specified object
Useful for manipulating tweens on the fly"""
return self.current_tweens.get(obj, None)
def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
if obj is not None:
try:
del self.current_tweens[obj]
except:
pass
else:
self.current_tweens = collections.defaultdict(set)
def remove_tween(self, tween):
""""remove given tween without completing the motion or firing the on_complete"""
if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]:
self.current_tweens[tween.target].remove(tween)
if not self.current_tweens[tween.target]:
del self.current_tweens[tween.target]
def finish(self):
"""jump the the last frame of all tweens"""
for obj in self.current_tweens:
for tween in self.current_tweens[obj]:
tween.finish()
self.current_tweens = {}
def update(self, delta_seconds):
"""update tweeners. delta_seconds is time in seconds since last frame"""
for obj in tuple(self.current_tweens):
for tween in tuple(self.current_tweens[obj]):
done = tween.update(delta_seconds)
if done:
self.current_tweens[obj].remove(tween)
if tween.on_complete: tween.on_complete(tween.target)
if not self.current_tweens[obj]:
del self.current_tweens[obj]
return self.current_tweens
class Tween(object):
__slots__ = ('tweenables', 'target', 'delta', 'duration', 'delay',
'ease', 'delta', 'complete', 'round',
'on_complete', 'on_update')
def __init__(self, obj, duration, delay, easing, on_complete, on_update, round,
**kwargs):
"""Tween object use Tweener.add_tween( ... ) to create"""
#: should the tween values truncated to integers or not. Default is False.
self.round = round
#: duration of the tween
self.duration = duration
#: delay before the animation should be started
self.delay = delay or 0
self.target = obj
#: easing function
self.ease = easing
# list of (property, start_value, delta)
self.tweenables = set()
for key, value in kwargs.items():
self.tweenables.add((key, Tweenable(getattr(self.target, key), value)))
self.delta = 0
#: callback to execute on complete
self.on_complete = on_complete
#: callback to execute on update
self.on_update = on_update
self.complete = False
def finish(self):
self.update(self.duration)
def update(self, ptime):
"""Update tween with the time since the last frame"""
delta = self.delta + ptime
total_duration = self.delay + self.duration
if delta > total_duration:
delta = total_duration
if delta < self.delay:
pass
elif delta == total_duration:
for key, tweenable in self.tweenables:
setattr(self.target, key, tweenable.target_value)
else:
fraction = self.ease((delta - self.delay) / (total_duration - self.delay))
for key, tweenable in self.tweenables:
res = tweenable.update(fraction)
if isinstance(res, float) and self.round:
res = int(res)
setattr(self.target, key, res)
if delta == total_duration or len(self.tweenables) == 0:
self.complete = True
self.delta = delta
if self.on_update:
self.on_update(self.target)
return self.complete
class Tweenable(object):
"""a single attribute that has to be tweened from start to target"""
__slots__ = ('start_value', 'change', 'decode_func', 'target_value', 'update')
hex_color_normal = re.compile("#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})")
hex_color_short = re.compile("#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])")
def __init__(self, start_value, target_value):
self.decode_func = lambda x: x
self.target_value = target_value
def float_update(fraction):
return self.start_value + self.change * fraction
def date_update(fraction):
return dt.date.fromtimestamp(self.start_value + self.change * fraction)
def datetime_update(fraction):
return dt.datetime.fromtimestamp(self.start_value + self.change * fraction)
def color_update(fraction):
val = [max(min(self.start_value[i] + self.change[i] * fraction, 255), 0) for i in range(3)]
return "#%02x%02x%02x" % (val[0], val[1], val[2])
if isinstance(start_value, int) or isinstance(start_value, float):
self.start_value = start_value
self.change = target_value - start_value
self.update = float_update
else:
if isinstance(start_value, dt.datetime) or isinstance(start_value, dt.date):
if isinstance(start_value, dt.datetime):
self.update = datetime_update
else:
self.update = date_update
self.decode_func = lambda x: time.mktime(x.timetuple())
self.start_value = self.decode_func(start_value)
self.change = self.decode_func(target_value) - self.start_value
elif isinstance(start_value, str) \
and (self.hex_color_normal.match(start_value) or self.hex_color_short.match(start_value)):
self.update = color_update
if self.hex_color_normal.match(start_value):
self.decode_func = lambda val: [int(match, 16)
for match in self.hex_color_normal.match(val).groups()]
elif self.hex_color_short.match(start_value):
self.decode_func = lambda val: [int(match + match, 16)
for match in self.hex_color_short.match(val).groups()]
if self.hex_color_normal.match(target_value):
target_value = [int(match, 16)
for match in self.hex_color_normal.match(target_value).groups()]
else:
target_value = [int(match + match, 16)
for match in self.hex_color_short.match(target_value).groups()]
self.start_value = self.decode_func(start_value)
self.change = [target - start for start, target in zip(self.start_value, target_value)]
"""Robert Penner's classes stripped from the repetetive c,b,d mish-mash
(discovery of Patryk Zawadzki). This way we do the math once and apply to
all the tweenables instead of repeating it for each attribute
"""
def inverse(method):
def real_inverse(t, *args, **kwargs):
t = 1 - t
return 1 - method(t, *args, **kwargs)
return real_inverse
def symmetric(ease_in, ease_out):
def real_symmetric(t, *args, **kwargs):
if t < 0.5:
return ease_in(t * 2, *args, **kwargs) / 2
return ease_out((t - 0.5) * 2, *args, **kwargs) / 2 + 0.5
return real_symmetric
class Symmetric(object):
def __init__(self, ease_in = None, ease_out = None):
self.ease_in = ease_in or inverse(ease_out)
self.ease_out = ease_out or inverse(ease_in)
self.ease_in_out = symmetric(self.ease_in, self.ease_out)
class Easing(object):
"""Class containing easing classes to use together with the tweener.
All of the classes have :func:`ease_in`, :func:`ease_out` and
:func:`ease_in_out` functions."""
Linear = Symmetric(lambda t: t, lambda t: t)
Quad = Symmetric(lambda t: t*t)
Cubic = Symmetric(lambda t: t*t*t)
Quart = Symmetric(lambda t: t*t*t*t)
Quint = Symmetric(lambda t: t*t*t*t*t)
Strong = Quint #oh i wonder why but the ported code is the same as in Quint
Circ = Symmetric(lambda t: 1 - math.sqrt(1 - t * t))
Sine = Symmetric(lambda t: 1 - math.cos(t * (math.pi / 2)))
def _back_in(t, s=1.70158):
return t * t * ((s + 1) * t - s)
Back = Symmetric(_back_in)
def _bounce_out(t):
if t < 1 / 2.75:
return 7.5625 * t * t
elif t < 2 / 2.75:
t = t - 1.5 / 2.75
return 7.5625 * t * t + 0.75
elif t < 2.5 / 2.75:
t = t - 2.25 / 2.75
return 7.5625 * t * t + .9375
else:
t = t - 2.625 / 2.75
return 7.5625 * t * t + 0.984375
Bounce = Symmetric(ease_out = _bounce_out)
def _elastic_in(t, springiness = 0, wave_length = 0):
if t in (0, 1):
return t
wave_length = wave_length or (1 - t) * 0.3
if springiness <= 1:
springiness = t
s = wave_length / 4
else:
s = wave_length / (2 * math.pi) * math.asin(t / springiness)
t = t - 1
return -(springiness * math.pow(2, 10 * t) * math.sin((t * t - s) * (2 * math.pi) / wave_length))
Elastic = Symmetric(_elastic_in)
def _expo_in(t):
if t in (0, 1): return t
return math.pow(2, 10 * t) * 0.001
Expo = Symmetric(_expo_in)
class _Dummy(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
if __name__ == "__main__":
import datetime as dt
tweener = Tweener()
objects = []
object_count, update_times = 1000, 100
for i in range(object_count):
objects.append(_Dummy(i-100, i-100, i-100))
total = dt.datetime.now()
t = dt.datetime.now()
print("Adding %d tweens..." % object_count)
for i, o in enumerate(objects):
tweener.add_tween(o, a = i,
b = i,
c = i,
duration = 0.1 * update_times,
easing=Easing.Circ.ease_in_out)
print(dt.datetime.now() - t)
t = dt.datetime.now()
print("Updating %d times......" % update_times)
for i in range(update_times): #update 1000 times
tweener.update(0.1)
print(dt.datetime.now() - t)
| 13,052 | Python | .py | 280 | 35.821429 | 107 | 0.584319 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,556 | dbus.py | projecthamster_hamster/src/hamster/lib/dbus.py | import dbus
from dbus.mainloop.glib import DBusGMainLoop as DBusMainLoop
from json import dumps, loads
from calendar import timegm
from hamster.lib import datetime as dt
from hamster.lib.fact import Fact
"""D-Bus communication utilities."""
# file layout: functions sorted in alphabetical order,
# not taking into account the "to_" and "from_" prefixes.
# So back and forth conversions are close to one another.
# dates
def from_dbus_date(dbus_date):
"""Convert D-Bus timestamp (seconds since epoch) to date."""
return dt.date.fromtimestamp(dbus_date) if dbus_date else None
def to_dbus_date(date):
"""Convert date to D-Bus timestamp (seconds since epoch)."""
return timegm(date.timetuple()) if date else 0
# facts
def from_dbus_fact_json(dbus_fact):
"""Convert D-Bus JSON to Fact."""
d = loads(dbus_fact)
range_d = d['range']
# should use pdt.datetime.fromisoformat,
# but that appears only in python3.7, nevermind
start_s = range_d['start']
end_s = range_d['end']
range = dt.Range(start=dt.datetime.parse(start_s) if start_s else None,
end=dt.datetime.parse(end_s) if end_s else None)
d['range'] = range
return Fact(**d)
def to_dbus_fact_json(fact):
"""Convert Fact to D-Bus JSON (str)."""
d = {}
keys = ('activity', 'category', 'description', 'tags', 'id', 'activity_id')
for key in keys:
d[key] = getattr(fact, key)
# isoformat(timespec="minutes") appears only in python3.6, nevermind
# and fromisoformat is not available anyway, so let's talk hamster
start = str(fact.range.start) if fact.range.start else None
end = str(fact.range.end) if fact.range.end else None
d['range'] = {'start': start, 'end': end}
return dumps(d)
# Range
def from_dbus_range(dbus_range):
"""Convert from D-Bus string to dt.Range."""
range, __ = dt.Range.parse(dbus_range, position="exact")
return range
def to_dbus_range(range):
"""Convert dt.Range to D-Bus string."""
# no default_day, to always output in the same format
return range.format(default_day=None)
# Legacy functions:
"""
old dbus_fact signature (types matching the to_dbus_fact output)
i id
i start_time
i end_time
s description
s activity name
i activity id
s category name
as List of fact tags
i date
i delta
"""
fact_signature = '(iiissisasii)'
def from_dbus_fact(dbus_fact):
"""Unpack the struct into a proper dict.
Legacy: to besuperceded by from_dbus_fact_json at some point.
"""
return Fact(activity=dbus_fact[4],
start_time=dt.datetime.utcfromtimestamp(dbus_fact[1]),
end_time=dt.datetime.utcfromtimestamp(dbus_fact[2]) if dbus_fact[2] else None,
description=dbus_fact[3],
activity_id=dbus_fact[5],
category=dbus_fact[6],
tags=dbus_fact[7],
id=dbus_fact[0]
)
def to_dbus_fact(fact):
"""Perform Fact conversion to D-Bus.
Return the corresponding dbus structure, with supported data types.
Legacy: to besuperceded by to_dbus_fact_json at some point.
"""
return (fact.id or 0,
timegm(fact.start_time.timetuple()),
timegm(fact.end_time.timetuple()) if fact.end_time else 0,
fact.description or '',
fact.activity or '',
fact.activity_id or 0,
fact.category or '',
dbus.Array(fact.tags, signature = 's'),
to_dbus_date(fact.date),
fact.delta.days * 24 * 60 * 60 + fact.delta.seconds)
| 3,629 | Python | .py | 94 | 32.393617 | 94 | 0.653451 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,557 | layout.py | projecthamster_hamster/src/hamster/lib/layout.py | # - coding: utf-8 -
# Copyright (c) 2011-2012 Media Modifications, Ltd.
# Copyright (c) 2014 Toms Baugis <toms.baugis@gmail.com>
# Dual licensed under the MIT or GPL Version 2 licenses.
import math
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import GObject as gobject
from gi.repository import Pango as pango
from collections import defaultdict
from hamster.lib import datetime as dt
from hamster.lib import graphics
class Widget(graphics.Sprite):
"""Base class for all widgets. You can use the width and height attributes
to request a specific width."""
_sizing_attributes = set(("visible", "min_width", "min_height",
"expand", "fill", "spacing",
"horizontal_spacing", "vertical_spacing", "x_align",
"y_align"))
min_width = None #: minimum width of the widget
min_height = None #: minimum height of the widget
#: Whether the child should receive extra space when the parent grows.
expand = True
#: Whether extra space given to the child should be allocated to the
#: child or used as padding. Edit :attr:`x_align` and
#: :attr:`y_align` properties to adjust alignment when fill is set to False.
fill = True
#: horizontal alignment within the parent. Works when :attr:`fill` is False
x_align = 0.5
#: vertical alignment within the parent. Works when :attr:`fill` is False
y_align = 0.5
#: child padding - shorthand to manipulate padding in pixels ala CSS. tuple
#: of one to four elements. Setting this value overwrites values of
#: :attr:`padding_top`, :attr:`padding_right`, :attr:`padding_bottom`
#: and :attr:`padding_left`
padding = None
padding_top = None #: child padding - top
padding_right = None #: child padding - right
padding_bottom = None #: child padding - bottom
padding_left = None #: child padding - left
#: widget margins - shorthand to manipulate margin in pixels ala CSS. tuple
#: of one to four elements. Setting this value overwrites values of
#: :attr:`margin_top`, :attr:`margin_right`, :attr:`margin_bottom` and
#: :attr:`margin_left`
margin = 0
margin_top = 0 #: top margin
margin_right = 0 #: right margin
margin_bottom = 0 #: bottom margin
margin_left = 0 #: left margin
enabled = True #: whether the widget is enabled
mouse_cursor = False #: Mouse cursor. see :attr:`graphics.Sprite.mouse_cursor` for values
def __init__(self, width = None, height = None, expand = None, fill = None,
x_align = None, y_align = None,
padding_top = None, padding_right = None,
padding_bottom = None, padding_left = None, padding = None,
margin_top = None, margin_right = None,
margin_bottom = None, margin_left = None, margin = None,
enabled = None, **kwargs):
graphics.Sprite.__init__(self, **kwargs)
def set_if_not_none(name, val):
# set values - avoid pitfalls of None vs 0/False
if val is not None:
setattr(self, name, val)
set_if_not_none("min_width", width)
set_if_not_none("min_height", height)
self._enabled = enabled if enabled is not None else self.__class__.enabled
set_if_not_none("fill", fill)
set_if_not_none("expand", expand)
set_if_not_none("x_align", x_align)
set_if_not_none("y_align", y_align)
# set padding
# (class, subclass, instance, and constructor)
if padding is not None or self.padding is not None:
self.padding = padding if padding is not None else self.padding
self.padding_top = padding_top or self.__class__.padding_top or self.padding_top or 0
self.padding_right = padding_right or self.__class__.padding_right or self.padding_right or 0
self.padding_bottom = padding_bottom or self.__class__.padding_bottom or self.padding_bottom or 0
self.padding_left = padding_left or self.__class__.padding_left or self.padding_left or 0
if margin is not None or self.margin is not None:
self.margin = margin if margin is not None else self.margin
self.margin_top = margin_top or self.__class__.margin_top or self.margin_top or 0
self.margin_right = margin_right or self.__class__.margin_right or self.margin_right or 0
self.margin_bottom = margin_bottom or self.__class__.margin_bottom or self.margin_bottom or 0
self.margin_left = margin_left or self.__class__.margin_left or self.margin_left or 0
#: width in pixels that have been allocated to the widget by parent
self.alloc_w = width if width is not None else self.min_width
#: height in pixels that have been allocated to the widget by parent
self.alloc_h = height if height is not None else self.min_height
self.connect_after("on-render", self.__on_render)
self.connect("on-mouse-over", self.__on_mouse_over)
self.connect("on-mouse-out", self.__on_mouse_out)
self.connect("on-mouse-down", self.__on_mouse_down)
self.connect("on-key-press", self.__on_key_press)
self._children_resize_queued = True
self._scene_resize_handler = None
def __setattr__(self, name, val):
# forward width and height to min_width and min_height as i've ruined the setters a bit i think
if name == "width":
name = "min_width"
elif name == "height":
name = "min_height"
elif name == 'enabled':
name = '_enabled'
elif name == "padding":
val = val or 0
if isinstance(val, int):
val = (val, )
if len(val) == 1:
self.padding_top = self.padding_right = self.padding_bottom = self.padding_left = val[0]
elif len(val) == 2:
self.padding_top = self.padding_bottom = val[0]
self.padding_right = self.padding_left = val[1]
elif len(val) == 3:
self.padding_top = val[0]
self.padding_right = self.padding_left = val[1]
self.padding_bottom = val[2]
elif len(val) == 4:
self.padding_top, self.padding_right, self.padding_bottom, self.padding_left = val
return
elif name == "margin":
val = val or 0
if isinstance(val, int):
val = (val, )
if len(val) == 1:
self.margin_top = self.margin_right = self.margin_bottom = self.margin_left = val[0]
elif len(val) == 2:
self.margin_top = self.margin_bottom = val[0]
self.margin_right = self.margin_left = val[1]
elif len(val) == 3:
self.margin_top = val[0]
self.margin_right = self.margin_left = val[1]
self.margin_bottom = val[2]
elif len(val) == 4:
self.margin_top, self.margin_right, self.margin_bottom, self.margin_left = val
return
if self.__dict__.get(name, "hamster_graphics_no_value_really") == val:
return
graphics.Sprite.__setattr__(self, name, val)
# in widget case visibility affects placement and everything so request repositioning from parent
if name == 'visible' and getattr(self, "parent", None) and getattr(self.parent, "resize_children", None):
self.parent.resize_children()
elif name == '_enabled' and getattr(self, "sprites", None):
self._propagate_enabledness()
if name in self._sizing_attributes:
self.queue_resize()
def _propagate_enabledness(self):
# runs down the tree and marks all child sprites as dirty as
# enabledness is inherited
self._sprite_dirty = True
for sprite in self.sprites:
next_call = getattr(sprite, "_propagate_enabledness", None)
if next_call:
next_call()
def _with_rotation(self, w, h):
"""calculate the actual dimensions after rotation"""
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h
@property
def horizontal_padding(self):
"""total calculated horizontal padding. A read-only property."""
return self.padding_left + self.padding_right
@property
def vertical_padding(self):
"""total calculated vertical padding. A read-only property."""
return self.padding_top + self.padding_bottom
def __on_mouse_over(self, sprite):
cursor, mouse_x, mouse_y, mods = sprite.get_scene().get_window().get_pointer()
if self.tooltip and not gdk.ModifierType.BUTTON1_MASK & mods:
self._set_tooltip(self.tooltip)
def __on_mouse_out(self, sprite):
if self.tooltip:
self._set_tooltip(None)
def __on_mouse_down(self, sprite, event):
if self.can_focus:
self.grab_focus()
if self.tooltip:
self._set_tooltip(None)
def __on_key_press(self, sprite, event):
if event.keyval in (gdk.KEY_Tab, gdk.KEY_ISO_Left_Tab):
idx = self.parent.sprites.index(self)
if event.state & gdk.ModifierType.SHIFT_MASK: # going backwards
if idx > 0:
idx -= 1
self.parent.sprites[idx].grab_focus()
else:
if idx < len(self.parent.sprites) - 1:
idx += 1
self.parent.sprites[idx].grab_focus()
def queue_resize(self):
"""request the element to re-check it's child sprite sizes"""
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize()
def get_min_size(self):
"""returns size required by the widget"""
if self.visible == False:
return 0, 0
else:
return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right,
(self.min_height or 0) + self.vertical_padding + self.margin_top + self.margin_bottom)
def insert(self, index = 0, *widgets):
"""insert widget in the sprites list at the given index.
by default will prepend."""
for widget in widgets:
self._add(widget, index)
index +=1 # as we are moving forwards
self._sort()
def insert_before(self, target):
"""insert this widget into the targets parent before the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target), self)
def insert_after(self, target):
"""insert this widget into the targets parent container after the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target) + 1, self)
@property
def width(self):
"""width in pixels"""
alloc_w = self.alloc_w
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_w = self.parent.width
def res(scene, event):
if self.parent:
self.queue_resize()
else:
scene.disconnect(self._scene_resize_handler)
self._scene_resize_handler = None
if not self._scene_resize_handler:
# TODO - disconnect on reparenting
self._scene_resize_handler = self.parent.connect("on-resize", res)
min_width = (self.min_width or 0) + self.margin_left + self.margin_right
w = alloc_w if alloc_w is not None and self.fill else min_width
w = max(w or 0, self.get_min_size()[0])
return w - self.margin_left - self.margin_right
@property
def height(self):
"""height in pixels"""
alloc_h = self.alloc_h
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_h = self.parent.height
min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom
h = alloc_h if alloc_h is not None and self.fill else min_height
h = max(h or 0, self.get_min_size()[1])
return h - self.margin_top - self.margin_bottom
@property
def enabled(self):
"""whether the user is allowed to interact with the
widget. Item is enabled only if all it's parent elements are"""
enabled = self._enabled
if not enabled:
return False
if self.parent and isinstance(self.parent, Widget):
if self.parent.enabled == False:
return False
return True
def __on_render(self, sprite):
self.do_render()
if self.debug:
self.graphics.save_context()
w, h = self.width, self.height
if hasattr(self, "get_height_for_width_size"):
w2, h2 = self.get_height_for_width_size()
w2 = w2 - self.margin_left - self.margin_right
h2 = h2 - self.margin_top - self.margin_bottom
w, h = max(w, w2), max(h, h2)
self.graphics.rectangle(0.5, 0.5, w, h)
self.graphics.set_line_style(3)
self.graphics.stroke("#666", 0.5)
self.graphics.restore_context()
if self.pivot_x or self.pivot_y:
self.graphics.fill_area(self.pivot_x - 3, self.pivot_y - 3, 6, 6, "#666")
def do_render(self):
"""this function is called in the on-render event. override it to do
any drawing. subscribing to the "on-render" event will work too, but
overriding this method is preferred for easier subclassing.
"""
pass
def get_min_size(sprite):
if hasattr(sprite, "get_min_size"):
min_width, min_height = sprite.get_min_size()
else:
min_width, min_height = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
min_width = min_width * sprite.scale_x
min_height = min_height * sprite.scale_y
return min_width, min_height
def get_props(sprite):
# gets all the relevant info for containers and puts it in a uniform dict.
# this way we can access any object without having to check types and such
keys = ("margin_top", "margin_right", "margin_bottom", "margin_left",
"padding_top", "padding_right", "padding_bottom", "padding_left")
res = dict((key, getattr(sprite, key, 0)) for key in keys)
res["expand"] = getattr(sprite, "expand", True)
return sprite, res
class Container(Widget):
"""The base container class that all other containers inherit from.
You can insert any sprite in the container, just make sure that it either
has width and height defined so that the container can do alignment, or
for more sophisticated cases, make sure it has get_min_size function that
returns how much space is needed.
Normally while performing layout the container will update child sprites
and set their alloc_h and alloc_w properties. The `alloc` part is short
for allocated. So use that when making rendering decisions.
"""
cache_attrs = Widget.cache_attrs | set(('_cached_w', '_cached_h'))
_sizing_attributes = Widget._sizing_attributes | set(('padding_top', 'padding_right', 'padding_bottom', 'padding_left'))
def __init__(self, contents = None, **kwargs):
Widget.__init__(self, **kwargs)
#: contents of the container - either a widget or a list of widgets
self.contents = contents
self._cached_w, self._cached_h = None, None
def __setattr__(self, name, val):
if self.__dict__.get(name, "hamster_graphics_no_value_really") == val:
return
Widget.__setattr__(self, name, val)
if name == 'contents':
if val:
if isinstance(val, graphics.Sprite):
val = [val]
self.add_child(*val)
if self.sprites and self.sprites != val:
self.remove_child(*list(set(self.sprites) ^ set(val or [])))
if name in ("alloc_w", "alloc_h") and val:
self.__dict__['_cached_w'], self.__dict__['_cached_h'] = None, None
self._children_resize_queued = True
@property
def contents(self):
return self.sprites
def _Widget__on_render(self, sprite):
if self._children_resize_queued:
self.resize_children()
self.__dict__['_children_resize_queued'] = False
Widget._Widget__on_render(self, sprite)
def _add(self, *sprites):
Widget._add(self, *sprites)
self.queue_resize()
def remove_child(self, *sprites):
Widget.remove_child(self, *sprites)
self.queue_resize()
def queue_resize(self):
self.__dict__['_cached_w'], self.__dict__['_cached_h'] = None, None
Widget.queue_resize(self)
def get_min_size(self):
# by default max between our requested size and the biggest child
if self.visible == False:
return 0, 0
if self._cached_w is None:
sprites = [sprite for sprite in self.sprites if sprite.visible]
width = max([get_min_size(sprite)[0] for sprite in sprites] or [0])
width += self.horizontal_padding + self.margin_left + self.margin_right
height = max([get_min_size(sprite)[1] for sprite in sprites] or [0])
height += self.vertical_padding + self.margin_top + self.margin_bottom
self._cached_w, self._cached_h = max(width, self.min_width or 0), max(height, self.min_height or 0)
return self._cached_w, self._cached_h
def get_height_for_width_size(self):
return self.get_min_size()
def resize_children(self):
"""default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties"""
width = self.width - self.horizontal_padding
height = self.height - self.vertical_padding
for sprite, props in (get_props(sprite) for sprite in self.sprites if sprite.visible):
sprite.alloc_w = width
sprite.alloc_h = height
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
if hasattr(sprite, "get_height_for_width_size"):
w2, h2 = sprite.get_height_for_width_size()
w, h = max(w, w2), max(h, h2)
w = w * sprite.scale_x + props["margin_left"] + props["margin_right"]
h = h * sprite.scale_y + props["margin_top"] + props["margin_bottom"]
sprite.x = self.padding_left + props["margin_left"] + (max(sprite.alloc_w * sprite.scale_x, w) - w) * getattr(sprite, "x_align", 0)
sprite.y = self.padding_top + props["margin_top"] + (max(sprite.alloc_h * sprite.scale_y, h) - h) * getattr(sprite, "y_align", 0)
self.__dict__['_children_resize_queued'] = False
class Bin(Container):
"""A container with only one child. Adding new children will throw the
previous ones out"""
def __init__(self, contents = None, **kwargs):
Container.__init__(self, contents, **kwargs)
@property
def child(self):
"""child sprite. shorthand for self.sprites[0]"""
return self.sprites[0] if self.sprites else None
def get_height_for_width_size(self):
if self._children_resize_queued:
self.resize_children()
sprites = [sprite for sprite in self.sprites if sprite.visible]
width, height = 0, 0
for sprite in sprites:
if hasattr(sprite, "get_height_for_width_size"):
w, h = sprite.get_height_for_width_size()
else:
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
w, h = w * sprite.scale_x, h * sprite.scale_y
width = max(width, w)
height = max(height, h)
#width = width + self.horizontal_padding + self.margin_left + self.margin_right
#height = height + self.vertical_padding + self.margin_top + self.margin_bottom
return width, height
def add_child(self, *sprites):
if not sprites:
return
sprite = sprites[-1] # there can be just one
# performing add then remove to not screw up coordinates in
# a strange reparenting case
Container.add_child(self, sprite)
if self.sprites and self.sprites[0] != sprite:
self.remove_child(*list(set(self.sprites) ^ set([sprite])))
class Fixed(Container):
"""Basic container that does not care about child positions. Handy if
you want to place stuff yourself or do animations.
"""
def __init__(self, contents = None, **kwargs):
Container.__init__(self, contents, **kwargs)
def resize_children(self):
# don't want
pass
class Box(Container):
"""Align children either horizontally or vertically.
Normally you would use :class:`HBox` or :class:`VBox` to be
specific but this one is suited so you can change the packing direction
dynamically.
"""
#: spacing in pixels between children
spacing = 5
#: whether the box is packing children horizontally (from left to right) or vertically (from top to bottom)
orient_horizontal = True
def __init__(self, contents = None, horizontal = None, spacing = None, **kwargs):
Container.__init__(self, contents, **kwargs)
if horizontal is not None:
self.orient_horizontal = horizontal
if spacing is not None:
self.spacing = spacing
def get_total_spacing(self):
# now lay them out
padding_sprites = 0
for sprite in self.sprites:
if sprite.visible:
if getattr(sprite, "expand", True):
padding_sprites += 1
else:
if hasattr(sprite, "get_min_size"):
size = sprite.get_min_size()[0] if self.orient_horizontal else sprite.get_min_size()[1]
else:
size = getattr(sprite, "width", 0) * sprite.scale_x if self.orient_horizontal else getattr(sprite, "height", 0) * sprite.scale_y
if size > 0:
padding_sprites +=1
return self.spacing * max(padding_sprites - 1, 0)
def resize_children(self):
if not self.parent:
return
width = self.width - self.padding_left - self.padding_right
height = self.height - self.padding_top - self.padding_bottom
sprites = [get_props(sprite) for sprite in self.sprites if sprite.visible]
# calculate if we have any spare space
sprite_sizes = []
for sprite, props in sprites:
if self.orient_horizontal:
sprite.alloc_h = height / sprite.scale_y
size = get_min_size(sprite)[0]
size = size + props["margin_left"] + props["margin_right"]
else:
sprite.alloc_w = width / sprite.scale_x
size = get_min_size(sprite)[1]
if hasattr(sprite, "get_height_for_width_size"):
size = max(size, sprite.get_height_for_width_size()[1] * sprite.scale_y)
size = size + props["margin_top"] + props["margin_bottom"]
sprite_sizes.append(size)
remaining_space = width if self.orient_horizontal else height
if sprite_sizes:
remaining_space = remaining_space - sum(sprite_sizes) - self.get_total_spacing()
interested_sprites = [sprite for sprite, props in sprites if getattr(sprite, "expand", True)]
# in order to stay pixel sharp we will recalculate remaining bonus
# each time we give up some of the remaining space
remaining_interested = len(interested_sprites)
bonus = 0
if remaining_space > 0 and interested_sprites:
bonus = int(remaining_space / remaining_interested)
actual_h = 0
x_pos, y_pos = 0, 0
for (sprite, props), min_size in zip(sprites, sprite_sizes):
sprite_bonus = 0
if sprite in interested_sprites:
sprite_bonus = bonus
remaining_interested -= 1
remaining_space -= bonus
if remaining_interested:
bonus = int(float(remaining_space) / remaining_interested)
if self.orient_horizontal:
sprite.alloc_w = (min_size + sprite_bonus) / sprite.scale_x
else:
sprite.alloc_h = (min_size + sprite_bonus) / sprite.scale_y
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
if hasattr(sprite, "get_height_for_width_size"):
w2, h2 = sprite.get_height_for_width_size()
w, h = max(w, w2), max(h, h2)
w = w * sprite.scale_x + props["margin_left"] + props["margin_right"]
h = h * sprite.scale_y + props["margin_top"] + props["margin_bottom"]
sprite.x = self.padding_left + x_pos + props["margin_left"] + (max(sprite.alloc_w * sprite.scale_x, w) - w) * getattr(sprite, "x_align", 0.5)
sprite.y = self.padding_top + y_pos + props["margin_top"] + (max(sprite.alloc_h * sprite.scale_y, h) - h) * getattr(sprite, "y_align", 0.5)
actual_h = max(actual_h, h * sprite.scale_y)
if (min_size + sprite_bonus) > 0:
if self.orient_horizontal:
x_pos += int(max(w, sprite.alloc_w * sprite.scale_x)) + self.spacing
else:
y_pos += max(h, sprite.alloc_h * sprite.scale_y) + self.spacing
if self.orient_horizontal:
for sprite, props in sprites:
sprite.__dict__['alloc_h'] = actual_h
self.__dict__['_children_resize_queued'] = False
def get_height_for_width_size(self):
if self._children_resize_queued:
self.resize_children()
sprites = [sprite for sprite in self.sprites if sprite.visible]
width, height = 0, 0
for sprite in sprites:
if hasattr(sprite, "get_height_for_width_size"):
w, h = sprite.get_height_for_width_size()
else:
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
w, h = w * sprite.scale_x, h * sprite.scale_y
if self.orient_horizontal:
width += w
height = max(height, h)
else:
width = max(width, w)
height = height + h
if self.orient_horizontal:
width = width + self.get_total_spacing()
else:
height = height + self.get_total_spacing()
width = width + self.horizontal_padding + self.margin_left + self.margin_right
height = height + self.vertical_padding + self.margin_top + self.margin_bottom
return width, height
def get_min_size(self):
if self.visible == False:
return 0, 0
if self._cached_w is None:
sprites = [sprite for sprite in self.sprites if sprite.visible]
width, height = 0, 0
for sprite in sprites:
if hasattr(sprite, "get_min_size"):
w, h = sprite.get_min_size()
else:
w, h = getattr(sprite, "width", 0), getattr(sprite, "height", 0)
w, h = w * sprite.scale_x, h * sprite.scale_y
if self.orient_horizontal:
width += w
height = max(height, h)
else:
width = max(width, w)
height = height + h
if self.orient_horizontal:
width = width + self.get_total_spacing()
else:
height = height + self.get_total_spacing()
width = width + self.horizontal_padding + self.margin_left + self.margin_right
height = height + self.vertical_padding + self.margin_top + self.margin_bottom
w, h = max(width, self.min_width or 0), max(height, self.min_height or 0)
self._cached_w, self._cached_h = w, h
return self._cached_w, self._cached_h
class HBox(Box):
"""A horizontally aligned box. identical to ui.Box(horizontal=True)"""
def __init__(self, contents = None, **kwargs):
Box.__init__(self, contents, **kwargs)
self.orient_horizontal = True
class VBox(Box):
"""A vertically aligned box. identical to ui.Box(horizontal=False)"""
def __init__(self, contents = None, **kwargs):
Box.__init__(self, contents, **kwargs)
self.orient_horizontal = False
class _DisplayLabel(graphics.Label):
cache_attrs = Box.cache_attrs | set(('_cached_w', '_cached_h'))
def __init__(self, text="", **kwargs):
graphics.Label.__init__(self, text, **kwargs)
self._cached_w, self._cached_h = None, None
self._cached_wh_w, self._cached_wh_h = None, None
def __setattr__(self, name, val):
graphics.Label.__setattr__(self, name, val)
if name in ("text", "markup", "size", "wrap", "ellipsize", "max_width"):
if name != "max_width":
self._cached_w, self._cached_h = None, None
self._cached_wh_w, self._cached_wh_h = None, None
def get_min_size(self):
if self._cached_w:
return self._cached_w, self._cached_h
text = self.markup or self.text
escape = len(self.markup) == 0
if self.wrap is not None or self.ellipsize is not None:
self._cached_w = self.measure(text, escape, 1)[0]
self._cached_h = self.measure(text, escape, -1)[1]
else:
self._cached_w, self._cached_h = self.measure(text, escape, -1)
return self._cached_w, self._cached_h
def get_height_for_width_size(self):
if self._cached_wh_w:
return self._cached_wh_w, self._cached_wh_h
text = self.markup or self.text
escape = len(self.markup) == 0
self._cached_wh_w, self._cached_wh_h = self.measure(text, escape, self.max_width)
return self._cached_wh_w, self._cached_wh_h
class Label(Bin):
"""a widget that displays a limited amount of read-only text"""
#: pango.FontDescription to use for the label
font_desc = None
#: image attachment. one of top, right, bottom, left
image_position = "left"
#: font size
size = None
fill = False
padding = 0
x_align = 0.5
def __init__(self, text = "", markup = "", spacing = 5, image = None,
image_position = None, size = None, font_desc = None,
overflow = False, color = "#000", background_color = None,
**kwargs):
# TODO - am initiating table with fill = false but that yields suboptimal label placement and the 0,0 points to whatever parent gave us
Bin.__init__(self, **kwargs)
#: image to put next to the label
self.image = image
# the actual container that contains the label and/or image
self.container = Box(spacing = spacing, fill = False,
x_align = self.x_align, y_align = self.y_align)
if image_position is not None:
self.image_position = image_position
self.display_label = _DisplayLabel(text = text, markup = markup, color=color, size = size)
self.display_label.x_align = 0 # the default is 0.5 which makes label align incorrectly on wrapping
if font_desc or self.font_desc:
self.display_label.font_desc = font_desc or self.font_desc
self.display_label.size = size or self.size
self.background_color = background_color
#: either the pango `wrap <http://www.pygtk.org/pygtk2reference/pango-constants.html#pango-wrap-mode-constants>`_
#: or `ellipsize <http://www.pygtk.org/pygtk2reference/pango-constants.html#pango-ellipsize-mode-constants>`_ constant.
#: if set to False will refuse to become smaller
self.overflow = overflow
self.add_child(self.container)
self._position_contents()
self.connect_after("on-render", self.__on_render)
def get_mouse_sprites(self):
return None
@property
def text(self):
"""label text. This attribute and :attr:`markup` are mutually exclusive."""
return self.display_label.text
@property
def markup(self):
"""pango markup to use in the label.
This attribute and :attr:`text` are mutually exclusive."""
return self.display_label.markup
@property
def color(self):
"""label color"""
return self.display_label.color
def __setattr__(self, name, val):
if name in ("text", "markup", "color", "size"):
if self.display_label.__dict__.get(name, "hamster_graphics_no_value_really") is val:
return
setattr(self.display_label, name, val)
elif name in ("spacing"):
setattr(self.container, name, val)
else:
if self.__dict__.get(name, "hamster_graphics_no_value_really") is val:
return
Bin.__setattr__(self, name, val)
if name in ('x_align', 'y_align') and hasattr(self, "container"):
setattr(self.container, name, val)
elif name == "alloc_w" and hasattr(self, "display_label") and getattr(self, "overflow") is not False:
self._update_max_width()
elif name == "min_width" and hasattr(self, "display_label"):
self.display_label.width = val - self.horizontal_padding
elif name == "overflow" and hasattr(self, "display_label"):
if val is False:
self.display_label.wrap = None
self.display_label.ellipsize = None
elif isinstance(val, pango.WrapMode) and val in (pango.WrapMode.WORD, pango.WrapMode.WORD_CHAR, pango.WrapMode.CHAR):
self.display_label.wrap = val
self.display_label.ellipsize = None
elif isinstance(val, pango.EllipsizeMode) and val in (pango.EllipsizeMode.START, pango.EllipsizeMode.MIDDLE, pango.EllipsizeMode.END):
self.display_label.wrap = None
self.display_label.ellipsize = val
self._update_max_width()
elif name in ("font_desc", "size"):
setattr(self.display_label, name, val)
if name in ("text", "markup", "image", "image_position", "overflow", "size"):
if hasattr(self, "overflow"):
self._position_contents()
self.container.queue_resize()
def _update_max_width(self):
# updates labels max width, respecting image and spacing
if self.overflow is False:
self.display_label.max_width = -1
else:
w = (self.alloc_w or 0) - self.horizontal_padding - self.container.spacing
if self.image and self.image_position in ("left", "right"):
w -= self.image.width - self.container.spacing
self.display_label.max_width = w
self.container.queue_resize()
def _position_contents(self):
if self.image and (self.text or self.markup):
self.image.expand = False
self.container.orient_horizontal = self.image_position in ("left", "right")
if self.image_position in ("top", "left"):
if self.container.sprites != [self.image, self.display_label]:
self.container.clear()
self.container.add_child(self.image, self.display_label)
else:
if self.container.sprites != [self.display_label, self.image]:
self.container.clear()
self.container.add_child(self.display_label, self.image)
elif self.image or (self.text or self.markup):
sprite = self.image or self.display_label
if self.container.sprites != [sprite]:
self.container.clear()
self.container.add_child(sprite)
def __on_render(self, sprite):
w, h = self.width, self.height
w2, h2 = self.get_height_for_width_size()
w, h = max(w, w2), max(h, h2)
self.graphics.rectangle(0, 0, w, h)
if self.background_color:
self.graphics.fill(self.background_color)
else:
self.graphics.new_path()
| 36,925 | Python | .py | 725 | 40.034483 | 153 | 0.599889 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,558 | parsing.py | projecthamster_hamster/src/hamster/lib/parsing.py | import logging
logger = logging.getLogger(__name__) # noqa: E402
import re
from hamster.lib import datetime as dt
# separator between times and activity
activity_separator = r"\s+"
# match #tag followed by any space or # that will be ignored
# tag must not contain '#' or ','
tag_re = re.compile(r"""
\# # hash character
(?P<tag>
[^#,]+ # (anything but hash or comma)
)
""", flags=re.VERBOSE)
tags_in_description = re.compile(r"""
\#
(?P<tag>
[a-zA-Z] # Starts with an alphabetic character (digits excluded)
[^\s]+ # followed by anything except spaces
)
""", flags=re.VERBOSE)
tags_separator = re.compile(r"""
,{1,2} # 1 or 2 commas
\s* # maybe spaces
(?=\#) # hash character (start of first tag, doesn't consume it)
""", flags=re.VERBOSE)
description_separator = re.compile(r"""
,+ # 1 or more commas
\s* # maybe spaces
""", flags=re.VERBOSE)
def get_tags_from_description(description):
return list(re.findall(tags_in_description, description))
def parse_fact(text, range_pos="head", default_day=None, ref="now"):
"""Extract fact fields from the string.
Returns found fields as a dict.
Tentative syntax (not accurate):
start [- end_time] activity[@category][, description][,]{ #tag}
According to the legacy tests, # were allowed in the description
"""
res = {}
text = text.strip()
if not text:
return res
# datetimes
# force at least a space to avoid matching 10.00@cat
(start, end), remaining_text = dt.Range.parse(text, position=range_pos,
separator=activity_separator,
default_day=default_day)
res["start_time"] = start
res["end_time"] = end
# tags
split = re.split(tags_separator, remaining_text, 1)
remaining_text = split[0]
tags_part = split[1] if len(split) > 1 else None
if tags_part:
tags = list(map(lambda x: x.strip(), re.findall(tag_re, tags_part)))
else:
tags = []
# description
# first look for comma (description hard left boundary)
split = re.split(description_separator, remaining_text, 1)
head = split[0]
description = split[1] if len(split) > 1 else ""
# Extract tags from description, put them before other tags
tags = get_tags_from_description(description) + tags
res["description"] = description.strip()
remaining_text = head.strip()
res["tags"] = tags
# activity
split = remaining_text.rsplit('@', maxsplit=1)
activity = split[0]
category = split[1] if len(split) > 1 else ""
res["activity"] = activity
res["category"] = category
return res
| 2,780 | Python | .py | 75 | 31.186667 | 79 | 0.62281 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,559 | charting.py | projecthamster_hamster/src/hamster/lib/charting.py | # - coding: utf-8 -
# Copyright (C) 2008-2010 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject as gobject
from gi.repository import Gtk as gtk
from gi.repository import Pango as pango
import time
from hamster.lib import graphics, stuff
from hamster.lib import datetime as dt
import locale
class Bar(graphics.Sprite):
def __init__(self, key, value, normalized, label_color):
graphics.Sprite.__init__(self, cache_as_bitmap=True)
self.key, self.value, self.normalized = key, value, normalized
self.height = 0
self.width = 20
self.interactive = True
self.fill = None
self.label = graphics.Label(value, size=8, color=label_color)
self.label_background = graphics.Rectangle(self.label.width + 4, self.label.height + 4, 4, visible=False)
self.add_child(self.label_background)
self.add_child(self.label)
self.connect("on-render", self.on_render)
def on_render(self, sprite):
# invisible rectangle for the mouse, covering whole area
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.fill("#000", 0)
size = round(self.width * self.normalized)
self.graphics.rectangle(0, 0, size, self.height, 3)
self.graphics.rectangle(0, 0, min(size, 3), self.height)
self.graphics.fill(self.fill)
self.label.y = (self.height - self.label.height) / 2
horiz_offset = min(10, self.label.y * 2)
if self.label.width < size - horiz_offset * 2:
#if it fits in the bar
self.label.x = size - self.label.width - horiz_offset
else:
self.label.x = size + 3
self.label_background.x = self.label.x - 2
self.label_background.y = self.label.y - 2
class Chart(graphics.Scene):
__gsignals__ = {
"bar-clicked": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )),
}
def __init__(self, max_bar_width = 20, legend_width = 70, value_format = "%.2f", interactive = True):
graphics.Scene.__init__(self)
self.selected_keys = [] # keys of selected bars
self.bars = []
self.labels = []
self.data = None
self.max_width = max_bar_width
self.legend_width = legend_width
self.value_format = value_format
self.graph_interactive = interactive
self.plot_area = graphics.Sprite(interactive = False)
self.add_child(self.plot_area)
self.bar_color, self.label_color = None, None
self.connect("on-enter-frame", self.on_enter_frame)
if self.graph_interactive:
self.connect("on-mouse-over", self.on_mouse_over)
self.connect("on-mouse-out", self.on_mouse_out)
self.connect("on-click", self.on_click)
def find_colors(self):
bg_color = "#eee" #self.get_style().bg[gtk.StateType.NORMAL].to_string()
self.bar_color = self.colors.contrast(bg_color, 30)
# now for the text - we want reduced contrast for relaxed visuals
fg_color = "#aaa" #self.get_style().fg[gtk.StateType.NORMAL].to_string()
self.label_color = self.colors.contrast(fg_color, 80)
def on_mouse_over(self, scene, bar):
if bar.key not in self.selected_keys:
bar.fill = "#999" #self.get_style().base[gtk.StateType.PRELIGHT].to_string()
def on_mouse_out(self, scene, bar):
if bar.key not in self.selected_keys:
bar.fill = self.bar_color
def on_click(self, scene, event, clicked_bar):
if not clicked_bar: return
self.emit("bar-clicked", clicked_bar.key)
def plot(self, keys, data):
self.data = data
bars = dict([(bar.key, bar.normalized) for bar in self.bars])
max_val = float(max(data or [0]))
new_bars, new_labels = [], []
for key, value in zip(keys, data):
if max_val:
normalized = value / max_val
else:
normalized = 0
bar = Bar(key, locale.format(self.value_format, value), normalized, self.label_color)
bar.interactive = self.graph_interactive
if key in bars:
bar.normalized = bars[key]
self.tweener.add_tween(bar, normalized=normalized)
new_bars.append(bar)
label = graphics.Label(stuff.escape_pango(key), size = 8, alignment = pango.Alignment.RIGHT)
new_labels.append(label)
self.plot_area.remove_child(*self.bars)
self.remove_child(*self.labels)
self.bars, self.labels = new_bars, new_labels
self.add_child(*self.labels)
self.plot_area.add_child(*self.bars)
self.show()
self.redraw()
def on_enter_frame(self, scene, context):
# adjust sizes and positions on redraw
legend_width = self.legend_width
if legend_width < 1: # allow fractions
legend_width = int(self.width * legend_width)
self.find_colors()
self.plot_area.y = 0
self.plot_area.height = self.height - self.plot_area.y
self.plot_area.x = legend_width + 8
self.plot_area.width = self.width - self.plot_area.x
y = 0
for i, (label, bar) in enumerate(zip(self.labels, self.bars)):
bar_width = min(round((self.plot_area.height - y) / (len(self.bars) - i)), self.max_width)
bar.y = y
bar.height = bar_width
bar.width = self.plot_area.width
if bar.key in self.selected_keys:
bar.fill = "#aaa" #self.get_style().bg[gtk.StateType.SELECTED].to_string()
if bar.normalized == 0:
bar.label.color = "#666" #self.get_style().fg[gtk.StateType.SELECTED].to_string()
bar.label_background.fill = "#aaa" #self.get_style().bg[gtk.StateType.SELECTED].to_string()
bar.label_background.visible = True
else:
bar.label_background.visible = False
if bar.label.x < round(bar.width * bar.normalized):
bar.label.color = "#666" #self.get_style().fg[gtk.StateType.SELECTED].to_string()
else:
bar.label.color = self.label_color
if not bar.fill:
bar.fill = self.bar_color
bar.label.color = self.label_color
bar.label_background.fill = None
label.y = y + (bar_width - label.height) / 2 + self.plot_area.y
label.width = legend_width
if not label.color:
label.color = self.label_color
y += bar_width + 1
class HorizontalDayChart(graphics.Scene):
"""Pretty much a horizontal bar chart, except for values it expects tuple
of start and end time, and the whole thing hangs in air"""
def __init__(self, max_bar_width, legend_width):
graphics.Scene.__init__(self)
self.max_bar_width = max_bar_width
self.legend_width = legend_width
self.start_time, self.end_time = None, None
self.connect("on-enter-frame", self.on_enter_frame)
def plot_day(self, keys, data, start_time = None, end_time = None):
self.keys, self.data = keys, data
self.start_time, self.end_time = start_time, end_time
self.show()
self.redraw()
def on_enter_frame(self, scene, context):
g = graphics.Graphics(context)
rowcount, keys = len(self.keys), self.keys
start_hour = 0
if self.start_time:
start_hour = self.start_time
end_hour = 24 * 60
if self.end_time:
end_hour = self.end_time
# push graph to the right, so it doesn't overlap
legend_width = self.legend_width or self.longest_label(keys)
self.graph_x = legend_width
self.graph_x += 8 #add another 8 pixes of padding
self.graph_width = self.width - self.graph_x
# TODO - should handle the layout business in graphics
self.layout = context.create_layout()
default_font = "Sans Serif" #pango.FontDescription(self.get_style().font_desc.to_string())
default_font.set_size(8 * pango.SCALE)
self.layout.set_font_description(default_font)
#on the botttom leave some space for label
self.layout.set_text("1234567890:")
label_w, label_h = self.layout.get_pixel_size()
self.graph_y, self.graph_height = 0, self.height - label_h - 4
if not self.data: #if we have nothing, let's go home
return
positions = {}
y = 0
bar_width = min(self.graph_height / float(len(self.keys)), self.max_bar_width)
for i, key in enumerate(self.keys):
positions[key] = (y + self.graph_y, round(bar_width - 1))
y = y + round(bar_width)
bar_width = min(self.max_bar_width,
(self.graph_height - y) / float(max(1, len(self.keys) - i - 1)))
max_bar_size = self.graph_width - 15
# now for the text - we want reduced contrast for relaxed visuals
fg_color = "#666" #self.get_style().fg[gtk.StateType.NORMAL].to_string()
label_color = self.colors.contrast(fg_color, 80)
self.layout.set_alignment(pango.Alignment.RIGHT)
self.layout.set_ellipsize(pango.ELLIPSIZE_END)
# bars and labels
self.layout.set_width(legend_width * pango.SCALE)
factor = max_bar_size / float(end_hour - start_hour)
# determine bar color
bg_color = "#eee" #self.get_style().bg[gtk.StateType.NORMAL].to_string()
base_color = self.colors.contrast(bg_color, 30)
for i, label in enumerate(keys):
g.set_color(label_color)
self.layout.set_text(label)
label_w, label_h = self.layout.get_pixel_size()
context.move_to(0, positions[label][0] + (positions[label][1] - label_h) / 2)
context.show_layout(self.layout)
if isinstance(self.data[i], list) == False:
self.data[i] = [self.data[i]]
for row in self.data[i]:
bar_x = round((row[0]- start_hour) * factor)
bar_size = round((row[1] - start_hour) * factor - bar_x)
g.fill_area(round(self.graph_x + bar_x),
positions[label][0],
bar_size,
positions[label][1],
base_color)
#white grid and scale values
self.layout.set_width(-1)
context.set_line_width(1)
pace = ((end_hour - start_hour) / 3) / 60 * 60
last_position = positions[keys[-1]]
grid_color = "#aaa" # self.get_style().bg[gtk.StateType.NORMAL].to_string()
for i in range(start_hour + 60, end_hour, pace):
x = round((i - start_hour) * factor)
minutes = i % (24 * 60)
self.layout.set_markup(dt.time(minutes / 60, minutes % 60).strftime("%H<small><sup>%M</sup></small>"))
label_w, label_h = self.layout.get_pixel_size()
context.move_to(self.graph_x + x - label_w / 2,
last_position[0] + last_position[1] + 4)
g.set_color(label_color)
context.show_layout(self.layout)
g.set_color(grid_color)
g.move_to(round(self.graph_x + x) + 0.5, self.graph_y)
g.line_to(round(self.graph_x + x) + 0.5,
last_position[0] + last_position[1])
context.stroke()
| 12,327 | Python | .py | 244 | 39.745902 | 114 | 0.602805 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,560 | i18n.py | projecthamster_hamster/src/hamster/lib/i18n.py | # - coding: utf-8 -
import os
import locale, gettext
import hamster
def setup_i18n():
#determine location of po files
# to avoid confusion, we won't translate unless running installed
# reason for that is that bindtextdomain is expecting
# localedir/language/LC_MESSAGES/domain.mo format, but we have
# localedir/language.mo at it's best (after build)
# and there does not seem to be any way to run straight from sources
if hamster.installed:
from hamster import defs # only available when running installed
locale_dir = os.path.realpath(os.path.join(defs.DATA_DIR, "locale"))
for module in (locale,gettext):
module.bindtextdomain('hamster', locale_dir)
module.textdomain('hamster')
gettext.install("hamster", locale_dir)
else:
gettext.install("hamster-uninstalled")
def C_(ctx, s):
"""Provide qualified translatable strings via context.
Taken from gnome-games.
"""
translated = gettext.gettext('%s\x04%s' % (ctx, s))
if '\x04' in translated:
# no translation found, return input string
return s
return translated
| 1,164 | Python | .py | 29 | 34 | 76 | 0.690053 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,561 | __init__.py | projecthamster_hamster/src/hamster/lib/__init__.py | import logging
logger = logging.getLogger(__name__) # noqa: E402
from hamster.lib.fact import Fact # for backward compatibility with v2
def default_logger(name):
"""Return a toplevel logger.
This should be used only in the toplevel file.
Files deeper in the hierarchy should use
``logger = logging.getLogger(__name__)``,
in order to considered as children of the toplevel logger.
Beware that without a setLevel() somewhere,
the default value (warning) will be used, so no debug message will be shown.
Args:
name (str): usually `__name__` in the package toplevel __init__.py, or
`__file__` in a script file
(because __name__ would be "__main__" in this case).
"""
# https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial
logger = logging.getLogger(name)
# this is a basic handler, with output to stderr
logger_handler = logging.StreamHandler()
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
logger_handler.setFormatter(formatter)
logger.addHandler(logger_handler)
return logger
| 1,147 | Python | .py | 24 | 41.541667 | 80 | 0.683738 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,562 | stuff.py | projecthamster_hamster/src/hamster/lib/stuff.py | # - coding: utf-8 -
# Copyright (C) 2008-2010, 2014 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
# some widgets that repeat all over the place
# cells, columns, trees and other
import logging
logger = logging.getLogger(__name__) # noqa: E402
from gi.repository import Gtk as gtk
from gi.repository import Pango as pango
from itertools import groupby
import calendar
import time
import re
import locale
import os
from hamster.lib import datetime as dt
# for pre-v3.0 backward compatibility
hamster_now = dt.datetime.now
hamster_today = dt.hday.today
hamsterday_time_to_datetime = dt.datetime.from_day_time
def datetime_to_hamsterday(civil_date_time):
"""Return the hamster day corresponding to a given civil datetime.
Deprecated: use civil_date_time.hday() instead
The hamster day start is taken into account.
"""
return civil_date_time.hday()
def hamster_round(time):
"""Round time or datetime.
Deprecated: hamster.lib/datetime.time or datetime are already rounded.
"""
if time is None:
return None
else:
return time.replace(second=0, microsecond=0)
def format_duration(minutes, human = True):
"""formats duration in a human readable format.
accepts either minutes or timedelta
Deprecated: use timedelta.format() instead.
"""
minutes = duration_minutes(minutes)
if not minutes:
if human:
return ""
else:
return "00:00"
if minutes < 0:
# format_duration did not work for negative values anyway
# return a warning
return "NEGATIVE"
hours = minutes / 60
minutes = minutes % 60
formatted_duration = ""
if human:
if minutes % 60 == 0:
# duration in round hours
formatted_duration += ("%dh") % (hours)
elif hours == 0:
# duration less than hour
formatted_duration += ("%dmin") % (minutes % 60.0)
else:
# x hours, y minutes
formatted_duration += ("%dh %dmin") % (hours, minutes % 60)
else:
formatted_duration += "%02d:%02d" % (hours, minutes)
return formatted_duration
def format_range(start_date, end_date):
dates_dict = dateDict(start_date, "start_")
dates_dict.update(dateDict(end_date, "end_"))
if start_date == end_date:
# label of date range if looking on single day
# date format for overview label when only single day is visible
# Using python datetime formatting syntax. See:
# http://docs.python.org/library/time.html#time.strftime
title = start_date.strftime(("%B %d, %Y"))
elif start_date.year != end_date.year:
# label of date range if start and end years don't match
# letter after prefixes (start_, end_) is the one of
# standard python date formatting ones- you can use all of them
# see http://docs.python.org/library/time.html#time.strftime
title = ("%(start_B)s %(start_d)s, %(start_Y)s – %(end_B)s %(end_d)s, %(end_Y)s") % dates_dict
elif start_date.month != end_date.month:
# label of date range if start and end month do not match
# letter after prefixes (start_, end_) is the one of
# standard python date formatting ones- you can use all of them
# see http://docs.python.org/library/time.html#time.strftime
title = ("%(start_B)s %(start_d)s – %(end_B)s %(end_d)s, %(end_Y)s") % dates_dict
else:
# label of date range for interval in same month
# letter after prefixes (start_, end_) is the one of
# standard python date formatting ones- you can use all of them
# see http://docs.python.org/library/time.html#time.strftime
title = ("%(start_B)s %(start_d)s – %(end_d)s, %(end_Y)s") % dates_dict
return title
def week(view_date):
# aligns start and end date to week
start_date = view_date - dt.timedelta(view_date.weekday() + 1)
start_date = start_date + dt.timedelta(locale_first_weekday())
end_date = start_date + dt.timedelta(6)
return start_date, end_date
def month(view_date):
# aligns start and end date to month
start_date = view_date - dt.timedelta(view_date.day - 1) #set to beginning of month
first_weekday, days_in_month = calendar.monthrange(view_date.year, view_date.month)
end_date = start_date + dt.timedelta(days_in_month - 1)
return start_date, end_date
def duration_minutes(duration):
"""Returns minutes from duration, otherwise we keep bashing in same math.
Deprecated, use dt.timedelta.total_minutes instead.
"""
if isinstance(duration, dt.timedelta):
return duration.total_seconds() / 60
elif isinstance(duration, (int, float)):
return duration
elif isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
else:
raise NotImplementedError("received {}".format(type(duration)))
def zero_hour(date):
return dt.datetime.combine(date.date(), dt.time(0,0))
# it seems that python or something has bug of sorts, that breaks stuff for
# japanese locale, so we have this locale from and to ut8 magic in some places
# see bug 562298
def locale_from_utf8(utf8_str):
try:
retval = str (utf8_str, "utf-8").encode(locale.getpreferredencoding())
except:
retval = utf8_str
return retval
def locale_to_utf8(locale_str):
try:
retval = str (locale_str, locale.getpreferredencoding()).encode("utf-8")
except:
retval = locale_str
return retval
def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen("locale first_weekday week-1stday")
week_offset, week_start = process.read().split('\n')[:2]
process.close()
week_start = dt.date(*time.strptime(week_start, "%Y%m%d")[:3])
week_offset = dt.timedelta(int(week_offset) - 1)
beginning = week_start + week_offset
first_weekday = int(beginning.strftime("%w"))
except:
logger.warn("WARNING - Failed to get first weekday from locale")
return first_weekday
def totals(iter, keyfunc, sumfunc):
"""groups items by field described in keyfunc and counts totals using value
from sumfunc
"""
data = sorted(iter, key=keyfunc)
res = {}
for k, group in groupby(data, keyfunc):
res[k] = sum([sumfunc(entry) for entry in group])
return res
def dateDict(date, prefix = ""):
"""converts date into dictionary, having prefix for all the keys"""
res = {}
res[prefix+"a"] = date.strftime("%a")
res[prefix+"A"] = date.strftime("%A")
res[prefix+"b"] = date.strftime("%b")
res[prefix+"B"] = date.strftime("%B")
res[prefix+"c"] = date.strftime("%c")
res[prefix+"d"] = date.strftime("%d")
res[prefix+"H"] = date.strftime("%H")
res[prefix+"I"] = date.strftime("%I")
res[prefix+"j"] = date.strftime("%j")
res[prefix+"m"] = date.strftime("%m")
res[prefix+"M"] = date.strftime("%M")
res[prefix+"p"] = date.strftime("%p")
res[prefix+"S"] = date.strftime("%S")
res[prefix+"U"] = date.strftime("%U")
res[prefix+"w"] = date.strftime("%w")
res[prefix+"W"] = date.strftime("%W")
res[prefix+"x"] = date.strftime("%x")
res[prefix+"X"] = date.strftime("%X")
res[prefix+"y"] = date.strftime("%y")
res[prefix+"Y"] = date.strftime("%Y")
res[prefix+"Z"] = date.strftime("%Z")
for i, value in res.items():
res[i] = locale_to_utf8(value)
return res
def escape_pango(text):
if not text:
return text
text = text.replace ("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
return text
| 8,528 | Python | .py | 204 | 36.014706 | 102 | 0.659603 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,563 | graphics.py | projecthamster_hamster/src/hamster/lib/graphics.py | # - coding: utf-8 -
# Copyright (c) 2008-2012 Toms Bauģis <toms.baugis at gmail.com>
# Copyright (c) 2011-2012 Media Modifications, Ltd.
# Dual licensed under the MIT or GPL Version 2 licenses.
# See http://github.com/tbaugis/hamster_experiments/blob/master/README.textile
from collections import defaultdict
import math
import datetime as dt # need the original python granularity here
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import GObject as gobject
from gi.repository import Pango as pango
from gi.repository import PangoCairo as pangocairo
import cairo
from gi.repository import GdkPixbuf
import re
try:
from hamster.lib import pytweener
except: # we can also live without tweener. Scene.animate will not work
pytweener = None
import colorsys
from collections import deque
# lemme know if you know a better way how to get default font
_test_label = gtk.Label("Hello")
_font_desc = _test_label.get_style().font_desc.to_string()
class ColorUtils(object):
hex_color_normal = re.compile("#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})")
hex_color_short = re.compile("#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])")
hex_color_long = re.compile("#([a-fA-F0-9]{4})([a-fA-F0-9]{4})([a-fA-F0-9]{4})")
# d3 colors
category10 = ("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf")
category20 = ("#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c",
"#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5",
"#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f",
"#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5")
category20b = ("#393b79", "#5254a3", "#6b6ecf", "#9c9ede", "#637939",
"#8ca252", "#b5cf6b", "#cedb9c", "#8c6d31", "#bd9e39",
"#e7ba52", "#e7cb94", "#843c39", "#ad494a", "#d6616b",
"#e7969c", "#7b4173", "#a55194", "#ce6dbd", "#de9ed6")
category20c = ("#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d",
"#fd8d3c", "#fdae6b", "#fdd0a2", "#31a354", "#74c476",
"#a1d99b", "#c7e9c0", "#756bb1", "#9e9ac8", "#bcbddc",
"#dadaeb", "#636363", "#969696", "#bdbdbd", "#d9d9d9")
def parse(self, color):
"""parse string or a color tuple into color usable for cairo (all values
in the normalized (0..1) range"""
assert color is not None
#parse color into rgb values
if isinstance(color, str):
match = self.hex_color_long.match(color)
if match:
color = [int(color, 16) / 65535.0 for color in match.groups()]
else:
match = self.hex_color_normal.match(color)
if match:
color = [int(color, 16) / 255.0 for color in match.groups()]
else:
match = self.hex_color_short.match(color)
color = [int(color + color, 16) / 255.0 for color in match.groups()]
elif isinstance(color, gdk.Color):
color = [color.red / 65535.0,
color.green / 65535.0,
color.blue / 65535.0]
elif isinstance(color, (list, tuple)):
# otherwise we assume we have color components in 0..255 range
if color[0] > 1 or color[1] > 1 or color[2] > 1:
color = [c / 255.0 for c in color]
else:
color = [color.red, color.green, color.blue]
return color
def rgb(self, color):
"""returns rgb[a] tuple of the color with values in range 0.255"""
return [c * 255 for c in self.parse(color)]
def gdk(self, color):
"""returns gdk.Color object of the given color"""
c = self.parse(color)
return gdk.Color.from_floats(c)
def hex(self, color):
if isinstance(color, gdk.RGBA):
r = int(255 * color.red)
g = int(255 * color.green)
b = int(255 * color.blue)
a = int(255 * color.alpha)
return "#{:02x}{:02x}{:02x}{:02x}".format(r, g, b, a)
else:
c = self.parse(color)
return "#" + "".join("{:02x}".format(int(color) * 255) for color in c)
def is_light(self, color):
"""tells you if color is dark or light, so you can up or down the
scale for improved contrast"""
return colorsys.rgb_to_hls(*self.rgb(color))[1] > 150
def darker(self, color, step):
"""returns color darker by step (where step is in range 0..255)"""
hls = colorsys.rgb_to_hls(*self.rgb(color))
return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
def contrast(self, color, step):
"""if color is dark, will return a lighter one, otherwise darker"""
hls = colorsys.rgb_to_hls(*self.rgb(color))
if self.is_light(color):
return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
else:
return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2])
# returns color darker by step (where step is in range 0..255)
@classmethod
def mix(cls, ca, cb, xb):
"""Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS.
"""
r = (1 - xb) * ca.red + xb * cb.red
g = (1 - xb) * ca.green + xb * cb.green
b = (1 - xb) * ca.blue + xb * cb.blue
a = (1 - xb) * ca.alpha + xb * cb.alpha
return gdk.RGBA(red=r, green=g, blue=b, alpha=a)
Colors = ColorUtils() # this is a static class, so an instance will do
def get_gdk_rectangle(x, y, w, h):
rect = gdk.Rectangle()
rect.x, rect.y, rect.width, rect.height = x or 0, y or 0, w or 0, h or 0
return rect
def chain(*steps):
"""chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all callees accept on_complete named param.
The last item in the list can omit that.
XXX - figure out where to place these guys as they are quite useful
"""
if not steps:
return
def on_done(sprite=None):
chain(*steps[2:])
obj, params = steps[:2]
if len(steps) > 2:
params['on_complete'] = on_done
if callable(obj):
obj(**params)
else:
obj.animate(**params)
def full_pixels(space, data, gap_pixels=1):
"""returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful
"""
available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps
res = []
for i, val in enumerate(data):
# convert data to 0..1 scale so we deal with fractions
data_sum = sum(data[i:])
norm = val * 1.0 / data_sum
w = max(int(round(available * norm)), 1)
res.append(w)
available -= w
return res
class Graphics(object):
"""If context is given upon contruction, will perform drawing
operations on context instantly. Otherwise queues up the drawing
instructions and performs them in passed-in order when _draw is called
with context.
Most of instructions are mapped to cairo functions by the same name.
Where there are differences, documenation is provided.
See http://cairographics.org/documentation/pycairo/2/reference/context.html
for detailed description of the cairo drawing functions.
"""
__slots__ = ('context', 'extents', 'paths', '_last_matrix',
'__new_instructions', '__instruction_cache', 'cache_surface',
'_cache_layout')
colors = Colors # pointer to the color utilities instance
def __init__(self, context = None):
self.context = context
self.extents = None # bounds of the object, only if interactive
self.paths = None # paths for mouse hit checks
self._last_matrix = None
self.__new_instructions = [] # instruction set until it is converted into path-based instructions
self.__instruction_cache = []
self.cache_surface = None
self._cache_layout = None
def clear(self):
"""clear all instructions"""
self.__new_instructions = []
self.__instruction_cache = []
self.paths = []
def stroke(self, color=None, alpha=1):
if color or alpha < 1:
self.set_color(color, alpha)
self._add_instruction("stroke")
def fill(self, color = None, alpha = 1):
if color or alpha < 1:
self.set_color(color, alpha)
self._add_instruction("fill")
def mask(self, pattern):
self._add_instruction("mask", pattern)
def stroke_preserve(self, color = None, alpha = 1):
if color or alpha < 1:
self.set_color(color, alpha)
self._add_instruction("stroke_preserve")
def fill_preserve(self, color = None, alpha = 1):
if color or alpha < 1:
self.set_color(color, alpha)
self._add_instruction("fill_preserve")
def new_path(self):
self._add_instruction("new_path")
def paint(self):
self._add_instruction("paint")
def set_font_face(self, face):
self._add_instruction("set_font_face", face)
def set_font_size(self, size):
self._add_instruction("set_font_size", size)
def set_source(self, image, x = 0, y = 0):
self._add_instruction("set_source", image)
def set_source_surface(self, surface, x = 0, y = 0):
self._add_instruction("set_source_surface", surface, x, y)
def set_source_pixbuf(self, pixbuf, x = 0, y = 0):
self._add_instruction("set_source_pixbuf", pixbuf, x, y)
def save_context(self):
self._add_instruction("save")
def restore_context(self):
self._add_instruction("restore")
def clip(self):
self._add_instruction("clip")
def rotate(self, radians):
self._add_instruction("rotate", radians)
def translate(self, x, y):
self._add_instruction("translate", x, y)
def scale(self, x_factor, y_factor):
self._add_instruction("scale", x_factor, y_factor)
def move_to(self, x, y):
self._add_instruction("move_to", x, y)
def line_to(self, x, y = None):
if y is not None:
self._add_instruction("line_to", x, y)
elif isinstance(x, list) and y is None:
for x2, y2 in x:
self._add_instruction("line_to", x2, y2)
def rel_line_to(self, x, y = None):
if x is not None and y is not None:
self._add_instruction("rel_line_to", x, y)
elif isinstance(x, list) and y is None:
for x2, y2 in x:
self._add_instruction("rel_line_to", x2, y2)
def curve_to(self, x, y, x2, y2, x3, y3):
"""draw a curve. (x2, y2) is the middle point of the curve"""
self._add_instruction("curve_to", x, y, x2, y2, x3, y3)
def close_path(self):
self._add_instruction("close_path")
def set_line_style(self, width = None, dash = None, dash_offset = 0):
"""change width and dash of a line"""
if width is not None:
self._add_instruction("set_line_width", width)
if dash is not None:
self._add_instruction("set_dash", dash, dash_offset)
def _set_color(self, context, r, g, b, a):
"""the alpha has to changed based on the parent, so that happens at the
time of drawing"""
if a < 1:
context.set_source_rgba(r, g, b, a)
else:
context.set_source_rgb(r, g, b)
def set_color(self, color, alpha = 1):
"""set active color. You can use hex colors like "#aaa", or you can use
normalized RGB tripplets (where every value is in range 0..1), or
you can do the same thing in range 0..65535.
also consider skipping this operation and specify the color on stroke and
fill.
"""
color = self.colors.parse(color) # parse whatever we have there into a normalized triplet
if len(color) == 4 and alpha is None:
alpha = color[3]
r, g, b = color[:3]
self._add_instruction("set_color", r, g, b, alpha)
def arc(self, x, y, radius, start_angle, end_angle):
"""draw arc going counter-clockwise from start_angle to end_angle"""
self._add_instruction("arc", x, y, radius, start_angle, end_angle)
def circle(self, x, y, radius):
"""draw circle"""
self._add_instruction("arc", x, y, radius, 0, math.pi * 2)
def ellipse(self, x, y, width, height, edges = None):
"""draw 'perfect' ellipse, opposed to squashed circle. works also for
equilateral polygons"""
# the automatic edge case is somewhat arbitrary
steps = edges or max((32, width, height)) / 2
angle = 0
step = math.pi * 2 / steps
points = []
while angle < math.pi * 2:
points.append((width / 2.0 * math.cos(angle),
height / 2.0 * math.sin(angle)))
angle += step
min_x = min((point[0] for point in points))
min_y = min((point[1] for point in points))
self.move_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
for p_x, p_y in points:
self.line_to(p_x - min_x + x, p_y - min_y + y)
self.line_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
def arc_negative(self, x, y, radius, start_angle, end_angle):
"""draw arc going clockwise from start_angle to end_angle"""
self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle)
def triangle(self, x, y, width, height):
self.move_to(x, y)
self.line_to(width/2 + x, height + y)
self.line_to(width + x, y)
self.line_to(x, y)
def rectangle(self, x, y, width, height, corner_radius = 0):
"""draw a rectangle. if corner_radius is specified, will draw
rounded corners. corner_radius can be either a number or a tuple of
four items to specify individually each corner, starting from top-left
and going clockwise"""
if corner_radius <= 0:
self._add_instruction("rectangle", x, y, width, height)
return
# convert into 4 border and make sure that w + h are larger than 2 * corner_radius
if isinstance(corner_radius, (int, float)):
corner_radius = [corner_radius] * 4
corner_radius = [min(r, min(width, height) / 2) for r in corner_radius]
x2, y2 = x + width, y + height
self._rounded_rectangle(x, y, x2, y2, corner_radius)
def _rounded_rectangle(self, x, y, x2, y2, corner_radius):
if isinstance(corner_radius, (int, float)):
corner_radius = [corner_radius] * 4
self._add_instruction("move_to", x + corner_radius[0], y)
self._add_instruction("line_to", x2 - corner_radius[1], y)
self._add_instruction("curve_to", x2 - corner_radius[1] / 2, y, x2, y + corner_radius[1] / 2, x2, y + corner_radius[1])
self._add_instruction("line_to", x2, y2 - corner_radius[2])
self._add_instruction("curve_to", x2, y2 - corner_radius[2] / 2, x2 - corner_radius[2] / 2, y2, x2 - corner_radius[2], y2)
self._add_instruction("line_to", x + corner_radius[3], y2)
self._add_instruction("curve_to", x + corner_radius[3] / 2, y2, x, y2 - corner_radius[3] / 2, x, y2 - corner_radius[3])
self._add_instruction("line_to", x, y + corner_radius[0])
self._add_instruction("curve_to", x, y + corner_radius[0] / 2, x + corner_radius[0] / 2, y, x + corner_radius[0], y)
def hexagon(self, x, y, height):
side = height * 0.5
angle_x = side * 0.5
angle_y = side * 0.8660254
self.move_to(x, y)
self.line_to(x + side, y)
self.line_to(x + side + angle_x, y + angle_y)
self.line_to(x + side, y + 2*angle_y)
self.line_to(x, y + 2*angle_y)
self.line_to(x - angle_x, y + angle_y)
self.line_to(x, y)
self.close_path()
def fill_area(self, x, y, width, height, color, opacity = 1):
"""fill rectangular area with specified color"""
self.save_context()
self.rectangle(x, y, width, height)
self._add_instruction("clip")
self.rectangle(x, y, width, height)
self.fill(color, opacity)
self.restore_context()
def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None):
"""fill and stroke the drawn area in one go"""
if line_width: self.set_line_style(line_width)
if fill and stroke:
self.fill_preserve(fill, opacity)
elif fill:
self.fill(fill, opacity)
if stroke:
self.stroke(stroke)
def create_layout(self, size = None):
"""utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout"""
if not self.context:
# TODO - this is rather sloppy as far as exception goes
# should explain better
raise Exception("Can not create layout without existing context!")
layout = pangocairo.create_layout(self.context)
font_desc = pango.FontDescription(_font_desc)
if size: font_desc.set_absolute_size(size * pango.SCALE)
layout.set_font_description(font_desc)
return layout
def show_label(self, text, size = None, color = None, font_desc = None):
"""display text. unless font_desc is provided, will use system's default font"""
font_desc = pango.FontDescription(font_desc or _font_desc)
if color: self.set_color(color)
if size: font_desc.set_absolute_size(size * pango.SCALE)
self.show_layout(text, font_desc)
def show_text(self, text):
self._add_instruction("show_text", text)
def text_path(self, text):
"""this function is most likely to change"""
self._add_instruction("text_path", text)
def _show_layout(self, context, layout, text, font_desc, alignment, width, wrap,
ellipsize, single_paragraph_mode):
layout.set_font_description(font_desc)
layout.set_markup(text)
layout.set_width(int(width or -1))
layout.set_single_paragraph_mode(single_paragraph_mode)
if alignment is not None:
layout.set_alignment(alignment)
if width > 0:
if wrap is not None:
layout.set_wrap(wrap)
else:
layout.set_ellipsize(ellipsize or pango.EllipsizeMode.END)
pangocairo.show_layout(context, layout)
def show_layout(self, text, font_desc, alignment = pango.Alignment.LEFT,
width = -1, wrap = None, ellipsize = None,
single_paragraph_mode = False):
"""display text. font_desc is string of pango font description
often handier than calling this function directly, is to create
a class:Label object
"""
layout = self._cache_layout = self._cache_layout or pangocairo.create_layout(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)))
self._add_instruction("show_layout", layout, text, font_desc,
alignment, width, wrap, ellipsize, single_paragraph_mode)
def _add_instruction(self, function, *params):
if self.context:
if function == "set_color":
self._set_color(self.context, *params)
elif function == "show_layout":
self._show_layout(self.context, *params)
else:
getattr(self.context, function)(*params)
else:
self.paths = None
self.__new_instructions.append((function, params))
def _draw(self, context, opacity):
"""draw accumulated instructions in context"""
# if we have been moved around, we should update bounds
fresh_draw = len(self.__new_instructions or []) > 0
if fresh_draw: #new stuff!
self.paths = []
self.__instruction_cache = self.__new_instructions
self.__new_instructions = []
else:
if not self.__instruction_cache:
return
for instruction, args in self.__instruction_cache:
if fresh_draw:
if instruction in ("new_path", "stroke", "fill", "clip"):
self.paths.append((instruction, "path", context.copy_path()))
elif instruction in ("save", "restore", "translate", "scale", "rotate"):
self.paths.append((instruction, "transform", args))
if instruction == "set_color":
self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
elif instruction == "show_layout":
self._show_layout(context, *args)
elif opacity < 1 and instruction == "paint":
context.paint_with_alpha(opacity)
else:
getattr(context, instruction)(*args)
def _draw_as_bitmap(self, context, opacity):
"""
instead of caching paths, this function caches the whole drawn thing
use cache_as_bitmap on sprite to enable this mode
"""
matrix = context.get_matrix()
matrix_changed = matrix != self._last_matrix
new_instructions = self.__new_instructions is not None and len(self.__new_instructions) > 0
if not new_instructions and not matrix_changed:
context.save()
context.identity_matrix()
context.translate(self.extents.x, self.extents.y)
context.set_source_surface(self.cache_surface)
if opacity < 1:
context.paint_with_alpha(opacity)
else:
context.paint()
context.restore()
return
if new_instructions:
self.__instruction_cache = list(self.__new_instructions)
self.__new_instructions = deque()
self.paths = []
self.extents = None
if not self.__instruction_cache:
# no instructions - nothing to do
return
# instructions that end path
path_end_instructions = ("new_path", "clip", "stroke", "fill", "stroke_preserve", "fill_preserve")
# measure the path extents so we know the size of cache surface
# also to save some time use the context to paint for the first time
extents = gdk.Rectangle()
for instruction, args in self.__instruction_cache:
if instruction in path_end_instructions:
self.paths.append((instruction, "path", context.copy_path()))
exts = context.path_extents()
exts = get_gdk_rectangle(int(exts[0]), int(exts[1]),
int(exts[2]-exts[0]), int(exts[3]-exts[1]))
if extents.width and extents.height:
extents = gdk.rectangle_union(extents, exts)
else:
extents = exts
elif instruction in ("save", "restore", "translate", "scale", "rotate"):
self.paths.append((instruction, "transform", args))
if instruction in ("set_source_pixbuf", "set_source_surface"):
# draw a rectangle around the pathless instructions so that the extents are correct
pixbuf = args[0]
x = args[1] if len(args) > 1 else 0
y = args[2] if len(args) > 2 else 0
context.rectangle(x, y, pixbuf.get_width(), pixbuf.get_height())
context.clip()
if instruction == "paint" and opacity < 1:
context.paint_with_alpha(opacity)
elif instruction == "set_color":
self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
elif instruction == "show_layout":
self._show_layout(context, *args)
else:
getattr(context, instruction)(*args)
# avoid re-caching if we have just moved
just_transforms = new_instructions == False and \
matrix and self._last_matrix \
and all([matrix[i] == self._last_matrix[i] for i in range(4)])
# TODO - this does not look awfully safe
extents.x += matrix[4] - 5
extents.y += matrix[5] - 5
self.extents = extents
if not just_transforms:
# now draw the instructions on the caching surface
w = int(extents.width) + 10
h = int(extents.height) + 10
self.cache_surface = context.get_target().create_similar(cairo.CONTENT_COLOR_ALPHA, w, h)
ctx = cairo.Context(self.cache_surface)
ctx.translate(-extents.x, -extents.y)
ctx.transform(matrix)
for instruction, args in self.__instruction_cache:
if instruction == "set_color":
self._set_color(ctx, args[0], args[1], args[2], args[3])
elif instruction == "show_layout":
self._show_layout(ctx, *args)
else:
getattr(ctx, instruction)(*args)
self._last_matrix = matrix
class Parent(object):
"""shared functions across scene and sprite"""
def find(self, id):
"""breadth-first sprite search by ID"""
for sprite in self.sprites:
if sprite.id == id:
return sprite
for sprite in self.sprites:
found = sprite.find(id)
if found:
return found
def __getitem__(self, i):
return self.sprites[i]
def traverse(self, attr_name = None, attr_value = None):
"""traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute
"""
for sprite in self.sprites:
if (attr_name is None) or \
(attr_value is None and hasattr(sprite, attr_name)) or \
(attr_value is not None and getattr(sprite, attr_name, None) == attr_value):
yield sprite
for child in sprite.traverse(attr_name, attr_value):
yield child
def log(self, *lines):
"""will print out the lines in console if debug is enabled for the
specific sprite"""
if getattr(self, "debug", False):
print(dt.datetime.now().time(), end=' ')
for line in lines:
print(line, end=' ')
print()
def _add(self, sprite, index = None):
"""add one sprite at a time. used by add_child. split them up so that
it would be possible specify the index externally"""
if sprite == self:
raise Exception("trying to add sprite to itself")
if sprite.parent:
sprite.x, sprite.y = self.from_scene_coords(*sprite.to_scene_coords())
sprite.parent.remove_child(sprite)
if index is not None:
self.sprites.insert(index, sprite)
else:
self.sprites.append(sprite)
sprite.parent = self
def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)
def add_child(self, *sprites):
"""Add child sprite. Child will be nested within parent"""
for sprite in sprites:
self._add(sprite)
self._sort()
self.redraw()
def remove_child(self, *sprites):
"""Remove one or several :class:`Sprite` sprites from scene """
# first drop focus
scene = self.get_scene()
if scene:
child_sprites = list(self.all_child_sprites())
if scene._focus_sprite in child_sprites:
scene._focus_sprite = None
for sprite in sprites:
if sprite in self.sprites:
self.sprites.remove(sprite)
sprite._scene = None
sprite.parent = None
self.disconnect_child(sprite)
self._sort()
self.redraw()
def clear(self):
"""Remove all child sprites"""
self.remove_child(*self.sprites)
def destroy(self):
"""recursively removes all sprite children so that it is freed from
any references and can be garbage collected"""
for sprite in self.sprites:
sprite.destroy()
self.clear()
def all_child_sprites(self):
"""returns all child and grandchild sprites in a flat list"""
for sprite in self.sprites:
for child_sprite in sprite.all_child_sprites():
yield child_sprite
yield sprite
def get_mouse_sprites(self):
"""returns list of child sprites that the mouse can interact with.
by default returns all visible sprites, but override
to define your own rules"""
return (sprite for sprite in self._z_ordered_sprites if sprite.visible)
def connect_child(self, sprite, event, *args, **kwargs):
"""connect to a child event so that will disconnect if the child is
removed from this sprite. this is the recommended way to connect to
child events. syntax is same as for the .connect itself, just you
prepend the child sprite as the first element"""
handler = sprite.connect(event, *args, **kwargs)
self._child_handlers[sprite].append(handler)
return handler
def connect_child_after(self, sprite, event, *args, **kwargs):
"""connect to a child event so that will disconnect if the child is
removed from this sprite. this is the recommended way to connect to
child events. syntax is same as for the .connect itself, just you
prepend the child sprite as the first element"""
handler = sprite.connect_after(event, *args, **kwargs)
self._child_handlers[sprite].append(handler)
return handler
def disconnect_child(self, sprite, *handlers):
"""disconnects from child event. if handler is not specified, will
disconnect from all the child sprite events"""
handlers = handlers or self._child_handlers.get(sprite, [])
for handler in list(handlers):
if sprite.handler_is_connected(handler):
sprite.disconnect(handler)
if handler in self._child_handlers.get(sprite, []):
self._child_handlers[sprite].remove(handler)
if not self._child_handlers[sprite]:
del self._child_handlers[sprite]
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, getattr(self, "id", None) or str(id(self)))
class Sprite(Parent, gobject.GObject):
"""The Sprite class is a basic display list building block: a display list
node that can display graphics and can also contain children.
Once you have created the sprite, use Scene's add_child to add it to
scene
"""
__gsignals__ = {
"on-mouse-over": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"on-mouse-move": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-out": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"on-mouse-down": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-double-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-triple-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-up": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-scroll": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-drag-start": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-drag": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-drag-finish": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-focus": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"on-blur": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"on-key-press": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-key-release": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-render": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
transformation_attrs = set(('x', 'y', 'rotation', 'scale_x', 'scale_y', 'pivot_x', 'pivot_y'))
visibility_attrs = set(('opacity', 'visible', 'z_order'))
cache_attrs = set(('_stroke_context', '_matrix', '_prev_parent_matrix', '_scene'))
graphics_unrelated_attrs = set(('drag_x', 'drag_y', 'sprites', 'mouse_cursor', '_sprite_dirty', 'id'))
#: mouse-over cursor of the sprite. Can be either a gdk cursor
#: constants, or a pixbuf or a pixmap. If set to False, will be using
#: scene's cursor. in order to have the cursor displayed, the sprite has
#: to be interactive
mouse_cursor = None
#: whether the widget can gain focus
can_focus = None
def __init__(self, x = 0, y = 0, opacity = 1, visible = True, rotation = 0,
pivot_x = 0, pivot_y = 0, scale_x = 1, scale_y = 1,
interactive = False, draggable = False, z_order = 0,
mouse_cursor = None, cache_as_bitmap = False,
snap_to_pixel = True, debug = False, id = None,
can_focus = False):
gobject.GObject.__init__(self)
# a place where to store child handlers
self.__dict__['_child_handlers'] = defaultdict(list)
self._scene = None
self.debug = debug
self.id = id
#: list of children sprites. Use :func:`add_child` to add sprites
self.sprites = []
self._z_ordered_sprites = []
#: instance of :ref:`graphics` for this sprite
self.graphics = Graphics()
#: boolean denoting whether the sprite responds to mouse events
self.interactive = interactive
#: boolean marking if sprite can be automatically dragged
self.draggable = draggable
#: relative x coordinate of the sprites' rotation point
self.pivot_x = pivot_x
#: relative y coordinates of the sprites' rotation point
self.pivot_y = pivot_y
#: sprite opacity
self.opacity = opacity
#: boolean visibility flag
self.visible = visible
#: pointer to parent :class:`Sprite` or :class:`Scene`
self.parent = None
#: sprite coordinates
self.x, self.y = x, y
#: rotation of the sprite in radians (use :func:`math.degrees` to convert to degrees if necessary)
self.rotation = rotation
#: scale X
self.scale_x = scale_x
#: scale Y
self.scale_y = scale_y
#: drawing order between siblings. The one with the highest z_order will be on top.
self.z_order = z_order
#: x position of the cursor within mouse upon drag. change this value
#: in on-drag-start to adjust drag point
self.drag_x = 0
#: y position of the cursor within mouse upon drag. change this value
#: in on-drag-start to adjust drag point
self.drag_y = 0
#: Whether the sprite should be cached as a bitmap. Default: true
#: Generally good when you have many static sprites
self.cache_as_bitmap = cache_as_bitmap
#: Should the sprite coordinates always rounded to full pixel. Default: true
#: Mostly this is good for performance but in some cases that can lead
#: to rounding errors in positioning.
self.snap_to_pixel = snap_to_pixel
#: focus state
self.focused = False
if mouse_cursor is not None:
self.mouse_cursor = mouse_cursor
if can_focus is not None:
self.can_focus = can_focus
self.__dict__["_sprite_dirty"] = True # flag that indicates that the graphics object of the sprite should be rendered
self._matrix = None
self._prev_parent_matrix = None
self._stroke_context = None
self.connect("on-click", self.__on_click)
def __setattr__(self, name, val):
if isinstance(getattr(type(self), name, None), property) and \
getattr(type(self), name).fset is not None:
getattr(type(self), name).fset(self, val)
return
prev = self.__dict__.get(name, "hamster_graphics_no_value_really")
if type(prev) == type(val) and prev == val:
return
self.__dict__[name] = val
# prev parent matrix walks downwards
if name == '_prev_parent_matrix' and self.visible:
# downwards recursive invalidation of parent matrix
for sprite in self.sprites:
sprite._prev_parent_matrix = None
if name in self.cache_attrs or name in self.graphics_unrelated_attrs:
return
"""all the other changes influence cache vars"""
if name == 'visible' and self.visible == False:
# when transforms happen while sprite is invisible
for sprite in self.sprites:
sprite._prev_parent_matrix = None
# on moves invalidate our matrix, child extent cache (as that depends on our transforms)
# as well as our parent's child extents as we moved
# then go into children and invalidate the parent matrix down the tree
if name in self.transformation_attrs:
self._matrix = None
for sprite in self.sprites:
sprite._prev_parent_matrix = None
elif name not in self.visibility_attrs:
# if attribute is not in transformation nor visibility, we conclude
# that it must be causing the sprite needs re-rendering
self.__dict__["_sprite_dirty"] = True
# on parent change invalidate the matrix
if name == 'parent':
self._prev_parent_matrix = None
return
if name == 'opacity' and getattr(self, "cache_as_bitmap", None) and hasattr(self, "graphics"):
# invalidating cache for the bitmap version as that paints opacity in the image
self.graphics._last_matrix = None
if name == 'z_order' and getattr(self, "parent", None):
self.parent._sort()
self.redraw()
def _get_mouse_cursor(self):
"""Determine mouse cursor.
By default look for self.mouse_cursor is defined and take that.
Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for
interactive sprites. Defaults to scenes cursor.
"""
if self.mouse_cursor is not None:
return self.mouse_cursor
elif self.interactive and self.draggable:
return gdk.CursorType.FLEUR
elif self.interactive:
return gdk.CursorType.HAND2
def bring_to_front(self):
"""adjusts sprite's z-order so that the sprite is on top of it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1
def send_to_back(self):
"""adjusts sprite's z-order so that the sprite is behind it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[0].z_order - 1
def has_focus(self):
"""True if the sprite has the global input focus, False otherwise."""
scene = self.get_scene()
return scene and scene._focus_sprite == self
def grab_focus(self):
"""grab window's focus. Keyboard and scroll events will be forwarded
to the sprite who has the focus. Check the 'focused' property of sprite
in the on-render event to decide how to render it (say, add an outline
when focused=true)"""
scene = self.get_scene()
if scene and scene._focus_sprite != self:
scene._focus_sprite = self
def blur(self):
"""removes focus from the current element if it has it"""
scene = self.get_scene()
if scene and scene._focus_sprite == self:
scene._focus_sprite = None
def __on_click(self, sprite, event):
if self.interactive and self.can_focus:
self.grab_focus()
def get_parents(self):
"""returns all the parent sprites up until scene"""
res = []
parent = self.parent
while parent and isinstance(parent, Scene) == False:
res.insert(0, parent)
parent = parent.parent
return res
def get_extents(self):
"""measure the extents of the sprite's graphics."""
if self._sprite_dirty:
# redrawing merely because we need fresh extents of the sprite
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
context.transform(self.get_matrix())
self.emit("on-render")
self.__dict__["_sprite_dirty"] = False
self.graphics._draw(context, 1)
if not self.graphics.paths:
self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1)
if not self.graphics.paths:
return None
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
# bit of a hack around the problem - looking for clip instructions in parent
# so extents would not get out of it
clip_extents = None
for parent in self.get_parents():
context.transform(parent.get_local_matrix())
if parent.graphics.paths:
clip_regions = []
for instruction, type, path in parent.graphics.paths:
if instruction == "clip":
context.append_path(path)
context.save()
context.identity_matrix()
clip_regions.append(context.fill_extents())
context.restore()
context.new_path()
elif instruction == "restore" and clip_regions:
clip_regions.pop()
for ext in clip_regions:
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1]))
intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext)
context.transform(self.get_local_matrix())
for instruction, type, path in self.graphics.paths:
if type == "path":
context.append_path(path)
else:
getattr(context, instruction)(*path)
context.identity_matrix()
ext = context.path_extents()
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]),
int(ext[2] - ext[0]), int(ext[3] - ext[1]))
if clip_extents:
intersect, ext = gdk.rectangle_intersect(clip_extents, ext)
if not ext.width and not ext.height:
ext = None
self.__dict__['_stroke_context'] = context
return ext
def check_hit(self, x, y):
"""check if the given coordinates are inside the sprite's fill or stroke path"""
extents = self.get_extents()
if not extents:
return False
if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height:
return self._stroke_context is None or self._stroke_context.in_fill(x, y)
else:
return False
def get_scene(self):
"""returns class:`Scene` the sprite belongs to"""
if self._scene is None:
parent = getattr(self, "parent", None)
if parent:
self._scene = parent.get_scene()
return self._scene
def redraw(self):
"""queue redraw of the sprite. this function is called automatically
whenever a sprite attribute changes. sprite changes that happen
during scene redraw are ignored in order to avoid echoes.
Call scene.redraw() explicitly if you need to redraw in these cases.
"""
scene = self.get_scene()
if scene:
scene.redraw()
def animate(self, duration = None, easing = None, on_complete = None,
on_update = None, round = False, **kwargs):
"""Request parent Scene to Interpolate attributes using the internal tweener.
Specify sprite's attributes that need changing.
`duration` defaults to 0.4 seconds and `easing` to cubic in-out
(for others see pytweener.Easing class).
Example::
# tween some_sprite to coordinates (50,100) using default duration and easing
self.animate(x = 50, y = 100)
"""
scene = self.get_scene()
if scene:
return scene.animate(self, duration, easing, on_complete,
on_update, round, **kwargs)
else:
for key, val in kwargs.items():
setattr(self, key, val)
return None
def stop_animation(self):
"""stop animation without firing on_complete"""
scene = self.get_scene()
if scene:
scene.stop_animation(self)
def get_local_matrix(self):
if self._matrix is None:
matrix, x, y, pivot_x, pivot_y = cairo.Matrix(), self.x, self.y, self.pivot_x, self.pivot_y
if self.snap_to_pixel:
matrix.translate(int(x) + int(pivot_x), int(y) + int(pivot_y))
else:
matrix.translate(x + pivot_x, self.y + pivot_y)
if self.rotation:
matrix.rotate(self.rotation)
if self.snap_to_pixel:
matrix.translate(int(-pivot_x), int(-pivot_y))
else:
matrix.translate(-pivot_x, -pivot_y)
if self.scale_x != 1 or self.scale_y != 1:
matrix.scale(self.scale_x, self.scale_y)
self._matrix = matrix
return cairo.Matrix() * self._matrix
def get_matrix(self):
"""return sprite's current transformation matrix"""
if self.parent:
return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix())
else:
return self.get_local_matrix()
def from_scene_coords(self, x=0, y=0):
"""Converts x, y given in the scene coordinates to sprite's local ones
coordinates"""
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y)
def to_scene_coords(self, x=0, y=0):
"""Converts x, y from sprite's local coordinates to scene coordinates"""
return self.get_matrix().transform_point(x, y)
def _draw(self, context, opacity = 1, parent_matrix = None):
if self.visible is False:
return
if (self._sprite_dirty): # send signal to redo the drawing when sprite is dirty
self.emit("on-render")
self.__dict__["_sprite_dirty"] = False
no_matrix = parent_matrix is None
parent_matrix = parent_matrix or cairo.Matrix()
# cache parent matrix
self._prev_parent_matrix = parent_matrix
matrix = self.get_local_matrix()
context.save()
context.transform(matrix)
if self.cache_as_bitmap:
self.graphics._draw_as_bitmap(context, self.opacity * opacity)
else:
self.graphics._draw(context, self.opacity * opacity)
context.new_path() #forget about us
if self.debug:
exts = self.get_extents()
if exts:
debug_colors = ["#c17d11", "#73d216", "#3465a4",
"#75507b", "#cc0000", "#edd400", "#f57900"]
depth = len(self.get_parents())
color = debug_colors[depth % len(debug_colors)]
context.save()
context.identity_matrix()
scene = self.get_scene()
if scene:
# go figure - seems like the context we are given starts
# in window coords when calling identity matrix
scene_alloc = self.get_scene().get_allocation()
context.translate(scene_alloc.x, scene_alloc.y)
context.rectangle(exts.x, exts.y, exts.width, exts.height)
context.set_source_rgb(*Colors.parse(color))
context.stroke()
context.restore()
for sprite in self._z_ordered_sprites:
sprite._draw(context, self.opacity * opacity, matrix * parent_matrix)
context.restore()
# having parent and not being given parent matrix means that somebody
# is calling draw directly - avoid caching matrix for such a case
# because when we will get called properly it won't be respecting
# the parent's transformations otherwise
if isinstance(self.parent, Sprite) and no_matrix:
self._prev_parent_matrix = None
# using _do functions so that subclassees can override these
def _do_mouse_down(self, event): self.emit("on-mouse-down", event)
def _do_double_click(self, event): self.emit("on-double-click", event)
def _do_triple_click(self, event): self.emit("on-triple-click", event)
def _do_mouse_up(self, event): self.emit("on-mouse-up", event)
def _do_click(self, event): self.emit("on-click", event)
def _do_mouse_over(self): self.emit("on-mouse-over")
def _do_mouse_move(self, event): self.emit("on-mouse-move", event)
def _do_mouse_out(self): self.emit("on-mouse-out")
def _do_focus(self): self.emit("on-focus")
def _do_blur(self): self.emit("on-blur")
def _do_key_press(self, event):
self.emit("on-key-press", event)
return False
def _do_key_release(self, event):
self.emit("on-key-release", event)
return False
class BitmapSprite(Sprite):
"""Caches given image data in a surface similar to targets, which ensures
that drawing it will be quick and low on CPU.
Image data can be either :class:`cairo.ImageSurface` or :class:`GdkPixbuf.Pixbuf`
"""
def __init__(self, image_data = None, cache_mode = None, **kwargs):
Sprite.__init__(self, **kwargs)
self.width, self.height = 0, 0
self.cache_mode = cache_mode or cairo.CONTENT_COLOR_ALPHA
#: image data
self.image_data = image_data
self._surface = None
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if not self._surface:
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.new_path()
def update_surface_cache(self):
"""for efficiency the image data is cached on a surface similar to the
target one. so if you do custom drawing after setting the image data,
it won't be reflected as the sprite has no idea about what is going on
there. call this function to trigger cache refresh."""
self._surface = None
def __setattr__(self, name, val):
if self.__dict__.get(name, "hamster_graphics_no_value_really") == val:
return
Sprite.__setattr__(self, name, val)
if name == 'image_data':
self._surface = None
if self.image_data:
self.__dict__['width'] = self.image_data.get_width()
self.__dict__['height'] = self.image_data.get_height()
def _draw(self, context, opacity = 1, parent_matrix = None):
if self.image_data is None or self.width is None or self.height is None:
return
if not self._surface:
# caching image on surface similar to the target
surface = context.get_target().create_similar(self.cache_mode,
self.width,
self.height)
local_context = cairo.Context(surface)
if isinstance(self.image_data, GdkPixbuf.Pixbuf):
gdk.cairo_set_source_pixbuf(local_context, self.image_data, 0, 0)
else:
local_context.set_source_surface(self.image_data)
local_context.paint()
# add instructions with the resulting surface
self.graphics.clear()
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.clip()
self.graphics.set_source_surface(surface)
self.graphics.paint()
self.__dict__['_surface'] = surface
Sprite._draw(self, context, opacity, parent_matrix)
class Image(BitmapSprite):
"""Displays image by path. Currently supports only PNG images."""
def __init__(self, path, **kwargs):
BitmapSprite.__init__(self, **kwargs)
#: path to the image
self.path = path
def __setattr__(self, name, val):
BitmapSprite.__setattr__(self, name, val)
if name == 'path': # load when the value is set to avoid penalty on render
self.image_data = cairo.ImageSurface.create_from_png(self.path)
class Icon(BitmapSprite):
"""Displays icon by name and size in the theme"""
def __init__(self, name, size=24, **kwargs):
BitmapSprite.__init__(self, **kwargs)
self.theme = gtk.IconTheme.get_default()
#: icon name from theme
self.name = name
#: icon size in pixels
self.size = size
def __setattr__(self, name, val):
BitmapSprite.__setattr__(self, name, val)
if name in ('name', 'size'): # no other reason to discard cache than just on path change
if self.__dict__.get('name') and self.__dict__.get('size'):
self.image_data = self.theme.load_icon(self.name, self.size, 0)
else:
self.image_data = None
class Label(Sprite):
__gsignals__ = {
"on-change": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
cache_attrs = Sprite.cache_attrs | set(("_letter_sizes", "__surface", "_ascent", "_bounds_width", "_measures"))
def __init__(self, text = "", size = None, color = None,
alignment = pango.Alignment.LEFT, single_paragraph = False,
max_width = None, wrap = None, ellipsize = None, markup = "",
font_desc = None, **kwargs):
Sprite.__init__(self, **kwargs)
self.width, self.height = None, None
self._test_context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A8, 0, 0))
self._test_layout = pangocairo.create_layout(self._test_context)
#: absolute font size in pixels. this will execute set_absolute_size
#: instead of set_size, which is fractional
self.size = size
#: pango.FontDescription, defaults to system font
self.font_desc = pango.FontDescription(font_desc or _font_desc)
#: color of label either as hex string or an (r,g,b) tuple
self.color = color
self._bounds_width = None
#: wrapping method. Can be set to pango. [WRAP_WORD, WRAP_CHAR,
#: WRAP_WORD_CHAR]
self.wrap = wrap
#: Ellipsize mode. Can be set to pango.[EllipsizeMode.NONE,
#: EllipsizeMode.START, EllipsizeMode.MIDDLE, EllipsizeMode.END]
self.ellipsize = ellipsize
#: alignment. one of pango.[Alignment.LEFT, Alignment.RIGHT, Alignment.CENTER]
self.alignment = alignment
#: If setting is True, do not treat newlines and similar characters as
#: paragraph separators; instead, keep all text in a single paragraph,
#: and display a glyph for paragraph separator characters. Used when you
#: want to allow editing of newlines on a single text line.
#: Defaults to False
self.single_paragraph = single_paragraph
#: maximum width of the label in pixels. if specified, the label
#: will be wrapped or ellipsized depending on the wrap and ellpisize settings
self.max_width = max_width
self.__surface = None
#: label text. upon setting will replace markup
self.text = text
#: label contents marked up using pango markup. upon setting will replace text
self.markup = markup
self._measures = {}
self.connect("on-render", self.on_render)
self.graphics_unrelated_attrs = self.graphics_unrelated_attrs | set(("__surface", "_bounds_width", "_measures"))
def __setattr__(self, name, val):
if name == "font_desc":
if isinstance(val, str):
val = pango.FontDescription(val)
elif isinstance(val, pango.FontDescription):
val = val.copy()
if self.__dict__.get(name, "hamster_graphics_no_value_really") != val:
if name == "width" and val and self.__dict__.get('_bounds_width') and val * pango.SCALE == self.__dict__['_bounds_width']:
return
Sprite.__setattr__(self, name, val)
if name == "width":
# setting width means consumer wants to contrain the label
if val is None or val == -1:
self.__dict__['_bounds_width'] = None
else:
self.__dict__['_bounds_width'] = val * pango.SCALE
if name in ("width", "text", "markup", "size", "font_desc", "wrap", "ellipsize", "max_width"):
self._measures = {}
# avoid chicken and egg
if hasattr(self, "size") and (hasattr(self, "text") or hasattr(self, "markup")):
if self.size:
self.font_desc.set_absolute_size(self.size * pango.SCALE)
markup = getattr(self, "markup", "")
self.__dict__['width'], self.__dict__['height'] = self.measure(markup or getattr(self, "text", ""), escape = len(markup) == 0)
if name == 'text':
if val:
self.__dict__['markup'] = ""
self.emit('on-change')
elif name == 'markup':
if val:
self.__dict__['text'] = ""
self.emit('on-change')
def measure(self, text, escape = True, max_width = None):
"""measures given text with label's font and size.
returns width, height and ascent. Ascent's null in case if the label
does not have font face specified (and is thusly using pango)"""
if escape:
text = text.replace ("&", "&").replace("<", "<").replace(">", ">")
if (max_width, text) in self._measures:
return self._measures[(max_width, text)]
width, height = None, None
context = self._test_context
layout = self._test_layout
layout.set_font_description(self.font_desc)
layout.set_markup(text)
layout.set_single_paragraph_mode(self.single_paragraph)
if self.alignment:
layout.set_alignment(self.alignment)
if self.wrap is not None:
layout.set_wrap(self.wrap)
layout.set_ellipsize(pango.EllipsizeMode.NONE)
else:
layout.set_ellipsize(self.ellipsize or pango.EllipsizeMode.END)
if max_width is not None:
layout.set_width(max_width * pango.SCALE)
else:
if self.max_width:
max_width = self.max_width * pango.SCALE
layout.set_width(int(self._bounds_width or max_width or -1))
width, height = layout.get_pixel_size()
self._measures[(max_width, text)] = width, height
return self._measures[(max_width, text)]
def on_render(self, sprite):
if not self.text and not self.markup:
self.graphics.clear()
return
self.graphics.set_color(self.color)
rect_width = self.width
max_width = 0
if self.max_width:
max_width = self.max_width * pango.SCALE
# when max width is specified and we are told to align in center
# do that (the pango instruction takes care of aligning within
# the lines of the text)
if self.alignment == pango.Alignment.CENTER:
self.graphics.move_to(-(self.max_width - self.width)/2, 0)
bounds_width = max_width or self._bounds_width or -1
text = ""
if self.markup:
text = self.markup
else:
# otherwise escape pango
text = self.text.replace ("&", "&").replace("<", "<").replace(">", ">")
self.graphics.show_layout(text, self.font_desc,
self.alignment,
bounds_width,
self.wrap,
self.ellipsize,
self.single_paragraph)
if self._bounds_width:
rect_width = self._bounds_width / pango.SCALE
self.graphics.rectangle(0, 0, rect_width, self.height)
self.graphics.clip()
class Rectangle(Sprite):
def __init__(self, w, h, corner_radius = 0, fill = None, stroke = None, line_width = 1, **kwargs):
Sprite.__init__(self, **kwargs)
#: width
self.width = w
#: height
self.height = h
#: fill color
self.fill = fill
#: stroke color
self.stroke = stroke
#: stroke line width
self.line_width = line_width
#: corner radius. Set bigger than 0 for rounded corners
self.corner_radius = corner_radius
self.connect("on-render", self.on_render)
def on_render(self, sprite):
self.graphics.set_line_style(width = self.line_width)
self.graphics.rectangle(0, 0, self.width, self.height, self.corner_radius)
self.graphics.fill_stroke(self.fill, self.stroke, line_width = self.line_width)
class Polygon(Sprite):
def __init__(self, points, fill = None, stroke = None, line_width = 1, **kwargs):
Sprite.__init__(self, **kwargs)
#: list of (x,y) tuples that the line should go through. Polygon
#: will automatically close path.
self.points = points
#: fill color
self.fill = fill
#: stroke color
self.stroke = stroke
#: stroke line width
self.line_width = line_width
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if not self.points:
self.graphics.clear()
return
self.graphics.move_to(*self.points[0])
self.graphics.line_to(self.points)
if self.fill:
self.graphics.close_path()
self.graphics.fill_stroke(self.fill, self.stroke, line_width = self.line_width)
class Circle(Sprite):
def __init__(self, width, height, fill = None, stroke = None, line_width = 1, **kwargs):
Sprite.__init__(self, **kwargs)
#: circle width
self.width = width
#: circle height
self.height = height
#: fill color
self.fill = fill
#: stroke color
self.stroke = stroke
#: stroke line width
self.line_width = line_width
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if self.width == self.height:
radius = self.width / 2.0
self.graphics.circle(radius, radius, radius)
else:
self.graphics.ellipse(0, 0, self.width, self.height)
self.graphics.fill_stroke(self.fill, self.stroke, line_width = self.line_width)
class Scene(Parent, gtk.DrawingArea):
""" Drawing area for displaying sprites.
Add sprites to the Scene by calling :func:`add_child`.
Scene is descendant of `gtk.DrawingArea <http://www.pygtk.org/docs/pygtk/class-gtkdrawingarea.html>`_
and thus inherits all it's methods and everything.
"""
__gsignals__ = {
# "draw": "override",
# "configure_event": "override",
"on-first-frame": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )),
"on-enter-frame": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )),
"on-finish-frame": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )),
"on-resize": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, )),
"on-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
"on-drag": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
"on-drag-start": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
"on-drag-finish": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
"on-mouse-move": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-down": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-double-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-triple-click": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-up": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-over": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-out": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-mouse-scroll": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-key-press": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
"on-key-release": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
}
def __init__(self, interactive = True, framerate = 60,
background_color = None, scale = False, keep_aspect = True,
style_class=None):
gtk.DrawingArea.__init__(self)
self._style = self.get_style_context()
#: widget style. One of gtk.STYLE_CLASS_*. By default it's BACKGROUND
self.style_class = style_class or gtk.STYLE_CLASS_BACKGROUND
self._style.add_class(self.style_class) # so we know our colors
#: list of sprites in scene. use :func:`add_child` to add sprites
self.sprites = []
self._z_ordered_sprites = []
# a place where to store child handlers
self.__dict__['_child_handlers'] = defaultdict(list)
#: framerate of animation. This will limit how often call for
#: redraw will be performed (that is - not more often than the framerate). It will
#: also influence the smoothness of tweeners.
self.framerate = framerate
#: Scene width. Will be `None` until first expose (that is until first
#: on-enter-frame signal below).
self.width = None
#: Scene height. Will be `None` until first expose (that is until first
#: on-enter-frame signal below).
self.height = None
#: instance of :class:`pytweener.Tweener` that is used by
#: :func:`animate` function, but can be also accessed directly for advanced control.
self.tweener = False
if pytweener:
self.tweener = pytweener.Tweener(0.4, pytweener.Easing.Cubic.ease_in_out)
#: instance of :class:`ColorUtils` class for color parsing
self.colors = Colors
#: read only info about current framerate (frames per second)
self.fps = None # inner frames per second counter
self._window = None # scenes don't really get reparented
#: Last known x position of the mouse (set on expose event)
self.mouse_x = None
#: Last known y position of the mouse (set on expose event)
self.mouse_y = None
#: Background color of the scene. Use either a string with hex color or an RGB triplet.
self.background_color = background_color
#: Mouse cursor appearance.
#: Replace with your own cursor or set to False to have no cursor.
#: None will revert back the default behavior
self.mouse_cursor = None
#: in contrast to the mouse cursor, this one is merely a suggestion and
#: can be overidden by child sprites
self.default_mouse_cursor = None
self._blank_cursor = gdk.Cursor(gdk.CursorType.BLANK_CURSOR)
self.__previous_mouse_signal_time = None
#: Miminum distance in pixels for a drag to occur
self.drag_distance = 1
self._last_frame_time = None
self._mouse_sprite = None
self._drag_sprite = None
self._mouse_down_sprite = None
self.__drag_started = False
self.__drag_start_x, self.__drag_start_y = None, None
self._mouse_in = False
self.__last_cursor = None
self.__drawing_queued = False
#: When specified, upon window resize the content will be scaled
#: relative to original window size. Defaults to False.
self.scale = scale
#: Should the stage maintain aspect ratio upon scale if
#: :attr:`Scene.scale` is enabled. Defaults to true.
self.keep_aspect = keep_aspect
self._original_width, self._original_height = None, None
self._focus_sprite = None # our internal focus management
self.__last_mouse_move = None
self.connect("realize", self.__on_realize)
if interactive:
self.set_can_focus(True)
self.set_events(gdk.EventMask.POINTER_MOTION_MASK
| gdk.EventMask.LEAVE_NOTIFY_MASK | gdk.EventMask.ENTER_NOTIFY_MASK
| gdk.EventMask.BUTTON_PRESS_MASK | gdk.EventMask.BUTTON_RELEASE_MASK
| gdk.EventMask.SCROLL_MASK
| gdk.EventMask.KEY_PRESS_MASK)
self.connect("motion-notify-event", self.__on_mouse_move)
self.connect("enter-notify-event", self.__on_mouse_enter)
self.connect("leave-notify-event", self.__on_mouse_leave)
self.connect("button-press-event", self.__on_button_press)
self.connect("button-release-event", self.__on_button_release)
self.connect("scroll-event", self.__on_scroll)
self.connect("key-press-event", self.__on_key_press)
self.connect("key-release-event", self.__on_key_release)
def __setattr__(self, name, val):
if self.__dict__.get(name, "hamster_graphics_no_value_really") is val:
return
if name == '_focus_sprite':
prev_focus = getattr(self, '_focus_sprite', None)
if prev_focus:
prev_focus.focused = False
self.__dict__['_focus_sprite'] = val # drop cache to avoid echoes
prev_focus._do_blur()
if val:
val.focused = True
val._do_focus()
elif name == "style_class":
if hasattr(self, "style_class"):
self._style.remove_class(self.style_class)
self._style.add_class(val)
elif name == "background_color":
if val:
self.override_background_color(gtk.StateType.NORMAL,
gdk.RGBA(*Colors.parse(val)))
else:
self.override_background_color(gtk.StateType.NORMAL, None)
self.__dict__[name] = val
# these two mimic sprite functions so parent check can be avoided
def from_scene_coords(self, x, y): return x, y
def to_scene_coords(self, x, y): return x, y
def get_matrix(self): return cairo.Matrix()
def get_scene(self): return self
def animate(self, sprite, duration = None, easing = None, on_complete = None,
on_update = None, round = False, **kwargs):
"""Interpolate attributes of the given object using the internal tweener
and redrawing scene after every tweener update.
Specify the sprite and sprite's attributes that need changing.
`duration` defaults to 0.4 seconds and `easing` to cubic in-out
(for others see pytweener.Easing class).
Redraw is requested right after creating the animation.
Example::
# tween some_sprite to coordinates (50,100) using default duration and easing
scene.animate(some_sprite, x = 50, y = 100)
"""
if not self.tweener: # here we complain
raise Exception("pytweener was not found. Include it to enable animations")
tween = self.tweener.add_tween(sprite,
duration=duration,
easing=easing,
on_complete=on_complete,
on_update=on_update,
round=round,
**kwargs)
self.redraw()
return tween
def stop_animation(self, sprites):
"""stop animation without firing on_complete"""
if isinstance(sprites, list) is False:
sprites = [sprites]
for sprite in sprites:
self.tweener.kill_tweens(sprite)
def redraw(self):
"""Queue redraw. The redraw will be performed not more often than
the `framerate` allows"""
if self.__drawing_queued == False: #if we are moving, then there is a timeout somewhere already
self.__drawing_queued = True
self._last_frame_time = dt.datetime.now()
gobject.timeout_add(1000 / self.framerate, self.__redraw_loop)
def __redraw_loop(self):
"""loop until there is nothing more to tween"""
self.queue_draw() # this will trigger do_expose_event when the current events have been flushed
self.__drawing_queued = self.tweener and self.tweener.has_tweens()
return self.__drawing_queued
def do_draw(self, context):
if self.scale:
aspect_x = self.width / self._original_width
aspect_y = self.height / self._original_height
if self.keep_aspect:
aspect_x = aspect_y = min(aspect_x, aspect_y)
context.scale(aspect_x, aspect_y)
if self.fps is None:
self.emit("on-first-frame", context)
cursor, self.mouse_x, self.mouse_y, mods = self._window.get_pointer()
# update tweens
now = dt.datetime.now()
delta = (now - (self._last_frame_time or dt.datetime.now())).total_seconds()
self._last_frame_time = now
if self.tweener:
self.tweener.update(delta)
self.fps = 1 / delta
# start drawing
self.emit("on-enter-frame", context)
for sprite in self._z_ordered_sprites:
sprite._draw(context)
self.__check_mouse(self.mouse_x, self.mouse_y)
self.emit("on-finish-frame", context)
# reset the mouse signal time as redraw means we are good now
self.__previous_mouse_signal_time = None
def do_configure_event(self, event):
if self._original_width is None:
self._original_width = float(event.width)
self._original_height = float(event.height)
width, height = self.width, self.height
self.width, self.height = event.width, event.height
if width != event.width or height != event.height:
self.emit("on-resize", event) # so that sprites can listen to it
def all_mouse_sprites(self):
"""Returns flat list of the sprite tree for simplified iteration"""
def all_recursive(sprites):
if not sprites:
return
for sprite in sprites:
if sprite.visible:
yield sprite
for child in all_recursive(sprite.get_mouse_sprites()):
yield child
return all_recursive(self.get_mouse_sprites())
def get_sprite_at_position(self, x, y):
"""Returns the topmost visible interactive sprite for given coordinates"""
over = None
for sprite in self.all_mouse_sprites():
if sprite.interactive and sprite.check_hit(x, y):
over = sprite
return over
def __check_mouse(self, x, y):
if x is None or self._mouse_in == False:
return
cursor = None
over = None
if self.mouse_cursor is not None:
cursor = self.mouse_cursor
if cursor is None and self._drag_sprite:
drag_cursor = self._drag_sprite._get_mouse_cursor()
if drag_cursor:
cursor = drag_cursor
#check if we have a mouse over
if self._drag_sprite is None:
over = self.get_sprite_at_position(x, y)
if self._mouse_sprite and self._mouse_sprite != over:
self._mouse_sprite._do_mouse_out()
self.emit("on-mouse-out", self._mouse_sprite)
if over and cursor is None:
sprite_cursor = over._get_mouse_cursor()
if sprite_cursor:
cursor = sprite_cursor
if over and over != self._mouse_sprite:
over._do_mouse_over()
self.emit("on-mouse-over", over)
self._mouse_sprite = over
if cursor is None:
cursor = self.default_mouse_cursor or gdk.CursorType.ARROW # default
elif cursor is False:
cursor = self._blank_cursor
if self.__last_cursor is None or cursor != self.__last_cursor:
if isinstance(cursor, gdk.Cursor):
self._window.set_cursor(cursor)
else:
self._window.set_cursor(gdk.Cursor(cursor))
self.__last_cursor = cursor
""" mouse events """
def __on_mouse_move(self, scene, event):
if self.__last_mouse_move:
gobject.source_remove(self.__last_mouse_move)
self.__last_mouse_move = None
self.mouse_x, self.mouse_y = event.x, event.y
# don't emit mouse move signals more often than every 0.05 seconds
timeout = dt.timedelta(seconds=0.05)
if self.__previous_mouse_signal_time and dt.datetime.now() - self.__previous_mouse_signal_time < timeout:
self.__last_mouse_move = gobject.timeout_add((timeout - (dt.datetime.now() - self.__previous_mouse_signal_time)).microseconds / 1000,
self.__on_mouse_move,
scene,
event.copy())
return
state = event.state
if self._mouse_down_sprite and self._mouse_down_sprite.interactive \
and self._mouse_down_sprite.draggable and gdk.ModifierType.BUTTON1_MASK & event.state:
# dragging around
if not self.__drag_started:
drag_started = (self.__drag_start_x is not None and \
(self.__drag_start_x - event.x) ** 2 + \
(self.__drag_start_y - event.y) ** 2 > self.drag_distance ** 2)
if drag_started:
self._drag_sprite = self._mouse_down_sprite
self._mouse_down_sprite.emit("on-drag-start", event)
self.emit("on-drag-start", self._drag_sprite, event)
self.start_drag(self._drag_sprite, self.__drag_start_x, self.__drag_start_y)
else:
# avoid double mouse checks - the redraw will also check for mouse!
if not self.__drawing_queued:
self.__check_mouse(event.x, event.y)
if self._drag_sprite:
diff_x, diff_y = event.x - self.__drag_start_x, event.y - self.__drag_start_y
if isinstance(self._drag_sprite.parent, Sprite):
matrix = self._drag_sprite.parent.get_matrix()
matrix.invert()
diff_x, diff_y = matrix.transform_distance(diff_x, diff_y)
self._drag_sprite.x, self._drag_sprite.y = self._drag_sprite.drag_x + diff_x, self._drag_sprite.drag_y + diff_y
self._drag_sprite.emit("on-drag", event)
self.emit("on-drag", self._drag_sprite, event)
if self._mouse_sprite:
sprite_event = event.copy()
sprite_event.x, sprite_event.y = self._mouse_sprite.from_scene_coords(event.x, event.y)
self._mouse_sprite._do_mouse_move(sprite_event)
self.emit("on-mouse-move", event)
self.__previous_mouse_signal_time = dt.datetime.now()
def start_drag(self, sprite, cursor_x = None, cursor_y = None):
"""start dragging given sprite"""
cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y
self._mouse_down_sprite = self._drag_sprite = sprite
sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y
self.__drag_start_x, self.__drag_start_y = cursor_x, cursor_y
self.__drag_started = True
def __on_mouse_enter(self, scene, event):
self._mouse_in = True
def __on_mouse_leave(self, scene, event):
self._mouse_in = False
if self._mouse_sprite:
self._mouse_sprite._do_mouse_out()
self.emit("on-mouse-out", self._mouse_sprite)
self._mouse_sprite = None
def __on_button_press(self, scene, event):
target = self.get_sprite_at_position(event.x, event.y)
if not self.__drag_started:
self.__drag_start_x, self.__drag_start_y = event.x, event.y
self._mouse_down_sprite = target
# differentiate between the click count!
if event.type == gdk.EventType.BUTTON_PRESS:
self.emit("on-mouse-down", event)
if target:
target_event = event.copy()
target_event.x, target_event.y = target.from_scene_coords(event.x, event.y)
target._do_mouse_down(target_event)
else:
scene._focus_sprite = None # lose focus if mouse ends up nowhere
elif event.type == gdk.EventType._2BUTTON_PRESS:
self.emit("on-double-click", event)
if target:
target_event = event.copy()
target_event.x, target_event.y = target.from_scene_coords(event.x, event.y)
target._do_double_click(target_event)
elif event.type == gdk.EventType._3BUTTON_PRESS:
self.emit("on-triple-click", event)
if target:
target_event = event.copy()
target_event.x, target_event.y = target.from_scene_coords(event.x, event.y)
target._do_triple_click(target_event)
self.__check_mouse(event.x, event.y)
return True
def __on_button_release(self, scene, event):
target = self.get_sprite_at_position(event.x, event.y)
if target:
target._do_mouse_up(event)
self.emit("on-mouse-up", event)
# trying to not emit click and drag-finish at the same time
click = not self.__drag_started or (event.x - self.__drag_start_x) ** 2 + \
(event.y - self.__drag_start_y) ** 2 < self.drag_distance
if (click and self.__drag_started == False) or not self._drag_sprite:
if target and target == self._mouse_down_sprite:
target_event = event.copy()
target_event.x, target_event.y = target.from_scene_coords(event.x, event.y)
target._do_click(target_event)
self.emit("on-click", event, target)
self._mouse_down_sprite = None
self.__drag_started = False
self.__drag_start_x, self__drag_start_y = None, None
if self._drag_sprite:
self._drag_sprite.drag_x, self._drag_sprite.drag_y = None, None
drag_sprite, self._drag_sprite = self._drag_sprite, None
drag_sprite.emit("on-drag-finish", event)
self.emit("on-drag-finish", drag_sprite, event)
self.__check_mouse(event.x, event.y)
return True
def __on_realize(self, widget):
# Store as soon as available. Maybe for performance reasons,
# to avoid get_window() calls in __on_mouse_move ?
self._window = self.get_window()
def __on_scroll(self, scene, event):
target = self.get_sprite_at_position(event.x, event.y)
if target:
target.emit("on-mouse-scroll", event)
self.emit("on-mouse-scroll", event)
return True
def __on_key_press(self, scene, event):
handled = False
if self._focus_sprite:
handled = self._focus_sprite._do_key_press(event)
if not handled:
self.emit("on-key-press", event)
return True
def __on_key_release(self, scene, event):
handled = False
if self._focus_sprite:
handled = self._focus_sprite._do_key_release(event)
if not handled:
self.emit("on-key-release", event)
return True
| 86,442 | Python | .py | 1,728 | 38.863426 | 146 | 0.593542 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,564 | db.py | projecthamster_hamster/src/hamster/storage/db.py | # - coding: utf-8 -
# Copyright (C) 2007-2009, 2012, 2014 Toms Bauģis <toms.baugis at gmail.com>
# Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
"""separate file for database operations"""
import logging
logger = logging.getLogger(__name__) # noqa: E402
import os, time
import itertools
import sqlite3 as sqlite
from shutil import copy as copyfile
try:
from gi.repository import Gio as gio
except ImportError:
print("Could not import gio - requires pygobject. File monitoring will be disabled")
gio = None
import hamster
from hamster.lib import datetime as dt
from hamster.lib.configuration import conf
from hamster.lib.fact import Fact
from hamster.storage import storage
# note: "zero id means failure" is quite standard,
# and that kind of convention will be mandatory for the dbus interface
# (None cannot pass through an integer signature).
class Storage(storage.Storage):
con = None # Connection will be created on demand
def __init__(self, unsorted_localized="Unsorted", database_dir=None):
"""Database storage.
Args:
unsorted_localized (str):
Default Fact.category value for returned facts
that were without any category in the db.
This is kept mainly for compatibility reasons.
The recommended value is an empty string.
How to handle empty category is now left to the caller.
database_dir (path):
Directory holding the database file,
or None to use the default location.
Note: Zero id means failure.
Unsorted category id is hard-coded as -1
"""
storage.Storage.__init__(self)
self._unsorted_localized = unsorted_localized
self.__con = None
self.__cur = None
self.__last_etag = None
self.db_path = self.__init_db_file(database_dir)
logger.info("database: '{}'".format(self.db_path))
if gio:
# add file monitoring so the app does not have to be restarted
# when db file is rewritten
def on_db_file_change(monitor, gio_file, event_uri, event):
logger.debug(event)
if event == gio.FileMonitorEvent.CHANGES_DONE_HINT:
if gio_file.query_info(gio.FILE_ATTRIBUTE_ETAG_VALUE,
gio.FileQueryInfoFlags.NONE,
None).get_etag() == self.__last_etag:
# ours
logger.info("database updated")
return
elif event == gio.FileMonitorEvent.DELETED:
self.con = None
if event == gio.FileMonitorEvent.CHANGES_DONE_HINT:
logger.warning("DB file has been modified externally. Calling all stations")
self.dispatch_overwrite()
self.__database_file = gio.File.new_for_path(self.db_path)
self.__db_monitor = self.__database_file.monitor_file(gio.FileMonitorFlags.WATCH_MOUNTS, None)
self.__db_monitor.connect("changed", on_db_file_change)
self.run_fixtures()
def __init_db_file(self, database_dir):
from gi.repository import GLib
xdg_data_home = GLib.get_user_data_dir()
if not database_dir:
database_dir = os.path.join(xdg_data_home, 'hamster')
if not os.path.exists(database_dir):
os.makedirs(database_dir, 0o744)
db_path = os.path.join(database_dir, "hamster.db")
# check if we have a database at all
if not os.path.exists(db_path):
# handle pre-existing hamster-applet database
# try most recent directories first
# change from hamster-applet to hamster-time-tracker:
# 9f345e5e (2019-09-19)
old_dirs = ['hamster-time-tracker', 'hamster-applet']
for old_dir in old_dirs:
old_db_path = os.path.join(xdg_data_home, old_dir, 'hamster.db')
if os.path.exists(old_db_path):
logger.warning("Linking {} with {}".format(old_db_path, db_path))
os.link(old_db_path, db_path)
break
if not os.path.exists(db_path):
# make a copy of the empty template hamster.db
if hamster.installed:
from hamster import defs # only available when running installed
data_dir = os.path.join(defs.DATA_DIR, "hamster")
else:
# running from sources
module_dir = os.path.dirname(os.path.realpath(__file__))
if os.path.exists(os.path.join(module_dir, "data")):
# running as flask app. XXX - detangle
data_dir = os.path.join(module_dir, "data")
else:
# get ./data from ./src/hamster/storage/db.py (3 levels up)
data_dir = os.path.join(module_dir, '..', '..', '..', 'data')
logger.warning("Database not found in {} - installing default from {}!"
.format(db_path, data_dir))
copyfile(os.path.join(data_dir, 'hamster.db'), db_path)
#change also permissions - sometimes they are 444
os.chmod(db_path, 0o664)
db_path = os.path.realpath(db_path) # needed for file monitoring?
return db_path
def register_modification(self):
if gio:
# db.execute calls this so we know that we were the ones
# that modified the DB and no extra refesh is not needed
self.__last_etag = self.__database_file.query_info(gio.FILE_ATTRIBUTE_ETAG_VALUE,
gio.FileQueryInfoFlags.NONE,
None).get_etag()
#tags, here we come!
def __get_tags(self, only_autocomplete = False):
if only_autocomplete:
return self.fetchall("select * from tags where autocomplete != 'false' order by name")
else:
return self.fetchall("select * from tags order by name")
def __get_tag_ids(self, tags):
"""look up tags by their name. create if not found"""
db_tags = self.fetchall("select * from tags where name in (%s)"
% ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables
changes = False
# check if any of tags needs resurrection
set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] in (0, "false")]
if set_complete:
changes = True
self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete))
found_tags = [tag["name"] for tag in db_tags]
add = set(tags) - set(found_tags)
if add:
statement = "insert into tags(name) values(?)"
self.execute([statement] * len(add), [(tag,) for tag in add])
return self.__get_tag_ids(tags)[0], True # all done, recurse
else:
return db_tags, changes
def __update_autocomplete_tags(self, tags):
tags = [tag.strip() for tag in tags.split(",") if tag.strip()] # split by comma
#first we will create new ones
tags, changes = self.__get_tag_ids(tags)
tags = [tag["id"] for tag in tags]
#now we will find which ones are gone from the list
query = """
SELECT b.id as id, b.autocomplete, count(a.fact_id) as occurences
FROM tags b
LEFT JOIN fact_tags a on a.tag_id = b.id
WHERE b.id not in (%s)
GROUP BY b.id
""" % ",".join(["?"] * len(tags)) # bit of magic here - using sqlites bind variables
gone = self.fetchall(query, tags)
to_delete = [str(tag["id"]) for tag in gone if tag["occurences"] == 0]
to_uncomplete = [str(tag["id"]) for tag in gone
if tag["occurences"] > 0 and tag["autocomplete"] in (1, "true")]
if to_delete:
self.execute("delete from tags where id in (%s)" % ", ".join(to_delete))
if to_uncomplete:
self.execute("update tags set autocomplete='false' where id in (%s)" % ", ".join(to_uncomplete))
return changes or len(to_delete + to_uncomplete) > 0
def __get_categories(self):
return self.fetchall("SELECT id, name FROM categories ORDER BY lower(name)")
def __update_activity(self, id, name, category_id):
query = """
UPDATE activities
SET name = ?,
search_name = ?,
category_id = ?
WHERE id = ?
"""
self.execute(query, (name, name.lower(), category_id, id))
affected_ids = [res[0] for res in self.fetchall("select id from facts where activity_id = ?", (id,))]
self.__remove_index(affected_ids)
def __change_category(self, id, category_id):
"""Change the category of an activity.
If an activity already exists with the same name
in the target category,
make all relevant facts use this target activity.
Args:
id (int): id of the source activity
category_id (int): id of the target category
Returns:
boolean: whether the database was changed.
"""
# first check if we don't have an activity with same name before us
activity = self.fetchone("select name from activities where id = ?", (id, ))
existing_activity = self.__get_activity_by_name(activity['name'], category_id)
if existing_activity and id == existing_activity['id']: # we are already there, go home
return False
if existing_activity: #ooh, we have something here!
# first move all facts that belong to movable activity to the new one
update = """
UPDATE facts
SET activity_id = ?
WHERE activity_id = ?
"""
self.execute(update, (existing_activity['id'], id))
# and now get rid of our friend
self.__remove_activity(id)
else: #just moving
statement = """
UPDATE activities
SET category_id = ?
WHERE id = ?
"""
self.execute(statement, (category_id, id))
affected_ids = [res[0] for res in self.fetchall("select id from facts where activity_id = ?", (id,))]
if existing_activity:
affected_ids.extend([res[0] for res in self.fetchall("select id from facts where activity_id = ?", (existing_activity['id'],))])
self.__remove_index(affected_ids)
return True
def __add_category(self, name):
query = """
INSERT INTO categories (name, search_name)
VALUES (?, ?)
"""
self.execute(query, (name, name.lower()))
return self.__last_insert_rowid()
def __update_category(self, id, name):
if id > -1: # Update, and ignore unsorted, if that was somehow triggered
update = """
UPDATE categories
SET name = ?, search_name = ?
WHERE id = ?
"""
self.execute(update, (name, name.lower(), id))
affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]
self.__remove_index(affected_ids)
def __get_activity_by_name(self, name, category_id = None, resurrect = True):
"""Get most recent, preferably not deleted activity by it's name.
If category_id is None or 0, show all activities matching name.
Otherwise, filter on the specified category.
"""
if category_id:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
AND category_id = ?
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, category_id))
else:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM activities a
LEFT JOIN categories b ON category_id = b.id
WHERE lower(a.name) = lower(?)
ORDER BY a.deleted, a.id desc
LIMIT 1
"""
res = self.fetchone(query, (self._unsorted_localized, name, ))
if res:
keys = ('id', 'name', 'deleted', 'category')
res = dict([(key, res[key]) for key in keys])
res['deleted'] = res['deleted'] or False
# if the activity was marked as deleted, resurrect on first call
# and put in the unsorted category
if res['deleted'] and resurrect:
update = """
UPDATE activities
SET deleted = null, category_id = -1
WHERE id = ?
"""
self.execute(update, (res['id'], ))
return res
return None
def __get_category_id(self, name):
"""Return category id from its name.
0 means none found.
"""
if not name:
# Unsorted
return -1
query = """
SELECT id from categories
WHERE lower(name) = lower(?)
ORDER BY id desc
LIMIT 1
"""
res = self.fetchone(query, (name, ))
if res:
return res['id']
return 0
def _dbfact_to_libfact(self, db_fact):
"""Convert a db fact (coming from __group_facts) to Fact."""
return Fact(activity=db_fact["name"],
category=db_fact["category"],
description=db_fact["description"],
tags=db_fact["tags"],
start_time=db_fact["start_time"],
end_time=db_fact["end_time"],
id=db_fact["id"],
activity_id=db_fact["activity_id"])
def __get_fact(self, id):
query = """
SELECT a.id AS id,
a.start_time AS start_time,
a.end_time AS end_time,
a.description as description,
b.name AS name, b.id as activity_id,
coalesce(c.name, ?) as category, coalesce(c.id, -1) as category_id,
e.name as tag
FROM facts a
LEFT JOIN activities b ON a.activity_id = b.id
LEFT JOIN categories c ON b.category_id = c.id
LEFT JOIN fact_tags d ON d.fact_id = a.id
LEFT JOIN tags e ON e.id = d.tag_id
WHERE a.id = ?
ORDER BY e.name
"""
fact_rows = self.fetchall(query, (self._unsorted_localized, id))
assert len(fact_rows) > 0, "No fact with id {}".format(id)
dbfact = self.__group_tags(fact_rows)[0]
fact = self._dbfact_to_libfact(dbfact)
logger.info("got fact {}".format(fact))
return fact
def __group_tags(self, facts):
"""put the fact back together and move all the unique tags to an array"""
if not facts: return facts #be it None or whatever
grouped_facts = []
for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]):
fact_tags = list(fact_tags)
# first one is as good as the last one
grouped_fact = fact_tags[0]
# we need dict so we can modify it (sqlite.Row is read only)
# in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!)
keys = ["id", "start_time", "end_time", "description", "name",
"activity_id", "category", "tag"]
grouped_fact = dict([(key, grouped_fact[key]) for key in keys])
grouped_fact["tags"] = [ft["tag"] for ft in fact_tags if ft["tag"]]
grouped_facts.append(grouped_fact)
return grouped_facts
def __touch_fact(self, fact, end_time = None):
end_time = end_time or dt.datetime.now()
# tasks under one minute do not count
if end_time - fact.start_time < dt.timedelta(minutes = 1):
self.__remove_fact(fact.id)
else:
query = """
UPDATE facts
SET end_time = ?
WHERE id = ?
"""
self.execute(query, (end_time, fact.id))
def __squeeze_in(self, start_time):
""" tries to put task in the given date
if there are conflicts, we will only truncate the ongoing task
and replace it's end part with our activity """
# we are checking if our start time is in the middle of anything
# or maybe there is something after us - so we know to adjust end time
# in the latter case go only few hours ahead. everything else is madness, heh
query = """
SELECT a.*, b.name
FROM facts a
LEFT JOIN activities b on b.id = a.activity_id
WHERE ((start_time < ? and end_time > ?)
OR (start_time > ? and start_time < ? and end_time is null)
OR (start_time > ? and start_time < ?))
ORDER BY start_time
LIMIT 1
"""
fact = self.fetchone(query, (start_time, start_time,
start_time - dt.timedelta(hours = 12),
start_time, start_time,
start_time + dt.timedelta(hours = 12)))
end_time = None
if fact:
if start_time > fact["start_time"]:
#we are in middle of a fact - truncate it to our start
self.execute("UPDATE facts SET end_time=? WHERE id=?",
(start_time, fact["id"]))
else: #otherwise we have found a task that is after us
end_time = fact["start_time"]
return end_time
def __solve_overlaps(self, start_time, end_time):
"""finds facts that happen in given interval and shifts them to
make room for new fact
"""
if end_time is None or start_time is None:
return
# possible combinations and the OR clauses that catch them
# (the side of the number marks if it catches the end or start time)
# |----------------- NEW -----------------|
# |--- old --- 1| |2 --- old --- 1| |2 --- old ---|
# |3 ----------------------- big old ------------------------ 3|
query = """
SELECT a.*, b.name, c.name as category
FROM facts a
LEFT JOIN activities b on b.id = a.activity_id
LEFT JOIN categories c on b.category_id = c.id
WHERE (end_time > ? and end_time < ?)
OR (start_time > ? and start_time < ?)
OR (start_time < ? and end_time > ?)
ORDER BY start_time
"""
conflicts = self.fetchall(query, (start_time, end_time,
start_time, end_time,
start_time, end_time))
for fact in conflicts:
# fact is a sqlite.Row, indexable by column name
fact_end_time = fact["end_time"] or dt.datetime.now()
# won't eliminate as it is better to have overlapping entries than loosing data
if start_time < fact["start_time"] and end_time > fact_end_time:
continue
# split - truncate until beginning of new entry and create new activity for end
if fact["start_time"] < start_time < fact_end_time and \
fact["start_time"] < end_time < fact_end_time:
logger.info("splitting %s" % fact["name"])
# truncate until beginning of the new entry
self.execute("""UPDATE facts
SET end_time = ?
WHERE id = ?""", (start_time, fact["id"]))
fact_name = fact["name"]
# create new fact for the end
new_fact = Fact(activity=fact["name"],
category=fact["category"],
description=fact["description"],
start_time=end_time,
end_time=fact_end_time)
storage.Storage.check_fact(new_fact)
new_fact_id = self.__add_fact(new_fact)
# copy tags
tag_update = """INSERT INTO fact_tags(fact_id, tag_id)
SELECT ?, tag_id
FROM fact_tags
WHERE fact_id = ?"""
self.execute(tag_update, (new_fact_id, fact["id"])) #clone tags
# overlap start
elif start_time < fact["start_time"] < end_time:
logger.info("Overlapping start of %s" % fact["name"])
self.execute("UPDATE facts SET start_time=? WHERE id=?",
(end_time, fact["id"]))
# overlap end
elif start_time < fact_end_time < end_time:
logger.info("Overlapping end of %s" % fact["name"])
self.execute("UPDATE facts SET end_time=? WHERE id=?",
(start_time, fact["id"]))
def __add_fact(self, fact, temporary=False):
"""Add fact to database.
Args:
fact (Fact)
Returns:
int, the new fact id in the database (> 0) on success,
0 if nothing needed to be done
(e.g. if the same fact was already on-going),
note: a sanity check on the given fact is performed first,
that would raise an AssertionError.
Other errors would also be handled through exceptions.
"""
logger.info("adding fact {}".format(fact))
start_time = fact.start_time
end_time = fact.end_time
# get tags from database - this will create any missing tags too
tags = [(tag['id'], tag['name'], tag['autocomplete']) for tag in self.get_tag_ids(fact.tags)]
# now check if maybe there is also a category
category_id = self.__get_category_id(fact.category)
if not category_id:
category_id = self.__add_category(fact.category)
# try to find activity, resurrect if not temporary
activity_id = self.__get_activity_by_name(fact.activity,
category_id,
resurrect = not temporary)
if not activity_id:
activity_id = self.__add_activity(fact.activity,
category_id, temporary)
else:
activity_id = activity_id['id']
# if we are working on +/- current day - check the last_activity
if (dt.timedelta(days=-1) <= dt.datetime.now() - start_time <= dt.timedelta(days=1)):
# pull in previous facts
facts = self.__get_todays_facts()
previous = None
if facts and facts[-1].end_time is None:
previous = facts[-1]
if previous and previous.start_time <= start_time:
# check if maybe that is the same one, in that case no need to restart
if (previous.activity_id == activity_id
and set(previous.tags) == set([tag[1] for tag in tags])
and (previous.description or "") == (fact.description or "")
):
logger.info("same fact, already on-going, nothing to do")
return 0
# if no description is added
# see if maybe previous was too short to qualify as an activity
if (not previous.description
and 60 >= (start_time - previous.start_time).seconds >= 0
):
self.__remove_fact(previous.id)
# now that we removed the previous one, see if maybe the one
# before that is actually same as the one we want to start
# (glueing)
if len(facts) > 1 and 60 >= (start_time - facts[-2].end_time).seconds >= 0:
before = facts[-2]
if (before.activity_id == activity_id
and set(before.tags) == set([tag[1] for tag in tags])
):
# resume and return
update = """
UPDATE facts
SET end_time = null
WHERE id = ?
"""
self.execute(update, (before.id,))
return before.id
else:
# otherwise stop
update = """
UPDATE facts
SET end_time = ?
WHERE id = ?
"""
self.execute(update, (start_time, previous.id))
# done with the current activity, now we can solve overlaps
if not end_time:
end_time = self.__squeeze_in(start_time)
else:
self.__solve_overlaps(start_time, end_time)
# finally add the new entry
insert = """
INSERT INTO facts (activity_id, start_time, end_time, description)
VALUES (?, ?, ?, ?)
"""
self.execute(insert, (activity_id, start_time, end_time, fact.description))
fact_id = self.__last_insert_rowid()
#now link tags
insert = ["insert into fact_tags(fact_id, tag_id) values(?, ?)"] * len(tags)
params = [(fact_id, tag[0]) for tag in tags]
self.execute(insert, params)
self.__remove_index([fact_id])
logger.info("fact successfully added, with id #{}".format(fact_id))
return fact_id
def __last_insert_rowid(self):
return self.fetchone("SELECT last_insert_rowid();")[0] or 0
def __get_todays_facts(self):
return self.__get_facts(dt.Range.today())
def __get_facts(self, range, search_terms=""):
datetime_from = range.start
datetime_to = range.end
logger.info("searching for facts from {} to {}".format(datetime_from, datetime_to))
query = """
SELECT a.id AS id,
a.start_time AS start_time,
a.end_time AS end_time,
a.description as description,
b.name AS name, b.id as activity_id,
coalesce(c.name, ?) as category,
e.name as tag
FROM facts a
LEFT JOIN activities b ON a.activity_id = b.id
LEFT JOIN categories c ON b.category_id = c.id
LEFT JOIN fact_tags d ON d.fact_id = a.id
LEFT JOIN tags e ON e.id = d.tag_id
WHERE (a.end_time >= ? OR a.end_time IS NULL) AND a.start_time <= ?
"""
if search_terms:
# check if we need changes to the index
self.__check_index(datetime_from, datetime_to)
# flip the query around when it starts with "not "
reverse_search_terms = search_terms.lower().startswith("not ")
if reverse_search_terms:
search_terms = search_terms[4:]
search_terms = search_terms.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_').replace("'", "''")
query += """ AND a.id %s IN (SELECT id
FROM fact_index
WHERE fact_index MATCH '%s')""" % ('NOT' if reverse_search_terms else '',
search_terms)
query += " ORDER BY a.start_time, e.name"
fact_rows = self.fetchall(query, (self._unsorted_localized,
datetime_from,
datetime_to))
#first let's put all tags in an array
dbfacts = self.__group_tags(fact_rows)
# ignore old on-going facts
return [self._dbfact_to_libfact(dbfact) for dbfact in dbfacts
if dbfact["start_time"] >= datetime_from - dt.timedelta(days=30)]
def __remove_fact(self, fact_id):
logger.info("removing fact #{}".format(fact_id))
statements = ["DELETE FROM fact_tags where fact_id = ?",
"DELETE FROM facts where id = ?"]
self.execute(statements, [(fact_id,)] * 2)
self.__remove_index([fact_id])
def __get_category_activities(self, category_id):
"""returns list of activities, if category is specified, order by name
otherwise - by activity_order"""
query = """
SELECT a.id, a.name, a.category_id, b.name as category
FROM activities a
LEFT JOIN categories b on coalesce(b.id, -1) = a.category_id
WHERE category_id = ?
AND deleted is null
ORDER BY lower(a.name)
"""
return self.fetchall(query, (category_id, ))
def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase"""
query = """
SELECT a.name AS name, b.name AS category
FROM activities a
LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id
LEFT JOIN facts f ON a.id = f.activity_id
WHERE deleted IS NULL
AND a.search_name LIKE ? ESCAPE '\\'
GROUP BY a.id
ORDER BY max(f.start_time) DESC, lower(a.name)
LIMIT 50
"""
search = search.lower()
search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
activities = self.fetchall(query, ('%s%%' % search, ))
return activities
def __remove_activity(self, id):
""" check if we have any facts with this activity and behave accordingly
if there are facts - sets activity to deleted = True
else, just remove it"""
query = "select count(*) as count from facts where activity_id = ?"
bound_facts = self.fetchone(query, (id,))['count']
if bound_facts > 0:
self.execute("UPDATE activities SET deleted = 1 WHERE id = ?", (id,))
else:
self.execute("delete from activities where id = ?", (id,))
def __remove_category(self, id):
"""move all activities to unsorted and remove category"""
affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))]
update = "update activities set category_id = -1 where category_id = ?"
self.execute(update, (id, ))
self.execute("delete from categories where id = ?", (id, ))
self.__remove_index(affected_ids)
def __add_activity(self, name, category_id = None, temporary = False):
# first check that we don't have anything like that yet
activity = self.__get_activity_by_name(name, category_id)
if activity:
return activity['id']
#now do the create bit
category_id = category_id or -1
deleted = None
if temporary:
deleted = 1
query = """
INSERT INTO activities (name, search_name, category_id, deleted)
VALUES (?, ?, ?, ?)
"""
self.execute(query, (name, name.lower(), category_id, deleted))
return self.__last_insert_rowid()
def __remove_index(self, ids):
"""remove affected ids from the index"""
if not ids:
return
ids = ",".join((str(id) for id in ids))
logger.info("removing fact #{} from index".format(ids))
self.execute("DELETE FROM fact_index where id in (%s)" % ids)
def __check_index(self, start_date, end_date):
"""check if maybe index needs rebuilding in the time span"""
index_query = """SELECT id
FROM facts
WHERE (end_time >= ? OR end_time IS NULL)
AND start_time <= ?
AND id not in(select id from fact_index)"""
rebuild_ids = ",".join([str(res[0]) for res in self.fetchall(index_query, (start_date, end_date))])
if rebuild_ids:
query = """
SELECT a.id AS id,
a.start_time AS start_time,
a.end_time AS end_time,
a.description as description,
b.name AS name, b.id as activity_id,
coalesce(c.name, ?) as category,
e.name as tag
FROM facts a
LEFT JOIN activities b ON a.activity_id = b.id
LEFT JOIN categories c ON b.category_id = c.id
LEFT JOIN fact_tags d ON d.fact_id = a.id
LEFT JOIN tags e ON e.id = d.tag_id
WHERE a.id in (%s)
ORDER BY a.id
""" % rebuild_ids
dbfacts = self.__group_tags(self.fetchall(query, (self._unsorted_localized, )))
facts = [self._dbfact_to_libfact(dbfact) for dbfact in dbfacts]
insert = """INSERT INTO fact_index (id, name, category, description, tag)
VALUES (?, ?, ?, ?, ?)"""
params = [(fact.id, fact.activity, fact.category, fact.description, " ".join(fact.tags)) for fact in facts]
self.executemany(insert, params)
""" Here be dragons (lame connection/cursor wrappers) """
def get_connection(self):
if self.con is None:
self.con = sqlite.connect(self.db_path, detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
self.con.row_factory = sqlite.Row
return self.con
connection = property(get_connection, None)
def fetchall(self, query, params = None):
"""Execute query.
Returns:
list(sqlite.Row)
"""
con = self.connection
cur = con.cursor()
logger.debug("%s %s" % (query, params))
if params:
cur.execute(query, params)
else:
cur.execute(query)
res = cur.fetchall()
cur.close()
return res
def fetchone(self, query, params = None):
res = self.fetchall(query, params)
if res:
return res[0]
else:
return None
def execute(self, statement, params = ()):
"""
execute sql statement. optionally you can give multiple statements
to save on cursor creation and closure
"""
con = self.__con or self.connection
cur = self.__cur or con.cursor()
if isinstance(statement, list) == False: # we expect to receive instructions in list
statement = [statement]
params = [params]
for state, param in zip(statement, params):
logger.debug("%s %s" % (state, param))
cur.execute(state, param)
if not self.__con:
con.commit()
cur.close()
self.register_modification()
def executemany(self, statement, params = []):
con = self.__con or self.connection
cur = self.__cur or con.cursor()
logger.debug("%s %s" % (statement, params))
cur.executemany(statement, params)
if not self.__con:
con.commit()
cur.close()
self.register_modification()
def start_transaction(self):
# will give some hints to execute not to close or commit anything
self.__con = self.connection
self.__cur = self.__con.cursor()
def end_transaction(self):
self.__con.commit()
self.__cur.close()
self.__con, self.__cur = None, None
self.register_modification()
def run_fixtures(self):
self.start_transaction()
"""upgrade DB to hamster version"""
version = self.fetchone("SELECT version FROM version")["version"]
current_version = 9
if version < 8:
# working around sqlite's utf-f case sensitivity (bug 624438)
# more info: http://www.gsak.net/help/hs23820.htm
self.execute("ALTER TABLE activities ADD COLUMN search_name varchar2")
activities = self.fetchall("select * from activities")
statement = "update activities set search_name = ? where id = ?"
for activity in activities:
self.execute(statement, (activity['name'].lower(), activity['id']))
# same for categories
self.execute("ALTER TABLE categories ADD COLUMN search_name varchar2")
categories = self.fetchall("select * from categories")
statement = "update categories set search_name = ? where id = ?"
for category in categories:
self.execute(statement, (category['name'].lower(), category['id']))
if version < 9:
# adding full text search
self.execute("""CREATE VIRTUAL TABLE fact_index
USING fts3(id, name, category, description, tag)""")
# at the happy end, update version number
if version < current_version:
#lock down current version
self.execute("UPDATE version SET version = %d" % current_version)
print("updated database from version %d to %d" % (version, current_version))
self.end_transaction()
# datetime/sql conversions
DATETIME_LOCAL_FMT = "%Y-%m-%d %H:%M:%S"
def adapt_datetime(t):
"""Convert datetime t to the suitable sql representation."""
return t.isoformat(" ")
def convert_datetime(s):
"""Convert the sql timestamp to datetime.
s is in bytes.
"""
# convert s from bytes to utf-8, and keep only data up to seconds
# 10 chars for YYYY-MM-DD, 1 space, 8 chars for HH:MM:SS
# note: let's leave any further rounding to dt.datetime.
datetime_string = s.decode('utf-8')[0:19]
return dt.datetime.strptime(datetime_string, DATETIME_LOCAL_FMT)
sqlite.register_adapter(dt.datetime, adapt_datetime)
sqlite.register_converter("timestamp", convert_datetime)
| 40,987 | Python | .py | 817 | 35.504284 | 140 | 0.530881 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,565 | storage.py | projecthamster_hamster/src/hamster/storage/storage.py | # - coding: utf-8 -
# Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org>
# Copyright (C) 2007-2012 Toms Baugis <toms.baugis@gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Project Hamster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import logging
logger = logging.getLogger(__name__) # noqa: E402
from hamster.lib import datetime as dt
from textwrap import dedent
from hamster.lib.fact import Fact, FactError
class Storage(object):
"""Abstract storage.
Concrete instances should implement the required private methods,
such as __get_facts.
"""
def run_fixtures(self):
pass
# signals that are called upon changes
def tags_changed(self): pass
def facts_changed(self): pass
def activities_changed(self): pass
def dispatch_overwrite(self):
self.tags_changed()
self.facts_changed()
self.activities_changed()
# facts
@classmethod
def check_fact(cls, fact, default_day=None):
"""Check Fact validity for inclusion in the storage.
Raise FactError(message) on failure.
"""
if fact.start_time is None:
raise FactError("Missing start time")
if fact.end_time and (fact.delta < dt.timedelta(0)):
fixed_fact = Fact(start_time=fact.start_time,
end_time=fact.end_time + dt.timedelta(days=1))
suggested_range_str = fixed_fact.range.format(default_day=default_day)
# work around cyclic imports
from hamster.lib.configuration import conf
raise FactError(dedent(
"""\
Duration would be negative.
Working late ?
This happens when the activity crosses the
hamster day start time ({:%H:%M} from tracking settings).
Suggestion: move the end to the next day; the range would become:
{}
(in civil local time)
""".format(conf.day_start, suggested_range_str)
))
if not fact.activity:
raise FactError("Missing activity")
if ',' in fact.category:
raise FactError(dedent(
"""\
Forbidden comma in category: '{}'
Note: The description separator changed
from single comma to double comma ',,' (cf. PR #482).
""".format(fact.category)
))
def add_fact(self, fact, start_time=None, end_time=None, temporary=False):
"""Add fact.
fact: either a Fact instance or
a string that can be parsed through Fact.parse.
note: start_time and end_time are used only when fact is a string,
for backward compatibility.
Passing fact as a string is deprecated
and will be removed in a future version.
Parsing should be done in the caller.
"""
if isinstance(fact, str):
logger.info("Passing fact as a string is deprecated")
fact = Fact.parse(fact)
fact.start_time = start_time
fact.end_time = end_time
# better fail before opening the transaction
self.check_fact(fact)
self.start_transaction()
result = self.__add_fact(fact, temporary)
self.end_transaction()
if result:
self.facts_changed()
return result
def get_fact(self, fact_id):
"""Get fact by id. For output format see GetFacts"""
return self.__get_fact(fact_id)
def update_fact(self, fact_id, fact, start_time=None, end_time=None, temporary=False):
# to be removed once update facts use Fact directly.
if isinstance(fact, str):
fact = Fact.parse(fact)
fact = fact.copy(start_time=start_time, end_time=end_time)
# better fail before opening the transaction
self.check_fact(fact)
self.start_transaction()
self.__remove_fact(fact_id)
result = self.__add_fact(fact, temporary)
if not result:
logger.warning("failed to update fact {} ({})".format(fact_id, fact))
self.end_transaction()
if result:
self.facts_changed()
return result
def stop_tracking(self, end_time):
"""Stops tracking the current activity"""
facts = self.__get_todays_facts()
if facts and not facts[-1].end_time:
self.__touch_fact(facts[-1], end_time)
self.facts_changed()
def stop_or_restart_tracking(self):
"""Stops or restarts tracking the last activity"""
facts = self.__get_todays_facts()
if facts:
if facts[-1].end_time:
self.add_fact(facts[-1].copy(start_time=dt.datetime.now(),
end_time = None))
else:
self.__touch_fact(facts[-1], end_time=dt.datetime.now())
self.facts_changed()
def remove_fact(self, fact_id):
"""Remove fact from storage by it's ID"""
self.start_transaction()
fact = self.__get_fact(fact_id)
if fact:
self.__remove_fact(fact_id)
self.facts_changed()
self.end_transaction()
def get_facts(self, start, end=None, search_terms=""):
range = dt.Range.from_start_end(start, end)
return self.__get_facts(range, search_terms)
def get_todays_facts(self):
"""Gets facts of today, respecting hamster midnight. See GetFacts for
return info"""
return self.__get_todays_facts()
# categories
def add_category(self, name):
res = self.__add_category(name)
self.activities_changed()
return res
def get_category_id(self, category):
return self.__get_category_id(category)
def update_category(self, id, name):
self.__update_category(id, name)
self.activities_changed()
def remove_category(self, id):
self.__remove_category(id)
self.activities_changed()
def get_categories(self):
return self.__get_categories()
# activities
def add_activity(self, name, category_id = -1):
new_id = self.__add_activity(name, category_id)
self.activities_changed()
return new_id
def update_activity(self, id, name, category_id):
self.__update_activity(id, name, category_id)
self.activities_changed()
def remove_activity(self, id):
result = self.__remove_activity(id)
self.activities_changed()
return result
def get_category_activities(self, category_id = -1):
return self.__get_category_activities(category_id = category_id)
def get_activities(self, search = ""):
return self.__get_activities(search)
def change_category(self, id, category_id):
changed = self.__change_category(id, category_id)
if changed:
self.activities_changed()
return changed
def get_activity_by_name(self, activity, category_id, resurrect = True):
category_id = category_id or None
if activity:
return dict(self.__get_activity_by_name(activity, category_id, resurrect) or {})
else:
return {}
# tags
def get_tags(self, only_autocomplete):
return self.__get_tags(only_autocomplete)
def get_tag_ids(self, tags):
tags, new_added = self.__get_tag_ids(tags)
if new_added:
self.tags_changed()
return tags
def update_autocomplete_tags(self, tags):
changes = self.__update_autocomplete_tags(tags)
if changes:
self.tags_changed()
| 8,298 | Python | .py | 196 | 32.857143 | 92 | 0.618119 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,566 | Configure.py | projecthamster_hamster/waflib/Configure.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Configuration system
A :py:class:`waflib.Configure.ConfigurationContext` instance is created when ``waf configure`` is called, it is used to:
* create data dictionaries (ConfigSet instances)
* store the list of modules to import
* hold configuration routines such as ``find_program``, etc
"""
import os, re, shlex, shutil, sys, time, traceback
from waflib import ConfigSet, Utils, Options, Logs, Context, Build, Errors
WAF_CONFIG_LOG = 'config.log'
"""Name of the configuration log file"""
autoconfig = False
"""Execute the configuration automatically"""
conf_template = '''# project %(app)s configured on %(now)s by
# waf %(wafver)s (abi %(abi)s, python %(pyver)x on %(systype)s)
# using %(args)s
#'''
class ConfigurationContext(Context.Context):
'''configures the project'''
cmd = 'configure'
error_handlers = []
"""
Additional functions to handle configuration errors
"""
def __init__(self, **kw):
super(ConfigurationContext, self).__init__(**kw)
self.environ = dict(os.environ)
self.all_envs = {}
self.top_dir = None
self.out_dir = None
self.tools = [] # tools loaded in the configuration, and that will be loaded when building
self.hash = 0
self.files = []
self.tool_cache = []
self.setenv('')
def setenv(self, name, env=None):
"""
Set a new config set for conf.env. If a config set of that name already exists,
recall it without modification.
The name is the filename prefix to save to ``c4che/NAME_cache.py``, and it
is also used as *variants* by the build commands.
Though related to variants, whatever kind of data may be stored in the config set::
def configure(cfg):
cfg.env.ONE = 1
cfg.setenv('foo')
cfg.env.ONE = 2
def build(bld):
2 == bld.env_of_name('foo').ONE
:param name: name of the configuration set
:type name: string
:param env: ConfigSet to copy, or an empty ConfigSet is created
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
"""
if name not in self.all_envs or env:
if not env:
env = ConfigSet.ConfigSet()
self.prepare_env(env)
else:
env = env.derive()
self.all_envs[name] = env
self.variant = name
def get_env(self):
"""Getter for the env property"""
return self.all_envs[self.variant]
def set_env(self, val):
"""Setter for the env property"""
self.all_envs[self.variant] = val
env = property(get_env, set_env)
def init_dirs(self):
"""
Initialize the project directory and the build directory
"""
top = self.top_dir
if not top:
top = Options.options.top
if not top:
top = getattr(Context.g_module, Context.TOP, None)
if not top:
top = self.path.abspath()
top = os.path.abspath(top)
self.srcnode = (os.path.isabs(top) and self.root or self.path).find_dir(top)
assert(self.srcnode)
out = self.out_dir
if not out:
out = Options.options.out
if not out:
out = getattr(Context.g_module, Context.OUT, None)
if not out:
out = Options.lockfile.replace('.lock-waf_%s_' % sys.platform, '').replace('.lock-waf', '')
# someone can be messing with symlinks
out = os.path.realpath(out)
self.bldnode = (os.path.isabs(out) and self.root or self.path).make_node(out)
self.bldnode.mkdir()
if not os.path.isdir(self.bldnode.abspath()):
self.fatal('Could not create the build directory %s' % self.bldnode.abspath())
def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
self.init_dirs()
self.cachedir = self.bldnode.make_node(Build.CACHE_DIR)
self.cachedir.mkdir()
path = os.path.join(self.bldnode.abspath(), WAF_CONFIG_LOG)
self.logger = Logs.make_logger(path, 'cfg')
app = getattr(Context.g_module, 'APPNAME', '')
if app:
ver = getattr(Context.g_module, 'VERSION', '')
if ver:
app = "%s (%s)" % (app, ver)
params = {'now': time.ctime(), 'pyver': sys.hexversion, 'systype': sys.platform, 'args': " ".join(sys.argv), 'wafver': Context.WAFVERSION, 'abi': Context.ABI, 'app': app}
self.to_log(conf_template % params)
self.msg('Setting top to', self.srcnode.abspath())
self.msg('Setting out to', self.bldnode.abspath())
if id(self.srcnode) == id(self.bldnode):
Logs.warn('Setting top == out')
elif id(self.path) != id(self.srcnode):
if self.srcnode.is_child_of(self.path):
Logs.warn('Are you certain that you do not want to set top="." ?')
super(ConfigurationContext, self).execute()
self.store()
Context.top_dir = self.srcnode.abspath()
Context.out_dir = self.bldnode.abspath()
# this will write a configure lock so that subsequent builds will
# consider the current path as the root directory (see prepare_impl).
# to remove: use 'waf distclean'
env = ConfigSet.ConfigSet()
env.argv = sys.argv
env.options = Options.options.__dict__
env.config_cmd = self.cmd
env.run_dir = Context.run_dir
env.top_dir = Context.top_dir
env.out_dir = Context.out_dir
# conf.hash & conf.files hold wscript files paths and hash
# (used only by Configure.autoconfig)
env.hash = self.hash
env.files = self.files
env.environ = dict(self.environ)
env.launch_dir = Context.launch_dir
if not (self.env.NO_LOCK_IN_RUN or env.environ.get('NO_LOCK_IN_RUN') or getattr(Options.options, 'no_lock_in_run')):
env.store(os.path.join(Context.run_dir, Options.lockfile))
if not (self.env.NO_LOCK_IN_TOP or env.environ.get('NO_LOCK_IN_TOP') or getattr(Options.options, 'no_lock_in_top')):
env.store(os.path.join(Context.top_dir, Options.lockfile))
if not (self.env.NO_LOCK_IN_OUT or env.environ.get('NO_LOCK_IN_OUT') or getattr(Options.options, 'no_lock_in_out')):
env.store(os.path.join(Context.out_dir, Options.lockfile))
def prepare_env(self, env):
"""
Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env``
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:param env: a ConfigSet, usually ``conf.env``
"""
if not env.PREFIX:
if Options.options.prefix or Utils.is_win32:
env.PREFIX = Options.options.prefix
else:
env.PREFIX = '/'
if not env.BINDIR:
if Options.options.bindir:
env.BINDIR = Options.options.bindir
else:
env.BINDIR = Utils.subst_vars('${PREFIX}/bin', env)
if not env.LIBDIR:
if Options.options.libdir:
env.LIBDIR = Options.options.libdir
else:
env.LIBDIR = Utils.subst_vars('${PREFIX}/lib%s' % Utils.lib64(), env)
def store(self):
"""Save the config results into the cache file"""
n = self.cachedir.make_node('build.config.py')
n.write('version = 0x%x\ntools = %r\n' % (Context.HEXVERSION, self.tools))
if not self.all_envs:
self.fatal('nothing to store in the configuration context!')
for key in self.all_envs:
tmpenv = self.all_envs[key]
tmpenv.store(os.path.join(self.cachedir.abspath(), key + Build.CACHE_SUFFIX))
def load(self, tool_list, tooldir=None, funs=None, with_sys_path=True, cache=False):
"""
Load Waf tools, which will be imported whenever a build is started.
:param tool_list: waf tools to import
:type tool_list: list of string
:param tooldir: paths for the imports
:type tooldir: list of string
:param funs: functions to execute from the waf tools
:type funs: list of string
:param cache: whether to prevent the tool from running twice
:type cache: bool
"""
tools = Utils.to_list(tool_list)
if tooldir:
tooldir = Utils.to_list(tooldir)
for tool in tools:
# avoid loading the same tool more than once with the same functions
# used by composite projects
if cache:
mag = (tool, id(self.env), tooldir, funs)
if mag in self.tool_cache:
self.to_log('(tool %s is already loaded, skipping)' % tool)
continue
self.tool_cache.append(mag)
module = None
try:
module = Context.load_tool(tool, tooldir, ctx=self, with_sys_path=with_sys_path)
except ImportError as e:
self.fatal('Could not load the Waf tool %r from %r\n%s' % (tool, getattr(e, 'waf_sys_path', sys.path), e))
except Exception as e:
self.to_log('imp %r (%r & %r)' % (tool, tooldir, funs))
self.to_log(traceback.format_exc())
raise
if funs is not None:
self.eval_rules(funs)
else:
func = getattr(module, 'configure', None)
if func:
if type(func) is type(Utils.readf):
func(self)
else:
self.eval_rules(func)
self.tools.append({'tool':tool, 'tooldir':tooldir, 'funs':funs})
def post_recurse(self, node):
"""
Records the path and a hash of the scripts visited, see :py:meth:`waflib.Context.Context.post_recurse`
:param node: script
:type node: :py:class:`waflib.Node.Node`
"""
super(ConfigurationContext, self).post_recurse(node)
self.hash = Utils.h_list((self.hash, node.read('rb')))
self.files.append(node.abspath())
def eval_rules(self, rules):
"""
Execute configuration tests provided as list of functions to run
:param rules: list of configuration method names
:type rules: list of string
"""
self.rules = Utils.to_list(rules)
for x in self.rules:
f = getattr(self, x)
if not f:
self.fatal('No such configuration function %r' % x)
f()
def conf(f):
"""
Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
:py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
named 'mandatory' to disable the configuration errors::
def configure(conf):
conf.find_program('abc', mandatory=False)
:param f: method to bind
:type f: function
"""
def fun(*k, **kw):
mandatory = kw.pop('mandatory', True)
try:
return f(*k, **kw)
except Errors.ConfigurationError:
if mandatory:
raise
fun.__name__ = f.__name__
setattr(ConfigurationContext, f.__name__, fun)
setattr(Build.BuildContext, f.__name__, fun)
return f
@conf
def add_os_flags(self, var, dest=None, dup=False):
"""
Import operating system environment values into ``conf.env`` dict::
def configure(conf):
conf.add_os_flags('CFLAGS')
:param var: variable to use
:type var: string
:param dest: destination variable, by default the same as var
:type dest: string
:param dup: add the same set of flags again
:type dup: bool
"""
try:
flags = shlex.split(self.environ[var])
except KeyError:
return
if dup or ''.join(flags) not in ''.join(Utils.to_list(self.env[dest or var])):
self.env.append_value(dest or var, flags)
@conf
def cmd_to_list(self, cmd):
"""
Detect if a command is written in pseudo shell like ``ccache g++`` and return a list.
:param cmd: command
:type cmd: a string or a list of string
"""
if isinstance(cmd, str):
if os.path.isfile(cmd):
# do not take any risk
return [cmd]
if os.sep == '/':
return shlex.split(cmd)
else:
try:
return shlex.split(cmd, posix=False)
except TypeError:
# Python 2.5 on windows?
return shlex.split(cmd)
return cmd
@conf
def check_waf_version(self, mini='1.9.99', maxi='2.1.0', **kw):
"""
Raise a Configuration error if the Waf version does not strictly match the given bounds::
conf.check_waf_version(mini='1.9.99', maxi='2.1.0')
:type mini: number, tuple or string
:param mini: Minimum required version
:type maxi: number, tuple or string
:param maxi: Maximum allowed version
"""
self.start_msg('Checking for waf version in %s-%s' % (str(mini), str(maxi)), **kw)
ver = Context.HEXVERSION
if Utils.num2ver(mini) > ver:
self.fatal('waf version should be at least %r (%r found)' % (Utils.num2ver(mini), ver))
if Utils.num2ver(maxi) < ver:
self.fatal('waf version should be at most %r (%r found)' % (Utils.num2ver(maxi), ver))
self.end_msg('ok', **kw)
@conf
def find_file(self, filename, path_list=[]):
"""
Find a file in a list of paths
:param filename: name of the file to search for
:param path_list: list of directories to search
:return: the first matching filename; else a configuration exception is raised
"""
for n in Utils.to_list(filename):
for d in Utils.to_list(path_list):
p = os.path.expanduser(os.path.join(d, n))
if os.path.exists(p):
return p
self.fatal('Could not find %r' % filename)
@conf
def find_program(self, filename, **kw):
"""
Search for a program on the operating system
When var is used, you may set os.environ[var] to help find a specific program version, for example::
$ CC='ccache gcc' waf configure
:param path_list: paths to use for searching
:type param_list: list of string
:param var: store the result to conf.env[var] where var defaults to filename.upper() if not provided; the result is stored as a list of strings
:type var: string
:param value: obtain the program from the value passed exclusively
:type value: list or string (list is preferred)
:param exts: list of extensions for the binary (do not add an extension for portability)
:type exts: list of string
:param msg: name to display in the log, by default filename is used
:type msg: string
:param interpreter: interpreter for the program
:type interpreter: ConfigSet variable key
:raises: :py:class:`waflib.Errors.ConfigurationError`
"""
exts = kw.get('exts', Utils.is_win32 and '.exe,.com,.bat,.cmd' or ',.sh,.pl,.py')
environ = kw.get('environ', getattr(self, 'environ', os.environ))
ret = ''
filename = Utils.to_list(filename)
msg = kw.get('msg', ', '.join(filename))
var = kw.get('var', '')
if not var:
var = re.sub(r'\W', '_', filename[0].upper())
path_list = kw.get('path_list', '')
if path_list:
path_list = Utils.to_list(path_list)
else:
path_list = environ.get('PATH', '').split(os.pathsep)
if kw.get('value'):
# user-provided in command-line options and passed to find_program
ret = self.cmd_to_list(kw['value'])
elif environ.get(var):
# user-provided in the os environment
ret = self.cmd_to_list(environ[var])
elif self.env[var]:
# a default option in the wscript file
ret = self.cmd_to_list(self.env[var])
else:
if not ret:
ret = self.find_binary(filename, exts.split(','), path_list)
if not ret and Utils.winreg:
ret = Utils.get_registry_app_path(Utils.winreg.HKEY_CURRENT_USER, filename)
if not ret and Utils.winreg:
ret = Utils.get_registry_app_path(Utils.winreg.HKEY_LOCAL_MACHINE, filename)
ret = self.cmd_to_list(ret)
if ret:
if len(ret) == 1:
retmsg = ret[0]
else:
retmsg = ret
else:
retmsg = False
self.msg('Checking for program %r' % msg, retmsg, **kw)
if not kw.get('quiet'):
self.to_log('find program=%r paths=%r var=%r -> %r' % (filename, path_list, var, ret))
if not ret:
self.fatal(kw.get('errmsg', '') or 'Could not find the program %r' % filename)
interpreter = kw.get('interpreter')
if interpreter is None:
if not Utils.check_exe(ret[0], env=environ):
self.fatal('Program %r is not executable' % ret)
self.env[var] = ret
else:
self.env[var] = self.env[interpreter] + ret
return ret
@conf
def find_binary(self, filenames, exts, paths):
for f in filenames:
for ext in exts:
exe_name = f + ext
if os.path.isabs(exe_name):
if os.path.isfile(exe_name):
return exe_name
else:
for path in paths:
x = os.path.expanduser(os.path.join(path, exe_name))
if os.path.isfile(x):
return x
return None
@conf
def run_build(self, *k, **kw):
"""
Create a temporary build context to execute a build. A temporary reference to that build
context is kept on self.test_bld for debugging purposes.
The arguments to this function are passed to a single task generator for that build.
Only three parameters are mandatory:
:param features: features to pass to a task generator created in the build
:type features: list of string
:param compile_filename: file to create for the compilation (default: *test.c*)
:type compile_filename: string
:param code: input file contents
:type code: string
Though this function returns *0* by default, the build may bind attribute named *retval* on the
build context object to return a particular value. See :py:func:`waflib.Tools.c_config.test_exec_fun` for example.
The temporary builds creates a temporary folder; the name of that folder is calculated
by hashing input arguments to this function, with the exception of :py:class:`waflib.ConfigSet.ConfigSet`
objects which are used for both reading and writing values.
This function also features a cache which is disabled by default; that cache relies
on the hash value calculated as indicated above::
def options(opt):
opt.add_option('--confcache', dest='confcache', default=0,
action='count', help='Use a configuration cache')
And execute the configuration with the following command-line::
$ waf configure --confcache
"""
buf = []
for key in sorted(kw.keys()):
v = kw[key]
if isinstance(v, ConfigSet.ConfigSet):
# values are being written to, so they are excluded from contributing to the hash
continue
elif hasattr(v, '__call__'):
buf.append(Utils.h_fun(v))
else:
buf.append(str(v))
h = Utils.h_list(buf)
dir = self.bldnode.abspath() + os.sep + (not Utils.is_win32 and '.' or '') + 'conf_check_' + Utils.to_hex(h)
cachemode = kw.get('confcache', getattr(Options.options, 'confcache', None))
if not cachemode and os.path.exists(dir):
shutil.rmtree(dir)
try:
os.makedirs(dir)
except OSError:
pass
try:
os.stat(dir)
except OSError:
self.fatal('cannot use the configuration test folder %r' % dir)
if cachemode == 1:
try:
proj = ConfigSet.ConfigSet(os.path.join(dir, 'cache_run_build'))
except EnvironmentError:
pass
else:
ret = proj['cache_run_build']
if isinstance(ret, str) and ret.startswith('Test does not build'):
self.fatal(ret)
return ret
bdir = os.path.join(dir, 'testbuild')
if not os.path.exists(bdir):
os.makedirs(bdir)
cls_name = kw.get('run_build_cls') or getattr(self, 'run_build_cls', 'build')
self.test_bld = bld = Context.create_context(cls_name, top_dir=dir, out_dir=bdir)
bld.init_dirs()
bld.progress_bar = 0
bld.targets = '*'
bld.logger = self.logger
bld.all_envs.update(self.all_envs) # not really necessary
bld.env = kw['env']
bld.kw = kw
bld.conf = self
kw['build_fun'](bld)
ret = -1
try:
try:
bld.compile()
except Errors.WafError:
ret = 'Test does not build: %s' % traceback.format_exc()
self.fatal(ret)
else:
ret = getattr(bld, 'retval', 0)
finally:
if cachemode:
# cache the results each time
proj = ConfigSet.ConfigSet()
proj['cache_run_build'] = ret
proj.store(os.path.join(dir, 'cache_run_build'))
else:
shutil.rmtree(dir)
return ret
@conf
def ret_msg(self, msg, args):
if isinstance(msg, str):
return msg
return msg(args)
@conf
def test(self, *k, **kw):
if not 'env' in kw:
kw['env'] = self.env.derive()
# validate_c for example
if kw.get('validate'):
kw['validate'](kw)
self.start_msg(kw['msg'], **kw)
ret = None
try:
ret = self.run_build(*k, **kw)
except self.errors.ConfigurationError:
self.end_msg(kw['errmsg'], 'YELLOW', **kw)
if Logs.verbose > 1:
raise
else:
self.fatal('The configuration failed')
else:
kw['success'] = ret
if kw.get('post_check'):
ret = kw['post_check'](kw)
if ret:
self.end_msg(kw['errmsg'], 'YELLOW', **kw)
self.fatal('The configuration failed %r' % ret)
else:
self.end_msg(self.ret_msg(kw['okmsg'], kw), **kw)
return ret
| 19,197 | Python | .py | 539 | 32.519481 | 172 | 0.704439 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,567 | Logs.py | projecthamster_hamster/waflib/Logs.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
logging, colors, terminal width and pretty-print
"""
import os, re, traceback, sys
from waflib import Utils, ansiterm
if not os.environ.get('NOSYNC', False):
# synchronized output is nearly mandatory to prevent garbled output
if sys.stdout.isatty() and id(sys.stdout) == id(sys.__stdout__):
sys.stdout = ansiterm.AnsiTerm(sys.stdout)
if sys.stderr.isatty() and id(sys.stderr) == id(sys.__stderr__):
sys.stderr = ansiterm.AnsiTerm(sys.stderr)
# import the logging module after since it holds a reference on sys.stderr
# in case someone uses the root logger
import logging
LOG_FORMAT = os.environ.get('WAF_LOG_FORMAT', '%(asctime)s %(c1)s%(zone)s%(c2)s %(message)s')
HOUR_FORMAT = os.environ.get('WAF_HOUR_FORMAT', '%H:%M:%S')
zones = []
"""
See :py:class:`waflib.Logs.log_filter`
"""
verbose = 0
"""
Global verbosity level, see :py:func:`waflib.Logs.debug` and :py:func:`waflib.Logs.error`
"""
colors_lst = {
'USE' : True,
'BOLD' :'\x1b[01;1m',
'RED' :'\x1b[01;31m',
'GREEN' :'\x1b[32m',
'YELLOW':'\x1b[33m',
'PINK' :'\x1b[35m',
'BLUE' :'\x1b[01;34m',
'CYAN' :'\x1b[36m',
'GREY' :'\x1b[37m',
'NORMAL':'\x1b[0m',
'cursor_on' :'\x1b[?25h',
'cursor_off' :'\x1b[?25l',
}
indicator = '\r\x1b[K%s%s%s'
try:
unicode
except NameError:
unicode = None
def enable_colors(use):
"""
If *1* is given, then the system will perform a few verifications
before enabling colors, such as checking whether the interpreter
is running in a terminal. A value of zero will disable colors,
and a value above *1* will force colors.
:param use: whether to enable colors or not
:type use: integer
"""
if use == 1:
if not (sys.stderr.isatty() or sys.stdout.isatty()):
use = 0
if Utils.is_win32 and os.name != 'java':
term = os.environ.get('TERM', '') # has ansiterm
else:
term = os.environ.get('TERM', 'dumb')
if term in ('dumb', 'emacs'):
use = 0
if use >= 1:
os.environ['TERM'] = 'vt100'
colors_lst['USE'] = use
# If console packages are available, replace the dummy function with a real
# implementation
try:
get_term_cols = ansiterm.get_term_cols
except AttributeError:
def get_term_cols():
return 80
get_term_cols.__doc__ = """
Returns the console width in characters.
:return: the number of characters per line
:rtype: int
"""
def get_color(cl):
"""
Returns the ansi sequence corresponding to the given color name.
An empty string is returned when coloring is globally disabled.
:param cl: color name in capital letters
:type cl: string
"""
if colors_lst['USE']:
return colors_lst.get(cl, '')
return ''
class color_dict(object):
"""attribute-based color access, eg: colors.PINK"""
def __getattr__(self, a):
return get_color(a)
def __call__(self, a):
return get_color(a)
colors = color_dict()
re_log = re.compile(r'(\w+): (.*)', re.M)
class log_filter(logging.Filter):
"""
Waf logs are of the form 'name: message', and can be filtered by 'waf --zones=name'.
For example, the following::
from waflib import Logs
Logs.debug('test: here is a message')
Will be displayed only when executing::
$ waf --zones=test
"""
def __init__(self, name=''):
logging.Filter.__init__(self, name)
def filter(self, rec):
"""
Filters log records by zone and by logging level
:param rec: log entry
"""
rec.zone = rec.module
if rec.levelno >= logging.INFO:
return True
m = re_log.match(rec.msg)
if m:
rec.zone = m.group(1)
rec.msg = m.group(2)
if zones:
return getattr(rec, 'zone', '') in zones or '*' in zones
elif not verbose > 2:
return False
return True
class log_handler(logging.StreamHandler):
"""Dispatches messages to stderr/stdout depending on the severity level"""
def emit(self, record):
"""
Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override`
"""
# default implementation
try:
try:
self.stream = record.stream
except AttributeError:
if record.levelno >= logging.WARNING:
record.stream = self.stream = sys.stderr
else:
record.stream = self.stream = sys.stdout
self.emit_override(record)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except: # from the python library -_-
self.handleError(record)
def emit_override(self, record, **kw):
"""
Writes the log record to the desired stream (stderr/stdout)
"""
self.terminator = getattr(record, 'terminator', '\n')
stream = self.stream
if unicode:
# python2
msg = self.formatter.format(record)
fs = '%s' + self.terminator
try:
if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
fs = fs.decode(stream.encoding)
try:
stream.write(fs % msg)
except UnicodeEncodeError:
stream.write((fs % msg).encode(stream.encoding))
else:
stream.write(fs % msg)
except UnicodeError:
stream.write((fs % msg).encode('utf-8'))
else:
logging.StreamHandler.emit(self, record)
class formatter(logging.Formatter):
"""Simple log formatter which handles colors"""
def __init__(self):
logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT)
def format(self, rec):
"""
Formats records and adds colors as needed. The records do not get
a leading hour format if the logging level is above *INFO*.
"""
try:
msg = rec.msg.decode('utf-8')
except Exception:
msg = rec.msg
use = colors_lst['USE']
if (use == 1 and rec.stream.isatty()) or use == 2:
c1 = getattr(rec, 'c1', None)
if c1 is None:
c1 = ''
if rec.levelno >= logging.ERROR:
c1 = colors.RED
elif rec.levelno >= logging.WARNING:
c1 = colors.YELLOW
elif rec.levelno >= logging.INFO:
c1 = colors.GREEN
c2 = getattr(rec, 'c2', colors.NORMAL)
msg = '%s%s%s' % (c1, msg, c2)
else:
# remove single \r that make long lines in text files
# and other terminal commands
msg = re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))', '', msg)
if rec.levelno >= logging.INFO:
# the goal of this is to format without the leading "Logs, hour" prefix
if rec.args:
try:
return msg % rec.args
except UnicodeDecodeError:
return msg.encode('utf-8') % rec.args
return msg
rec.msg = msg
rec.c1 = colors.PINK
rec.c2 = colors.NORMAL
return logging.Formatter.format(self, rec)
log = None
"""global logger for Logs.debug, Logs.error, etc"""
def debug(*k, **kw):
"""
Wraps logging.debug and discards messages if the verbosity level :py:attr:`waflib.Logs.verbose` ≤ 0
"""
if verbose:
k = list(k)
k[0] = k[0].replace('\n', ' ')
log.debug(*k, **kw)
def error(*k, **kw):
"""
Wrap logging.errors, adds the stack trace when the verbosity level :py:attr:`waflib.Logs.verbose` ≥ 2
"""
log.error(*k, **kw)
if verbose > 2:
st = traceback.extract_stack()
if st:
st = st[:-1]
buf = []
for filename, lineno, name, line in st:
buf.append(' File %r, line %d, in %s' % (filename, lineno, name))
if line:
buf.append(' %s' % line.strip())
if buf:
log.error('\n'.join(buf))
def warn(*k, **kw):
"""
Wraps logging.warning
"""
log.warning(*k, **kw)
def info(*k, **kw):
"""
Wraps logging.info
"""
log.info(*k, **kw)
def init_log():
"""
Initializes the logger :py:attr:`waflib.Logs.log`
"""
global log
log = logging.getLogger('waflib')
log.handlers = []
log.filters = []
hdlr = log_handler()
hdlr.setFormatter(formatter())
log.addHandler(hdlr)
log.addFilter(log_filter())
log.setLevel(logging.DEBUG)
def make_logger(path, name):
"""
Creates a simple logger, which is often used to redirect the context command output::
from waflib import Logs
bld.logger = Logs.make_logger('test.log', 'build')
bld.check(header_name='sadlib.h', features='cxx cprogram', mandatory=False)
# have the file closed immediately
Logs.free_logger(bld.logger)
# stop logging
bld.logger = None
The method finalize() of the command will try to free the logger, if any
:param path: file name to write the log output to
:type path: string
:param name: logger name (loggers are reused)
:type name: string
"""
logger = logging.getLogger(name)
if sys.hexversion > 0x3000000:
encoding = sys.stdout.encoding
else:
encoding = None
hdlr = logging.FileHandler(path, 'w', encoding=encoding)
formatter = logging.Formatter('%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
return logger
def make_mem_logger(name, to_log, size=8192):
"""
Creates a memory logger to avoid writing concurrently to the main logger
"""
from logging.handlers import MemoryHandler
logger = logging.getLogger(name)
hdlr = MemoryHandler(size, target=to_log)
formatter = logging.Formatter('%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.memhandler = hdlr
logger.setLevel(logging.DEBUG)
return logger
def free_logger(logger):
"""
Frees the resources held by the loggers created through make_logger or make_mem_logger.
This is used for file cleanup and for handler removal (logger objects are re-used).
"""
try:
for x in logger.handlers:
x.close()
logger.removeHandler(x)
except Exception:
pass
def pprint(col, msg, label='', sep='\n'):
"""
Prints messages in color immediately on stderr::
from waflib import Logs
Logs.pprint('RED', 'Something bad just happened')
:param col: color name to use in :py:const:`Logs.colors_lst`
:type col: string
:param msg: message to display
:type msg: string or a value that can be printed by %s
:param label: a message to add after the colored output
:type label: string
:param sep: a string to append at the end (line separator)
:type sep: string
"""
info('%s%s%s %s', colors(col), msg, colors.NORMAL, label, extra={'terminator':sep})
| 9,755 | Python | .py | 326 | 27.153374 | 102 | 0.695058 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,568 | Node.py | projecthamster_hamster/waflib/Node.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Node: filesystem structure
#. Each file/folder is represented by exactly one node.
#. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc.
Unused class members can increase the `.wafpickle` file size sensibly.
#. Node objects should never be created directly, use
the methods :py:func:`Node.make_node` or :py:func:`Node.find_node` for the low-level operations
#. The methods :py:func:`Node.find_resource`, :py:func:`Node.find_dir` :py:func:`Node.find_or_declare` must be
used when a build context is present
#. Each instance of :py:class:`waflib.Context.Context` has a unique :py:class:`Node` subclass required for serialization.
(:py:class:`waflib.Node.Nod3`, see the :py:class:`waflib.Context.Context` initializer). A reference to the context
owning a node is held as *self.ctx*
"""
import os, re, sys, shutil
from waflib import Utils, Errors
exclude_regs = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/*.swp
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/BitKeeper
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzrignore
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/.arch-ids
**/{arch}
**/_darcs
**/_darcs/**
**/.intlcache
**/.DS_Store'''
"""
Ant patterns for files and folders to exclude while doing the
recursive traversal in :py:meth:`waflib.Node.Node.ant_glob`
"""
def ant_matcher(s, ignorecase):
reflags = re.I if ignorecase else 0
ret = []
for x in Utils.to_list(s):
x = x.replace('\\', '/').replace('//', '/')
if x.endswith('/'):
x += '**'
accu = []
for k in x.split('/'):
if k == '**':
accu.append(k)
else:
k = k.replace('.', '[.]').replace('*', '.*').replace('?', '.').replace('+', '\\+')
k = '^%s$' % k
try:
exp = re.compile(k, flags=reflags)
except Exception as e:
raise Errors.WafError('Invalid pattern: %s' % k, e)
else:
accu.append(exp)
ret.append(accu)
return ret
def ant_sub_filter(name, nn):
ret = []
for lst in nn:
if not lst:
pass
elif lst[0] == '**':
ret.append(lst)
if len(lst) > 1:
if lst[1].match(name):
ret.append(lst[2:])
else:
ret.append([])
elif lst[0].match(name):
ret.append(lst[1:])
return ret
def ant_sub_matcher(name, pats):
nacc = ant_sub_filter(name, pats[0])
nrej = ant_sub_filter(name, pats[1])
if [] in nrej:
nacc = []
return [nacc, nrej]
class Node(object):
"""
This class is organized in two parts:
* The basic methods meant for filesystem access (compute paths, create folders, etc)
* The methods bound to a :py:class:`waflib.Build.BuildContext` (require ``bld.srcnode`` and ``bld.bldnode``)
"""
dict_class = dict
"""
Subclasses can provide a dict class to enable case insensitivity for example.
"""
__slots__ = ('name', 'parent', 'children', 'cache_abspath', 'cache_isdir')
def __init__(self, name, parent):
"""
.. note:: Use :py:func:`Node.make_node` or :py:func:`Node.find_node` instead of calling this constructor
"""
self.name = name
self.parent = parent
if parent:
if name in parent.children:
raise Errors.WafError('node %s exists in the parent files %r already' % (name, parent))
parent.children[name] = self
def __setstate__(self, data):
"Deserializes node information, used for persistence"
self.name = data[0]
self.parent = data[1]
if data[2] is not None:
# Issue 1480
self.children = self.dict_class(data[2])
def __getstate__(self):
"Serializes node information, used for persistence"
return (self.name, self.parent, getattr(self, 'children', None))
def __str__(self):
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
return self.abspath()
def __repr__(self):
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
return self.abspath()
def __copy__(self):
"""
Provided to prevent nodes from being copied
:raises: :py:class:`waflib.Errors.WafError`
"""
raise Errors.WafError('nodes are not supposed to be copied')
def read(self, flags='r', encoding='latin-1'):
"""
Reads and returns the contents of the file represented by this node, see :py:func:`waflib.Utils.readf`::
def build(bld):
bld.path.find_node('wscript').read()
:param flags: Open mode
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
:rtype: string or bytes
:return: File contents
"""
return Utils.readf(self.abspath(), flags, encoding)
def write(self, data, flags='w', encoding='latin-1'):
"""
Writes data to the file represented by this node, see :py:func:`waflib.Utils.writef`::
def build(bld):
bld.path.make_node('foo.txt').write('Hello, world!')
:param data: data to write
:type data: string
:param flags: Write mode
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
"""
Utils.writef(self.abspath(), data, flags, encoding)
def read_json(self, convert=True, encoding='utf-8'):
"""
Reads and parses the contents of this node as JSON (Python ≥ 2.6)::
def build(bld):
bld.path.find_node('abc.json').read_json()
Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does.
:type convert: boolean
:param convert: Prevents decoding of unicode strings on Python2
:type encoding: string
:param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard
:rtype: object
:return: Parsed file contents
"""
import json # Python 2.6 and up
object_pairs_hook = None
if convert and sys.hexversion < 0x3000000:
try:
_type = unicode
except NameError:
_type = str
def convert(value):
if isinstance(value, list):
return [convert(element) for element in value]
elif isinstance(value, _type):
return str(value)
else:
return value
def object_pairs(pairs):
return dict((str(pair[0]), convert(pair[1])) for pair in pairs)
object_pairs_hook = object_pairs
return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook)
def write_json(self, data, pretty=True):
"""
Writes a python object as JSON to disk (Python ≥ 2.6) as UTF-8 data (JSON standard)::
def build(bld):
bld.path.find_node('xyz.json').write_json(199)
:type data: object
:param data: The data to write to disk
:type pretty: boolean
:param pretty: Determines if the JSON will be nicely space separated
"""
import json # Python 2.6 and up
indent = 2
separators = (',', ': ')
sort_keys = pretty
newline = os.linesep
if not pretty:
indent = None
separators = (',', ':')
newline = ''
output = json.dumps(data, indent=indent, separators=separators, sort_keys=sort_keys) + newline
self.write(output, encoding='utf-8')
def exists(self):
"""
Returns whether the Node is present on the filesystem
:rtype: bool
"""
return os.path.exists(self.abspath())
def isdir(self):
"""
Returns whether the Node represents a folder
:rtype: bool
"""
return os.path.isdir(self.abspath())
def chmod(self, val):
"""
Changes the file/dir permissions::
def build(bld):
bld.path.chmod(493) # 0755
"""
os.chmod(self.abspath(), val)
def delete(self, evict=True):
"""
Removes the file/folder from the filesystem (equivalent to `rm -rf`), and remove this object from the Node tree.
Do not use this object after calling this method.
"""
try:
try:
if os.path.isdir(self.abspath()):
shutil.rmtree(self.abspath())
else:
os.remove(self.abspath())
except OSError:
if os.path.exists(self.abspath()):
raise
finally:
if evict:
self.evict()
def evict(self):
"""
Removes this node from the Node tree
"""
del self.parent.children[self.name]
def suffix(self):
"""
Returns the file rightmost extension, for example `a.b.c.d → .d`
:rtype: string
"""
k = max(0, self.name.rfind('.'))
return self.name[k:]
def height(self):
"""
Returns the depth in the folder hierarchy from the filesystem root or from all the file drives
:returns: filesystem depth
:rtype: integer
"""
d = self
val = -1
while d:
d = d.parent
val += 1
return val
def listdir(self):
"""
Lists the folder contents
:returns: list of file/folder names ordered alphabetically
:rtype: list of string
"""
lst = Utils.listdir(self.abspath())
lst.sort()
return lst
def mkdir(self):
"""
Creates a folder represented by this node. Intermediate folders are created as needed.
:raises: :py:class:`waflib.Errors.WafError` when the folder is missing
"""
if self.isdir():
return
try:
self.parent.mkdir()
except OSError:
pass
if self.name:
try:
os.makedirs(self.abspath())
except OSError:
pass
if not self.isdir():
raise Errors.WafError('Could not create the directory %r' % self)
try:
self.children
except AttributeError:
self.children = self.dict_class()
def find_node(self, lst):
"""
Finds a node on the file system (files or folders), and creates the corresponding Node objects if it exists
:param lst: relative path
:type lst: string or list of string
:returns: The corresponding Node object or None if no entry was found on the filesystem
:rtype: :py:class:´waflib.Node.Node´
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
if lst and lst[0].startswith('\\\\') and not self.parent:
node = self.ctx.root.make_node(lst[0])
node.cache_isdir = True
return node.find_node(lst[1:])
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
ch = cur.children
except AttributeError:
cur.children = self.dict_class()
else:
try:
cur = ch[x]
continue
except KeyError:
pass
# optimistic: create the node first then look if it was correct to do so
cur = self.__class__(x, cur)
if not cur.exists():
cur.evict()
return None
if not cur.exists():
cur.evict()
return None
return cur
def make_node(self, lst):
"""
Returns or creates a Node object corresponding to the input path without considering the filesystem.
:param lst: relative path
:type lst: string or list of string
:rtype: :py:class:´waflib.Node.Node´
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
cur = cur.children[x]
except AttributeError:
cur.children = self.dict_class()
except KeyError:
pass
else:
continue
cur = self.__class__(x, cur)
return cur
def search_node(self, lst):
"""
Returns a Node previously defined in the data structure. The filesystem is not considered.
:param lst: relative path
:type lst: string or list of string
:rtype: :py:class:´waflib.Node.Node´ or None if there is no entry in the Node datastructure
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
else:
try:
cur = cur.children[x]
except (AttributeError, KeyError):
return None
return cur
def path_from(self, node):
"""
Path of this node seen from the other::
def build(bld):
n1 = bld.path.find_node('foo/bar/xyz.txt')
n2 = bld.path.find_node('foo/stuff/')
n1.path_from(n2) # '../bar/xyz.txt'
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
:returns: a relative path or an absolute one if that is better
:rtype: string
"""
c1 = self
c2 = node
c1h = c1.height()
c2h = c2.height()
lst = []
up = 0
while c1h > c2h:
lst.append(c1.name)
c1 = c1.parent
c1h -= 1
while c2h > c1h:
up += 1
c2 = c2.parent
c2h -= 1
while not c1 is c2:
lst.append(c1.name)
up += 1
c1 = c1.parent
c2 = c2.parent
if c1.parent:
lst.extend(['..'] * up)
lst.reverse()
return os.sep.join(lst) or '.'
else:
return self.abspath()
def abspath(self):
"""
Returns the absolute path. A cache is kept in the context as ``cache_node_abspath``
:rtype: string
"""
try:
return self.cache_abspath
except AttributeError:
pass
# think twice before touching this (performance + complexity + correctness)
if not self.parent:
val = os.sep
elif not self.parent.name:
val = os.sep + self.name
else:
val = self.parent.abspath() + os.sep + self.name
self.cache_abspath = val
return val
if Utils.is_win32:
def abspath(self):
try:
return self.cache_abspath
except AttributeError:
pass
if not self.parent:
val = ''
elif not self.parent.name:
val = self.name + os.sep
else:
val = self.parent.abspath().rstrip(os.sep) + os.sep + self.name
self.cache_abspath = val
return val
def is_child_of(self, node):
"""
Returns whether the object belongs to a subtree of the input node::
def build(bld):
node = bld.path.find_node('wscript')
node.is_child_of(bld.path) # True
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
:rtype: bool
"""
p = self
diff = self.height() - node.height()
while diff > 0:
diff -= 1
p = p.parent
return p is node
def ant_iter(self, accept=None, maxdepth=25, pats=[], dir=False, src=True, remove=True, quiet=False):
"""
Recursive method used by :py:meth:`waflib.Node.ant_glob`.
:param accept: function used for accepting/rejecting a node, returns the patterns that can be still accepted in recursion
:type accept: function
:param maxdepth: maximum depth in the filesystem (25)
:type maxdepth: int
:param pats: list of patterns to accept and list of patterns to exclude
:type pats: tuple
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
:param quiet: disable build directory traversal warnings (verbose mode)
:type quiet: bool
:returns: A generator object to iterate from
:rtype: iterator
"""
dircont = self.listdir()
try:
lst = set(self.children.keys())
except AttributeError:
self.children = self.dict_class()
else:
if remove:
for x in lst - set(dircont):
self.children[x].evict()
for name in dircont:
npats = accept(name, pats)
if npats and npats[0]:
accepted = [] in npats[0]
node = self.make_node([name])
isdir = node.isdir()
if accepted:
if isdir:
if dir:
yield node
elif src:
yield node
if isdir:
node.cache_isdir = True
if maxdepth:
for k in node.ant_iter(accept=accept, maxdepth=maxdepth - 1, pats=npats, dir=dir, src=src, remove=remove, quiet=quiet):
yield k
def ant_glob(self, *k, **kw):
"""
Finds files across folders and returns Node objects:
* ``**/*`` find all files recursively
* ``**/*.class`` find all files ending by .class
* ``..`` find files having two dot characters
For example::
def configure(cfg):
# find all .cpp files
cfg.path.ant_glob('**/*.cpp')
# find particular files from the root filesystem (can be slow)
cfg.root.ant_glob('etc/*.txt')
# simple exclusion rule example
cfg.path.ant_glob('*.c*', excl=['*.c'], src=True, dir=False)
For more information about the patterns, consult http://ant.apache.org/manual/dirtasks.html
Please remember that the '..' sequence does not represent the parent directory::
def configure(cfg):
cfg.path.ant_glob('../*.h') # incorrect
cfg.path.parent.ant_glob('*.h') # correct
The Node structure is itself a filesystem cache, so certain precautions must
be taken while matching files in the build or installation phases.
Nodes objects that do have a corresponding file or folder are garbage-collected by default.
This garbage collection is usually required to prevent returning files that do not
exist anymore. Yet, this may also remove Node objects of files that are yet-to-be built.
This typically happens when trying to match files in the build directory,
but there are also cases when files are created in the source directory.
Run ``waf -v`` to display any warnings, and try consider passing ``remove=False``
when matching files in the build directory.
Since ant_glob can traverse both source and build folders, it is a best practice
to call this method only from the most specific build node::
def build(bld):
# traverses the build directory, may need ``remove=False``:
bld.path.ant_glob('project/dir/**/*.h')
# better, no accidental build directory traversal:
bld.path.find_node('project/dir').ant_glob('**/*.h') # best
In addition, files and folders are listed immediately. When matching files in the
build folders, consider passing ``generator=True`` so that the generator object
returned can defer computation to a later stage. For example::
def build(bld):
bld(rule='tar xvf ${SRC}', source='arch.tar')
bld.add_group()
gen = bld.bldnode.ant_glob("*.h", generator=True, remove=True)
# files will be listed only after the arch.tar is unpacked
bld(rule='ls ${SRC}', source=gen, name='XYZ')
:param incl: ant patterns or list of patterns to include
:type incl: string or list of strings
:param excl: ant patterns or list of patterns to exclude
:type excl: string or list of strings
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param maxdepth: maximum depth of recursion
:type maxdepth: int
:param ignorecase: ignore case while matching (False by default)
:type ignorecase: bool
:param generator: Whether to evaluate the Nodes lazily
:type generator: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
:param quiet: disable build directory traversal warnings (verbose mode)
:type quiet: bool
:returns: The corresponding Node objects as a list or as a generator object (generator=True)
:rtype: by default, list of :py:class:`waflib.Node.Node` instances
"""
src = kw.get('src', True)
dir = kw.get('dir')
excl = kw.get('excl', exclude_regs)
incl = k and k[0] or kw.get('incl', '**')
remove = kw.get('remove', True)
maxdepth = kw.get('maxdepth', 25)
ignorecase = kw.get('ignorecase', False)
quiet = kw.get('quiet', False)
pats = (ant_matcher(incl, ignorecase), ant_matcher(excl, ignorecase))
if kw.get('generator'):
return Utils.lazy_generator(self.ant_iter, (ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet))
it = self.ant_iter(ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet)
if kw.get('flat'):
# returns relative paths as a space-delimited string
# prefer Node objects whenever possible
return ' '.join(x.path_from(self) for x in it)
return list(it)
# ----------------------------------------------------------------------------
# the methods below require the source/build folders (bld.srcnode/bld.bldnode)
def is_src(self):
"""
Returns True if the node is below the source directory. Note that ``!is_src() ≠ is_bld()``
:rtype: bool
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
while cur.parent:
if cur is y:
return False
if cur is x:
return True
cur = cur.parent
return False
def is_bld(self):
"""
Returns True if the node is below the build directory. Note that ``!is_bld() ≠ is_src()``
:rtype: bool
"""
cur = self
y = self.ctx.bldnode
while cur.parent:
if cur is y:
return True
cur = cur.parent
return False
def get_src(self):
"""
Returns the corresponding Node object in the source directory (or self if already
under the source directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
lst = []
while cur.parent:
if cur is y:
lst.reverse()
return x.make_node(lst)
if cur is x:
return self
lst.append(cur.name)
cur = cur.parent
return self
def get_bld(self):
"""
Return the corresponding Node object in the build directory (or self if already
under the build directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
lst = []
while cur.parent:
if cur is y:
return self
if cur is x:
lst.reverse()
return self.ctx.bldnode.make_node(lst)
lst.append(cur.name)
cur = cur.parent
# the file is external to the current project, make a fake root in the current build directory
lst.reverse()
if lst and Utils.is_win32 and len(lst[0]) == 2 and lst[0].endswith(':'):
lst[0] = lst[0][0]
return self.ctx.bldnode.make_node(['__root__'] + lst)
def find_resource(self, lst):
"""
Use this method in the build phase to find source files corresponding to the relative path given.
First it looks up the Node data structure to find any declared Node object in the build directory.
If None is found, it then considers the filesystem in the source directory.
:param lst: relative path
:type lst: string or list of string
:returns: the corresponding Node object or None
:rtype: :py:class:`waflib.Node.Node`
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
node = self.get_bld().search_node(lst)
if not node:
node = self.get_src().find_node(lst)
if node and node.isdir():
return None
return node
def find_or_declare(self, lst):
"""
Use this method in the build phase to declare output files which
are meant to be written in the build directory.
This method creates the Node object and its parent folder
as needed.
:param lst: relative path
:type lst: string or list of string
"""
if isinstance(lst, str) and os.path.isabs(lst):
node = self.ctx.root.make_node(lst)
else:
node = self.get_bld().make_node(lst)
node.parent.mkdir()
return node
def find_dir(self, lst):
"""
Searches for a folder on the filesystem (see :py:meth:`waflib.Node.Node.find_node`)
:param lst: relative path
:type lst: string or list of string
:returns: The corresponding Node object or None if there is no such folder
:rtype: :py:class:`waflib.Node.Node`
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
node = self.find_node(lst)
if node and not node.isdir():
return None
return node
# helpers for building things
def change_ext(self, ext, ext_in=None):
"""
Declares a build node with a distinct extension; this is uses :py:meth:`waflib.Node.Node.find_or_declare`
:return: A build node of the same path, but with a different extension
:rtype: :py:class:`waflib.Node.Node`
"""
name = self.name
if ext_in is None:
k = name.rfind('.')
if k >= 0:
name = name[:k] + ext
else:
name = name + ext
else:
name = name[:- len(ext_in)] + ext
return self.parent.find_or_declare([name])
def bldpath(self):
"""
Returns the relative path seen from the build directory ``src/foo.cpp``
:rtype: string
"""
return self.path_from(self.ctx.bldnode)
def srcpath(self):
"""
Returns the relative path seen from the source directory ``../src/foo.cpp``
:rtype: string
"""
return self.path_from(self.ctx.srcnode)
def relpath(self):
"""
If a file in the build directory, returns :py:meth:`waflib.Node.Node.bldpath`,
else returns :py:meth:`waflib.Node.Node.srcpath`
:rtype: string
"""
cur = self
x = self.ctx.bldnode
while cur.parent:
if cur is x:
return self.bldpath()
cur = cur.parent
return self.srcpath()
def bld_dir(self):
"""
Equivalent to self.parent.bldpath()
:rtype: string
"""
return self.parent.bldpath()
def h_file(self):
"""
See :py:func:`waflib.Utils.h_file`
:return: a hash representing the file contents
:rtype: string or bytes
"""
return Utils.h_file(self.abspath())
def get_bld_sig(self):
"""
Returns a signature (see :py:meth:`waflib.Node.Node.h_file`) for the purpose
of build dependency calculation. This method uses a per-context cache.
:return: a hash representing the object contents
:rtype: string or bytes
"""
# previous behaviour can be set by returning self.ctx.node_sigs[self] when a build node
try:
cache = self.ctx.cache_sig
except AttributeError:
cache = self.ctx.cache_sig = {}
try:
ret = cache[self]
except KeyError:
p = self.abspath()
try:
ret = cache[self] = self.h_file()
except EnvironmentError:
if self.isdir():
# allow folders as build nodes, do not use the creation time
st = os.stat(p)
ret = cache[self] = Utils.h_list([p, st.st_ino, st.st_mode])
return ret
raise
return ret
pickle_lock = Utils.threading.Lock()
"""Lock mandatory for thread-safe node serialization"""
class Nod3(Node):
"""Mandatory subclass for thread-safe node serialization"""
pass # do not remove
| 25,493 | Python | .py | 815 | 27.771779 | 125 | 0.685082 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,569 | Scripting.py | projecthamster_hamster/waflib/Scripting.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"Module called for configuring, compiling and installing targets"
from __future__ import with_statement
import os, shlex, shutil, traceback, errno, sys, stat
from waflib import Utils, Configure, Logs, Options, ConfigSet, Context, Errors, Build, Node
build_dir_override = None
no_climb_commands = ['configure']
default_cmd = "build"
def waf_entry_point(current_directory, version, wafdir):
"""
This is the main entry point, all Waf execution starts here.
:param current_directory: absolute path representing the current directory
:type current_directory: string
:param version: version number
:type version: string
:param wafdir: absolute path representing the directory of the waf library
:type wafdir: string
"""
Logs.init_log()
if Context.WAFVERSION != version:
Logs.error('Waf script %r and library %r do not match (directory %r)', version, Context.WAFVERSION, wafdir)
sys.exit(1)
# Store current directory before any chdir
Context.waf_dir = wafdir
Context.run_dir = Context.launch_dir = current_directory
start_dir = current_directory
no_climb = os.environ.get('NOCLIMB')
if len(sys.argv) > 1:
# os.path.join handles absolute paths
# if sys.argv[1] is not an absolute path, then it is relative to the current working directory
potential_wscript = os.path.join(current_directory, sys.argv[1])
if os.path.basename(potential_wscript) == Context.WSCRIPT_FILE and os.path.isfile(potential_wscript):
# need to explicitly normalize the path, as it may contain extra '/.'
path = os.path.normpath(os.path.dirname(potential_wscript))
start_dir = os.path.abspath(path)
no_climb = True
sys.argv.pop(1)
ctx = Context.create_context('options')
(options, commands, env) = ctx.parse_cmd_args(allow_unknown=True)
if options.top:
start_dir = Context.run_dir = Context.top_dir = options.top
no_climb = True
if options.out:
Context.out_dir = options.out
# if 'configure' is in the commands, do not search any further
if not no_climb:
for k in no_climb_commands:
for y in commands:
if y.startswith(k):
no_climb = True
break
# try to find a lock file (if the project was configured)
# at the same time, store the first wscript file seen
cur = start_dir
while cur:
try:
lst = os.listdir(cur)
except OSError:
lst = []
Logs.error('Directory %r is unreadable!', cur)
if Options.lockfile in lst:
env = ConfigSet.ConfigSet()
try:
env.load(os.path.join(cur, Options.lockfile))
ino = os.stat(cur)[stat.ST_INO]
except EnvironmentError:
pass
else:
# check if the folder was not moved
for x in (env.run_dir, env.top_dir, env.out_dir):
if not x:
continue
if Utils.is_win32:
if cur == x:
load = True
break
else:
# if the filesystem features symlinks, compare the inode numbers
try:
ino2 = os.stat(x)[stat.ST_INO]
except OSError:
pass
else:
if ino == ino2:
load = True
break
else:
Logs.warn('invalid lock file in %s', cur)
load = False
if load:
Context.run_dir = env.run_dir
Context.top_dir = env.top_dir
Context.out_dir = env.out_dir
break
if not Context.run_dir:
if Context.WSCRIPT_FILE in lst:
Context.run_dir = cur
next = os.path.dirname(cur)
if next == cur:
break
cur = next
if no_climb:
break
wscript = os.path.normpath(os.path.join(Context.run_dir, Context.WSCRIPT_FILE))
if not os.path.exists(wscript):
if options.whelp:
Logs.warn('These are the generic options (no wscript/project found)')
ctx.parser.print_help()
sys.exit(0)
Logs.error('Waf: Run from a folder containing a %r file (or try -h for the generic options)', Context.WSCRIPT_FILE)
sys.exit(1)
try:
os.chdir(Context.run_dir)
except OSError:
Logs.error('Waf: The folder %r is unreadable', Context.run_dir)
sys.exit(1)
try:
set_main_module(wscript)
except Errors.WafError as e:
Logs.pprint('RED', e.verbose_msg)
Logs.error(str(e))
sys.exit(1)
except Exception as e:
Logs.error('Waf: The wscript in %r is unreadable', Context.run_dir)
traceback.print_exc(file=sys.stdout)
sys.exit(2)
if options.profile:
import cProfile, pstats
cProfile.runctx('from waflib import Scripting; Scripting.run_commands()', {}, {}, 'profi.txt')
p = pstats.Stats('profi.txt')
p.sort_stats('time').print_stats(75) # or 'cumulative'
else:
try:
try:
run_commands()
except:
if options.pdb:
import pdb
type, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
else:
raise
except Errors.WafError as e:
if Logs.verbose > 1:
Logs.pprint('RED', e.verbose_msg)
Logs.error(e.msg)
sys.exit(1)
except SystemExit:
raise
except Exception as e:
traceback.print_exc(file=sys.stdout)
sys.exit(2)
except KeyboardInterrupt:
Logs.pprint('RED', 'Interrupted')
sys.exit(68)
def set_main_module(file_path):
"""
Read the main wscript file into :py:const:`waflib.Context.Context.g_module` and
bind default functions such as ``init``, ``dist``, ``distclean`` if not defined.
Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
:param file_path: absolute path representing the top-level wscript file
:type file_path: string
"""
Context.g_module = Context.load_module(file_path)
Context.g_module.root_path = file_path
# note: to register the module globally, use the following:
# sys.modules['wscript_main'] = g_module
def set_def(obj):
name = obj.__name__
if not name in Context.g_module.__dict__:
setattr(Context.g_module, name, obj)
for k in (dist, distclean, distcheck):
set_def(k)
# add dummy init and shutdown functions if they're not defined
if not 'init' in Context.g_module.__dict__:
Context.g_module.init = Utils.nada
if not 'shutdown' in Context.g_module.__dict__:
Context.g_module.shutdown = Utils.nada
if not 'options' in Context.g_module.__dict__:
Context.g_module.options = Utils.nada
def parse_options():
"""
Parses the command-line options and initialize the logging system.
Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization.
"""
ctx = Context.create_context('options')
ctx.execute()
if not Options.commands:
if isinstance(default_cmd, list):
Options.commands.extend(default_cmd)
else:
Options.commands.append(default_cmd)
if Options.options.whelp:
ctx.parser.print_help()
sys.exit(0)
def run_command(cmd_name):
"""
Executes a single Waf command. Called by :py:func:`waflib.Scripting.run_commands`.
:param cmd_name: command to execute, like ``build``
:type cmd_name: string
"""
ctx = Context.create_context(cmd_name)
ctx.log_timer = Utils.Timer()
ctx.options = Options.options # provided for convenience
ctx.cmd = cmd_name
try:
ctx.execute()
finally:
# Issue 1374
ctx.finalize()
return ctx
def run_commands():
"""
Execute the Waf commands that were given on the command-line, and the other options
Called by :py:func:`waflib.Scripting.waf_entry_point` during the initialization, and executed
after :py:func:`waflib.Scripting.parse_options`.
"""
parse_options()
run_command('init')
while Options.commands:
cmd_name = Options.commands.pop(0)
ctx = run_command(cmd_name)
Logs.info('%r finished successfully (%s)', cmd_name, ctx.log_timer)
run_command('shutdown')
###########################################################################################
def distclean_dir(dirname):
"""
Distclean function called in the particular case when::
top == out
:param dirname: absolute path of the folder to clean
:type dirname: string
"""
for (root, dirs, files) in os.walk(dirname):
for f in files:
if f.endswith(('.o', '.moc', '.exe')):
fname = os.path.join(root, f)
try:
os.remove(fname)
except OSError:
Logs.warn('Could not remove %r', fname)
for x in (Context.DBFILE, 'config.log'):
try:
os.remove(x)
except OSError:
pass
try:
shutil.rmtree(Build.CACHE_DIR)
except OSError:
pass
def distclean(ctx):
'''removes build folders and data'''
def remove_and_log(k, fun):
try:
fun(k)
except EnvironmentError as e:
if e.errno != errno.ENOENT:
Logs.warn('Could not remove %r', k)
# remove waf cache folders on the top-level
if not Options.commands:
for k in os.listdir('.'):
for x in '.waf-2 waf-2 .waf3-2 waf3-2'.split():
if k.startswith(x):
remove_and_log(k, shutil.rmtree)
# remove a build folder, if any
cur = '.'
if os.environ.get('NO_LOCK_IN_TOP') or ctx.options.no_lock_in_top:
cur = ctx.options.out
try:
lst = os.listdir(cur)
except OSError:
Logs.warn('Could not read %r', cur)
return
if Options.lockfile in lst:
f = os.path.join(cur, Options.lockfile)
try:
env = ConfigSet.ConfigSet(f)
except EnvironmentError:
Logs.warn('Could not read %r', f)
return
if not env.out_dir or not env.top_dir:
Logs.warn('Invalid lock file %r', f)
return
if env.out_dir == env.top_dir:
distclean_dir(env.out_dir)
else:
remove_and_log(env.out_dir, shutil.rmtree)
env_dirs = [env.out_dir]
if not (os.environ.get('NO_LOCK_IN_TOP') or ctx.options.no_lock_in_top):
env_dirs.append(env.top_dir)
if not (os.environ.get('NO_LOCK_IN_RUN') or ctx.options.no_lock_in_run):
env_dirs.append(env.run_dir)
for k in env_dirs:
p = os.path.join(k, Options.lockfile)
remove_and_log(p, os.remove)
class Dist(Context.Context):
'''creates an archive containing the project source code'''
cmd = 'dist'
fun = 'dist'
algo = 'tar.bz2'
ext_algo = {}
def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
self.recurse([os.path.dirname(Context.g_module.root_path)])
self.archive()
def archive(self):
"""
Creates the source archive.
"""
import tarfile
arch_name = self.get_arch_name()
try:
self.base_path
except AttributeError:
self.base_path = self.path
node = self.base_path.make_node(arch_name)
try:
node.delete()
except OSError:
pass
files = self.get_files()
if self.algo.startswith('tar.'):
tar = tarfile.open(node.abspath(), 'w:' + self.algo.replace('tar.', ''))
for x in files:
self.add_tar_file(x, tar)
tar.close()
elif self.algo == 'zip':
import zipfile
zip = zipfile.ZipFile(node.abspath(), 'w', compression=zipfile.ZIP_DEFLATED)
for x in files:
archive_name = self.get_base_name() + '/' + x.path_from(self.base_path)
if os.environ.get('SOURCE_DATE_EPOCH'):
# TODO: parse that timestamp
zip.writestr(zipfile.ZipInfo(archive_name), x.read(), zipfile.ZIP_DEFLATED)
else:
zip.write(x.abspath(), archive_name, zipfile.ZIP_DEFLATED)
zip.close()
else:
self.fatal('Valid algo types are tar.bz2, tar.gz, tar.xz or zip')
try:
from hashlib import sha256
except ImportError:
digest = ''
else:
digest = ' (sha256=%r)' % sha256(node.read(flags='rb')).hexdigest()
Logs.info('New archive created: %s%s', self.arch_name, digest)
def get_tar_path(self, node):
"""
Return the path to use for a node in the tar archive, the purpose of this
is to let subclases resolve symbolic links or to change file names
:return: absolute path
:rtype: string
"""
return node.abspath()
def add_tar_file(self, x, tar):
"""
Adds a file to the tar archive. Symlinks are not verified.
:param x: file path
:param tar: tar file object
"""
p = self.get_tar_path(x)
tinfo = tar.gettarinfo(name=p, arcname=self.get_tar_prefix() + '/' + x.path_from(self.base_path))
tinfo.uid = 0
tinfo.gid = 0
tinfo.uname = 'root'
tinfo.gname = 'root'
if os.environ.get('SOURCE_DATE_EPOCH'):
tinfo.mtime = int(os.environ.get('SOURCE_DATE_EPOCH'))
if os.path.isfile(p):
with open(p, 'rb') as f:
tar.addfile(tinfo, fileobj=f)
else:
tar.addfile(tinfo)
def get_tar_prefix(self):
"""
Returns the base path for files added into the archive tar file
:rtype: string
"""
try:
return self.tar_prefix
except AttributeError:
return self.get_base_name()
def get_arch_name(self):
"""
Returns the archive file name.
Set the attribute *arch_name* to change the default value::
def dist(ctx):
ctx.arch_name = 'ctx.tar.bz2'
:rtype: string
"""
try:
self.arch_name
except AttributeError:
self.arch_name = self.get_base_name() + '.' + self.ext_algo.get(self.algo, self.algo)
return self.arch_name
def get_base_name(self):
"""
Returns the default name of the main directory in the archive, which is set to *appname-version*.
Set the attribute *base_name* to change the default value::
def dist(ctx):
ctx.base_name = 'files'
:rtype: string
"""
try:
self.base_name
except AttributeError:
appname = getattr(Context.g_module, Context.APPNAME, 'noname')
version = getattr(Context.g_module, Context.VERSION, '1.0')
self.base_name = appname + '-' + version
return self.base_name
def get_excl(self):
"""
Returns the patterns to exclude for finding the files in the top-level directory.
Set the attribute *excl* to change the default value::
def dist(ctx):
ctx.excl = 'build **/*.o **/*.class'
:rtype: string
"""
try:
return self.excl
except AttributeError:
self.excl = Node.exclude_regs + ' **/waf-2.* **/.waf-2.* **/waf3-2.* **/.waf3-2.* **/*~ **/*.rej **/*.orig **/*.pyc **/*.pyo **/*.bak **/*.swp **/.lock-w*'
if Context.out_dir:
nd = self.root.find_node(Context.out_dir)
if nd:
self.excl += ' ' + nd.path_from(self.base_path)
return self.excl
def get_files(self):
"""
Files to package are searched automatically by :py:func:`waflib.Node.Node.ant_glob`.
Set *files* to prevent this behaviour::
def dist(ctx):
ctx.files = ctx.path.find_node('wscript')
Files are also searched from the directory 'base_path', to change it, set::
def dist(ctx):
ctx.base_path = path
:rtype: list of :py:class:`waflib.Node.Node`
"""
try:
files = self.files
except AttributeError:
files = self.base_path.ant_glob('**/*', excl=self.get_excl())
return files
def dist(ctx):
'''makes a tarball for redistributing the sources'''
pass
class DistCheck(Dist):
"""creates an archive with dist, then tries to build it"""
fun = 'distcheck'
cmd = 'distcheck'
def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
self.recurse([os.path.dirname(Context.g_module.root_path)])
self.archive()
self.check()
def make_distcheck_cmd(self, tmpdir):
cfg = []
if Options.options.distcheck_args:
cfg = shlex.split(Options.options.distcheck_args)
else:
cfg = [x for x in sys.argv if x.startswith('-')]
cmd = [sys.executable, sys.argv[0], 'configure', 'build', 'install', 'uninstall', '--destdir=' + tmpdir] + cfg
return cmd
def check(self):
"""
Creates the archive, uncompresses it and tries to build the project
"""
import tempfile, tarfile
with tarfile.open(self.get_arch_name()) as t:
for x in t:
t.extract(x)
instdir = tempfile.mkdtemp('.inst', self.get_base_name())
cmd = self.make_distcheck_cmd(instdir)
ret = Utils.subprocess.Popen(cmd, cwd=self.get_base_name()).wait()
if ret:
raise Errors.WafError('distcheck failed with code %r' % ret)
if os.path.exists(instdir):
raise Errors.WafError('distcheck succeeded, but files were left in %s' % instdir)
shutil.rmtree(self.get_base_name())
def distcheck(ctx):
'''checks if the project compiles (tarball from 'dist')'''
pass
def autoconfigure(execute_method):
"""
Decorator that enables context commands to run *configure* as needed.
"""
def execute(self):
"""
Wraps :py:func:`waflib.Context.Context.execute` on the context class
"""
if not Configure.autoconfig:
return execute_method(self)
env = ConfigSet.ConfigSet()
do_config = False
try:
env.load(os.path.join(Context.top_dir, Options.lockfile))
except EnvironmentError:
Logs.warn('Configuring the project')
do_config = True
else:
if env.run_dir != Context.run_dir:
do_config = True
else:
h = 0
for f in env.files:
try:
h = Utils.h_list((h, Utils.readf(f, 'rb')))
except EnvironmentError:
do_config = True
break
else:
do_config = h != env.hash
if do_config:
cmd = env.config_cmd or 'configure'
if Configure.autoconfig == 'clobber':
tmp = Options.options.__dict__
launch_dir_tmp = Context.launch_dir
if env.options:
Options.options.__dict__ = env.options
Context.launch_dir = env.launch_dir
try:
run_command(cmd)
finally:
Options.options.__dict__ = tmp
Context.launch_dir = launch_dir_tmp
else:
run_command(cmd)
run_command(self.cmd)
else:
return execute_method(self)
return execute
Build.BuildContext.execute = autoconfigure(Build.BuildContext.execute)
| 16,906 | Python | .py | 538 | 27.933086 | 158 | 0.692965 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,570 | ConfigSet.py | projecthamster_hamster/waflib/ConfigSet.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
ConfigSet: a special dict
The values put in :py:class:`ConfigSet` must be serializable (dicts, lists, strings)
"""
import copy, re, os
from waflib import Logs, Utils
re_imp = re.compile(r'^(#)*?([^#=]*?)\ =\ (.*?)$', re.M)
class ConfigSet(object):
"""
A copy-on-write dict with human-readable serialized format. The serialization format
is human-readable (python-like) and performed by using eval() and repr().
For high performance prefer pickle. Do not store functions as they are not serializable.
The values can be accessed by attributes or by keys::
from waflib.ConfigSet import ConfigSet
env = ConfigSet()
env.FOO = 'test'
env['FOO'] = 'test'
"""
__slots__ = ('table', 'parent')
def __init__(self, filename=None):
self.table = {}
"""
Internal dict holding the object values
"""
#self.parent = None
if filename:
self.load(filename)
def __contains__(self, key):
"""
Enables the *in* syntax::
if 'foo' in env:
print(env['foo'])
"""
if key in self.table:
return True
try:
return self.parent.__contains__(key)
except AttributeError:
return False # parent may not exist
def keys(self):
"""Dict interface"""
keys = set()
cur = self
while cur:
keys.update(cur.table.keys())
cur = getattr(cur, 'parent', None)
keys = list(keys)
keys.sort()
return keys
def __iter__(self):
return iter(self.keys())
def __str__(self):
"""Text representation of the ConfigSet (for debugging purposes)"""
return "\n".join(["%r %r" % (x, self.__getitem__(x)) for x in self.keys()])
def __getitem__(self, key):
"""
Dictionary interface: get value from key::
def configure(conf):
conf.env['foo'] = {}
print(env['foo'])
"""
try:
while 1:
x = self.table.get(key)
if not x is None:
return x
self = self.parent
except AttributeError:
return []
def __setitem__(self, key, value):
"""
Dictionary interface: set value from key
"""
self.table[key] = value
def __delitem__(self, key):
"""
Dictionary interface: mark the value as missing
"""
self[key] = []
def __getattr__(self, name):
"""
Attribute access provided for convenience. The following forms are equivalent::
def configure(conf):
conf.env.value
conf.env['value']
"""
if name in self.__slots__:
return object.__getattribute__(self, name)
else:
return self[name]
def __setattr__(self, name, value):
"""
Attribute access provided for convenience. The following forms are equivalent::
def configure(conf):
conf.env.value = x
env['value'] = x
"""
if name in self.__slots__:
object.__setattr__(self, name, value)
else:
self[name] = value
def __delattr__(self, name):
"""
Attribute access provided for convenience. The following forms are equivalent::
def configure(conf):
del env.value
del env['value']
"""
if name in self.__slots__:
object.__delattr__(self, name)
else:
del self[name]
def derive(self):
"""
Returns a new ConfigSet deriving from self. The copy returned
will be a shallow copy::
from waflib.ConfigSet import ConfigSet
env = ConfigSet()
env.append_value('CFLAGS', ['-O2'])
child = env.derive()
child.CFLAGS.append('test') # warning! this will modify 'env'
child.CFLAGS = ['-O3'] # new list, ok
child.append_value('CFLAGS', ['-O3']) # ok
Use :py:func:`ConfigSet.detach` to detach the child from the parent.
"""
newenv = ConfigSet()
newenv.parent = self
return newenv
def detach(self):
"""
Detaches this instance from its parent (if present)
Modifying the parent :py:class:`ConfigSet` will not change the current object
Modifying this :py:class:`ConfigSet` will not modify the parent one.
"""
tbl = self.get_merged_dict()
try:
delattr(self, 'parent')
except AttributeError:
pass
else:
keys = tbl.keys()
for x in keys:
tbl[x] = copy.deepcopy(tbl[x])
self.table = tbl
return self
def get_flat(self, key):
"""
Returns a value as a string. If the input is a list, the value returned is space-separated.
:param key: key to use
:type key: string
"""
s = self[key]
if isinstance(s, str):
return s
return ' '.join(s)
def _get_list_value_for_modification(self, key):
"""
Returns a list value for further modification.
The list may be modified inplace and there is no need to do this afterwards::
self.table[var] = value
"""
try:
value = self.table[key]
except KeyError:
try:
value = self.parent[key]
except AttributeError:
value = []
else:
if isinstance(value, list):
# force a copy
value = value[:]
else:
value = [value]
self.table[key] = value
else:
if not isinstance(value, list):
self.table[key] = value = [value]
return value
def append_value(self, var, val):
"""
Appends a value to the specified config key::
def build(bld):
bld.env.append_value('CFLAGS', ['-O2'])
The value must be a list or a tuple
"""
if isinstance(val, str): # if there were string everywhere we could optimize this
val = [val]
current_value = self._get_list_value_for_modification(var)
current_value.extend(val)
def prepend_value(self, var, val):
"""
Prepends a value to the specified item::
def configure(conf):
conf.env.prepend_value('CFLAGS', ['-O2'])
The value must be a list or a tuple
"""
if isinstance(val, str):
val = [val]
self.table[var] = val + self._get_list_value_for_modification(var)
def append_unique(self, var, val):
"""
Appends a value to the specified item only if it's not already present::
def build(bld):
bld.env.append_unique('CFLAGS', ['-O2', '-g'])
The value must be a list or a tuple
"""
if isinstance(val, str):
val = [val]
current_value = self._get_list_value_for_modification(var)
for x in val:
if x not in current_value:
current_value.append(x)
def get_merged_dict(self):
"""
Computes the merged dictionary from the fusion of self and all its parent
:rtype: a ConfigSet object
"""
table_list = []
env = self
while 1:
table_list.insert(0, env.table)
try:
env = env.parent
except AttributeError:
break
merged_table = {}
for table in table_list:
merged_table.update(table)
return merged_table
def store(self, filename):
"""
Serializes the :py:class:`ConfigSet` data to a file. See :py:meth:`ConfigSet.load` for reading such files.
:param filename: file to use
:type filename: string
"""
try:
os.makedirs(os.path.split(filename)[0])
except OSError:
pass
buf = []
merged_table = self.get_merged_dict()
keys = list(merged_table.keys())
keys.sort()
try:
fun = ascii
except NameError:
fun = repr
for k in keys:
if k != 'undo_stack':
buf.append('%s = %s\n' % (k, fun(merged_table[k])))
Utils.writef(filename, ''.join(buf))
def load(self, filename):
"""
Restores contents from a file (current values are not cleared). Files are written using :py:meth:`ConfigSet.store`.
:param filename: file to use
:type filename: string
"""
tbl = self.table
code = Utils.readf(filename, m='r')
for m in re_imp.finditer(code):
g = m.group
tbl[g(2)] = eval(g(3))
Logs.debug('env: %s', self.table)
def update(self, d):
"""
Dictionary interface: replace values with the ones from another dict
:param d: object to use the value from
:type d: dict-like object
"""
self.table.update(d)
def stash(self):
"""
Stores the object state to provide transactionality semantics::
env = ConfigSet()
env.stash()
try:
env.append_value('CFLAGS', '-O3')
call_some_method(env)
finally:
env.revert()
The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store`
"""
orig = self.table
tbl = self.table = self.table.copy()
for x in tbl.keys():
tbl[x] = copy.deepcopy(tbl[x])
self.undo_stack = self.undo_stack + [orig]
def commit(self):
"""
Commits transactional changes. See :py:meth:`ConfigSet.stash`
"""
self.undo_stack.pop(-1)
def revert(self):
"""
Reverts the object to a previous state. See :py:meth:`ConfigSet.stash`
"""
self.table = self.undo_stack.pop(-1)
| 8,294 | Python | .py | 301 | 24.10299 | 117 | 0.671751 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,571 | ansiterm.py | projecthamster_hamster/waflib/ansiterm.py | #!/usr/bin/env python
# encoding: utf-8
"""
Emulate a vt100 terminal in cmd.exe
By wrapping sys.stdout / sys.stderr with Ansiterm,
the vt100 escape characters will be interpreted and
the equivalent actions will be performed with Win32
console commands.
"""
import os, re, sys
from waflib import Utils
wlock = Utils.threading.Lock()
try:
from ctypes import Structure, windll, c_short, c_ushort, c_ulong, c_int, byref, c_wchar, POINTER, c_long
except ImportError:
class AnsiTerm(object):
def __init__(self, stream):
self.stream = stream
try:
self.errors = self.stream.errors
except AttributeError:
pass # python 2.5
self.encoding = self.stream.encoding
def write(self, txt):
try:
wlock.acquire()
self.stream.write(txt)
self.stream.flush()
finally:
wlock.release()
def fileno(self):
return self.stream.fileno()
def flush(self):
self.stream.flush()
def isatty(self):
return self.stream.isatty()
else:
class COORD(Structure):
_fields_ = [("X", c_short), ("Y", c_short)]
class SMALL_RECT(Structure):
_fields_ = [("Left", c_short), ("Top", c_short), ("Right", c_short), ("Bottom", c_short)]
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("Size", COORD), ("CursorPosition", COORD), ("Attributes", c_ushort), ("Window", SMALL_RECT), ("MaximumWindowSize", COORD)]
class CONSOLE_CURSOR_INFO(Structure):
_fields_ = [('dwSize', c_ulong), ('bVisible', c_int)]
try:
_type = unicode
except NameError:
_type = str
to_int = lambda number, default: number and int(number) or default
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
windll.kernel32.GetStdHandle.argtypes = [c_ulong]
windll.kernel32.GetStdHandle.restype = c_ulong
windll.kernel32.GetConsoleScreenBufferInfo.argtypes = [c_ulong, POINTER(CONSOLE_SCREEN_BUFFER_INFO)]
windll.kernel32.GetConsoleScreenBufferInfo.restype = c_long
windll.kernel32.SetConsoleTextAttribute.argtypes = [c_ulong, c_ushort]
windll.kernel32.SetConsoleTextAttribute.restype = c_long
windll.kernel32.FillConsoleOutputCharacterW.argtypes = [c_ulong, c_wchar, c_ulong, POINTER(COORD), POINTER(c_ulong)]
windll.kernel32.FillConsoleOutputCharacterW.restype = c_long
windll.kernel32.FillConsoleOutputAttribute.argtypes = [c_ulong, c_ushort, c_ulong, POINTER(COORD), POINTER(c_ulong) ]
windll.kernel32.FillConsoleOutputAttribute.restype = c_long
windll.kernel32.SetConsoleCursorPosition.argtypes = [c_ulong, POINTER(COORD) ]
windll.kernel32.SetConsoleCursorPosition.restype = c_long
windll.kernel32.SetConsoleCursorInfo.argtypes = [c_ulong, POINTER(CONSOLE_CURSOR_INFO)]
windll.kernel32.SetConsoleCursorInfo.restype = c_long
class AnsiTerm(object):
"""
emulate a vt100 terminal in cmd.exe
"""
def __init__(self, s):
self.stream = s
try:
self.errors = s.errors
except AttributeError:
pass # python2.5
self.encoding = s.encoding
self.cursor_history = []
handle = (s.fileno() == 2) and STD_ERROR_HANDLE or STD_OUTPUT_HANDLE
self.hconsole = windll.kernel32.GetStdHandle(handle)
self._sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
self._csinfo = CONSOLE_CURSOR_INFO()
windll.kernel32.GetConsoleCursorInfo(self.hconsole, byref(self._csinfo))
# just to double check that the console is usable
self._orig_sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
r = windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(self._orig_sbinfo))
self._isatty = r == 1
def screen_buffer_info(self):
"""
Updates self._sbinfo and returns it
"""
windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(self._sbinfo))
return self._sbinfo
def clear_line(self, param):
mode = param and int(param) or 0
sbinfo = self.screen_buffer_info()
if mode == 1: # Clear from beginning of line to cursor position
line_start = COORD(0, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X
elif mode == 2: # Clear entire line
line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
else: # Clear from cursor position to end of line
line_start = sbinfo.CursorPosition
line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
chars_written = c_ulong()
windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
def clear_screen(self, param):
mode = to_int(param, 0)
sbinfo = self.screen_buffer_info()
if mode == 1: # Clear from beginning of screen to cursor position
clear_start = COORD(0, 0)
clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
elif mode == 2: # Clear entire screen and return cursor to home
clear_start = COORD(0, 0)
clear_length = sbinfo.Size.X * sbinfo.Size.Y
windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
else: # Clear from cursor position to end of screen
clear_start = sbinfo.CursorPosition
clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
chars_written = c_ulong()
windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), clear_length, clear_start, byref(chars_written))
windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written))
def push_cursor(self, param):
sbinfo = self.screen_buffer_info()
self.cursor_history.append(sbinfo.CursorPosition)
def pop_cursor(self, param):
if self.cursor_history:
old_pos = self.cursor_history.pop()
windll.kernel32.SetConsoleCursorPosition(self.hconsole, old_pos)
def set_cursor(self, param):
y, sep, x = param.partition(';')
x = to_int(x, 1) - 1
y = to_int(y, 1) - 1
sbinfo = self.screen_buffer_info()
new_pos = COORD(
min(max(0, x), sbinfo.Size.X),
min(max(0, y), sbinfo.Size.Y)
)
windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)
def set_column(self, param):
x = to_int(param, 1) - 1
sbinfo = self.screen_buffer_info()
new_pos = COORD(
min(max(0, x), sbinfo.Size.X),
sbinfo.CursorPosition.Y
)
windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)
def move_cursor(self, x_offset=0, y_offset=0):
sbinfo = self.screen_buffer_info()
new_pos = COORD(
min(max(0, sbinfo.CursorPosition.X + x_offset), sbinfo.Size.X),
min(max(0, sbinfo.CursorPosition.Y + y_offset), sbinfo.Size.Y)
)
windll.kernel32.SetConsoleCursorPosition(self.hconsole, new_pos)
def move_up(self, param):
self.move_cursor(y_offset = -to_int(param, 1))
def move_down(self, param):
self.move_cursor(y_offset = to_int(param, 1))
def move_left(self, param):
self.move_cursor(x_offset = -to_int(param, 1))
def move_right(self, param):
self.move_cursor(x_offset = to_int(param, 1))
def next_line(self, param):
sbinfo = self.screen_buffer_info()
self.move_cursor(
x_offset = -sbinfo.CursorPosition.X,
y_offset = to_int(param, 1)
)
def prev_line(self, param):
sbinfo = self.screen_buffer_info()
self.move_cursor(
x_offset = -sbinfo.CursorPosition.X,
y_offset = -to_int(param, 1)
)
def rgb2bgr(self, c):
return ((c&1) << 2) | (c&2) | ((c&4)>>2)
def set_color(self, param):
cols = param.split(';')
sbinfo = self.screen_buffer_info()
attr = sbinfo.Attributes
for c in cols:
c = to_int(c, 0)
if 29 < c < 38: # fgcolor
attr = (attr & 0xfff0) | self.rgb2bgr(c - 30)
elif 39 < c < 48: # bgcolor
attr = (attr & 0xff0f) | (self.rgb2bgr(c - 40) << 4)
elif c == 0: # reset
attr = self._orig_sbinfo.Attributes
elif c == 1: # strong
attr |= 0x08
elif c == 4: # blink not available -> bg intensity
attr |= 0x80
elif c == 7: # negative
attr = (attr & 0xff88) | ((attr & 0x70) >> 4) | ((attr & 0x07) << 4)
windll.kernel32.SetConsoleTextAttribute(self.hconsole, attr)
def show_cursor(self,param):
self._csinfo.bVisible = 1
windll.kernel32.SetConsoleCursorInfo(self.hconsole, byref(self._csinfo))
def hide_cursor(self,param):
self._csinfo.bVisible = 0
windll.kernel32.SetConsoleCursorInfo(self.hconsole, byref(self._csinfo))
ansi_command_table = {
'A': move_up,
'B': move_down,
'C': move_right,
'D': move_left,
'E': next_line,
'F': prev_line,
'G': set_column,
'H': set_cursor,
'f': set_cursor,
'J': clear_screen,
'K': clear_line,
'h': show_cursor,
'l': hide_cursor,
'm': set_color,
's': push_cursor,
'u': pop_cursor,
}
# Match either the escape sequence or text not containing escape sequence
ansi_tokens = re.compile(r'(?:\x1b\[([0-9?;]*)([a-zA-Z])|([^\x1b]+))')
def write(self, text):
try:
wlock.acquire()
if self._isatty:
for param, cmd, txt in self.ansi_tokens.findall(text):
if cmd:
cmd_func = self.ansi_command_table.get(cmd)
if cmd_func:
cmd_func(self, param)
else:
self.writeconsole(txt)
else:
# no support for colors in the console, just output the text:
# eclipse or msys may be able to interpret the escape sequences
self.stream.write(text)
finally:
wlock.release()
def writeconsole(self, txt):
chars_written = c_ulong()
writeconsole = windll.kernel32.WriteConsoleA
if isinstance(txt, _type):
writeconsole = windll.kernel32.WriteConsoleW
# MSDN says that there is a shared buffer of 64 KB for the console
# writes. Attempt to not get ERROR_NOT_ENOUGH_MEMORY, see waf issue #746
done = 0
todo = len(txt)
chunk = 32<<10
while todo != 0:
doing = min(chunk, todo)
buf = txt[done:done+doing]
r = writeconsole(self.hconsole, buf, doing, byref(chars_written), None)
if r == 0:
chunk >>= 1
continue
done += doing
todo -= doing
def fileno(self):
return self.stream.fileno()
def flush(self):
pass
def isatty(self):
return self._isatty
if sys.stdout.isatty() or sys.stderr.isatty():
handle = sys.stdout.isatty() and STD_OUTPUT_HANDLE or STD_ERROR_HANDLE
console = windll.kernel32.GetStdHandle(handle)
sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
def get_term_cols():
windll.kernel32.GetConsoleScreenBufferInfo(console, byref(sbinfo))
# Issue 1401 - the progress bar cannot reach the last character
return sbinfo.Size.X - 1
# just try and see
try:
import struct, fcntl, termios
except ImportError:
pass
else:
if (sys.stdout.isatty() or sys.stderr.isatty()) and os.environ.get('TERM', '') not in ('dumb', 'emacs'):
FD = sys.stdout.isatty() and sys.stdout.fileno() or sys.stderr.fileno()
def fun():
return struct.unpack("HHHH", fcntl.ioctl(FD, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)))[1]
try:
fun()
except Exception as e:
pass
else:
get_term_cols = fun
| 10,939 | Python | .py | 289 | 33.910035 | 137 | 0.701331 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,572 | __init__.py | projecthamster_hamster/waflib/__init__.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
| 71 | Python | .py | 3 | 22.666667 | 30 | 0.705882 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,573 | Errors.py | projecthamster_hamster/waflib/Errors.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010-2018 (ita)
"""
Exceptions used in the Waf code
"""
import traceback, sys
class WafError(Exception):
"""Base class for all Waf errors"""
def __init__(self, msg='', ex=None):
"""
:param msg: error message
:type msg: string
:param ex: exception causing this error (optional)
:type ex: exception
"""
Exception.__init__(self)
self.msg = msg
assert not isinstance(msg, Exception)
self.stack = []
if ex:
if not msg:
self.msg = str(ex)
if isinstance(ex, WafError):
self.stack = ex.stack
else:
self.stack = traceback.extract_tb(sys.exc_info()[2])
self.stack += traceback.extract_stack()[:-1]
self.verbose_msg = ''.join(traceback.format_list(self.stack))
def __str__(self):
return str(self.msg)
class BuildError(WafError):
"""Error raised during the build and install phases"""
def __init__(self, error_tasks=[]):
"""
:param error_tasks: tasks that could not complete normally
:type error_tasks: list of task objects
"""
self.tasks = error_tasks
WafError.__init__(self, self.format_error())
def format_error(self):
"""Formats the error messages from the tasks that failed"""
lst = ['Build failed']
for tsk in self.tasks:
txt = tsk.format_error()
if txt:
lst.append(txt)
return '\n'.join(lst)
class ConfigurationError(WafError):
"""Configuration exception raised in particular by :py:meth:`waflib.Context.Context.fatal`"""
pass
class TaskRescan(WafError):
"""Task-specific exception type signalling required signature recalculations"""
pass
class TaskNotReady(WafError):
"""Task-specific exception type signalling that task signatures cannot be computed"""
pass
| 1,713 | Python | .py | 57 | 27.263158 | 94 | 0.714286 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,574 | Build.py | projecthamster_hamster/waflib/Build.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Classes related to the build phase (build, clean, install, step, etc)
The inheritance tree is the following:
"""
import os, sys, errno, re, shutil, stat
try:
import cPickle
except ImportError:
import pickle as cPickle
from waflib import Node, Runner, TaskGen, Utils, ConfigSet, Task, Logs, Options, Context, Errors
CACHE_DIR = 'c4che'
"""Name of the cache directory"""
CACHE_SUFFIX = '_cache.py'
"""ConfigSet cache files for variants are written under :py:attr:´waflib.Build.CACHE_DIR´ in the form ´variant_name´_cache.py"""
INSTALL = 1337
"""Positive value '->' install, see :py:attr:`waflib.Build.BuildContext.is_install`"""
UNINSTALL = -1337
"""Negative value '<-' uninstall, see :py:attr:`waflib.Build.BuildContext.is_install`"""
SAVED_ATTRS = 'root node_sigs task_sigs imp_sigs raw_deps node_deps'.split()
"""Build class members to save between the runs; these should be all dicts
except for `root` which represents a :py:class:`waflib.Node.Node` instance
"""
CFG_FILES = 'cfg_files'
"""Files from the build directory to hash before starting the build (``config.h`` written during the configuration)"""
POST_AT_ONCE = 0
"""Post mode: all task generators are posted before any task executed"""
POST_LAZY = 1
"""Post mode: post the task generators group after group, the tasks in the next group are created when the tasks in the previous groups are done"""
PROTOCOL = -1
if sys.platform == 'cli':
PROTOCOL = 0
class BuildContext(Context.Context):
'''executes the build'''
cmd = 'build'
variant = ''
def __init__(self, **kw):
super(BuildContext, self).__init__(**kw)
self.is_install = 0
"""Non-zero value when installing or uninstalling file"""
self.top_dir = kw.get('top_dir', Context.top_dir)
"""See :py:attr:`waflib.Context.top_dir`; prefer :py:attr:`waflib.Build.BuildContext.srcnode`"""
self.out_dir = kw.get('out_dir', Context.out_dir)
"""See :py:attr:`waflib.Context.out_dir`; prefer :py:attr:`waflib.Build.BuildContext.bldnode`"""
self.run_dir = kw.get('run_dir', Context.run_dir)
"""See :py:attr:`waflib.Context.run_dir`"""
self.launch_dir = Context.launch_dir
"""See :py:attr:`waflib.Context.out_dir`; prefer :py:meth:`waflib.Build.BuildContext.launch_node`"""
self.post_mode = POST_LAZY
"""Whether to post the task generators at once or group-by-group (default is group-by-group)"""
self.cache_dir = kw.get('cache_dir')
if not self.cache_dir:
self.cache_dir = os.path.join(self.out_dir, CACHE_DIR)
self.all_envs = {}
"""Map names to :py:class:`waflib.ConfigSet.ConfigSet`, the empty string must map to the default environment"""
# ======================================= #
# cache variables
self.node_sigs = {}
"""Dict mapping build nodes to task identifier (uid), it indicates whether a task created a particular file (persists across builds)"""
self.task_sigs = {}
"""Dict mapping task identifiers (uid) to task signatures (persists across builds)"""
self.imp_sigs = {}
"""Dict mapping task identifiers (uid) to implicit task dependencies used for scanning targets (persists across builds)"""
self.node_deps = {}
"""Dict mapping task identifiers (uid) to node dependencies found by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
self.raw_deps = {}
"""Dict mapping task identifiers (uid) to custom data returned by :py:meth:`waflib.Task.Task.scan` (persists across builds)"""
self.task_gen_cache_names = {}
self.jobs = Options.options.jobs
"""Amount of jobs to run in parallel"""
self.targets = Options.options.targets
"""List of targets to build (default: \\*)"""
self.keep = Options.options.keep
"""Whether the build should continue past errors"""
self.progress_bar = Options.options.progress_bar
"""
Level of progress status:
0. normal output
1. progress bar
2. IDE output
3. No output at all
"""
# Manual dependencies.
self.deps_man = Utils.defaultdict(list)
"""Manual dependencies set by :py:meth:`waflib.Build.BuildContext.add_manual_dependency`"""
# just the structure here
self.current_group = 0
"""
Current build group
"""
self.groups = []
"""
List containing lists of task generators
"""
self.group_names = {}
"""
Map group names to the group lists. See :py:meth:`waflib.Build.BuildContext.add_group`
"""
for v in SAVED_ATTRS:
if not hasattr(self, v):
setattr(self, v, {})
def get_variant_dir(self):
"""Getter for the variant_dir attribute"""
if not self.variant:
return self.out_dir
return os.path.join(self.out_dir, os.path.normpath(self.variant))
variant_dir = property(get_variant_dir, None)
def __call__(self, *k, **kw):
"""
Create a task generator and add it to the current build group. The following forms are equivalent::
def build(bld):
tg = bld(a=1, b=2)
def build(bld):
tg = bld()
tg.a = 1
tg.b = 2
def build(bld):
tg = TaskGen.task_gen(a=1, b=2)
bld.add_to_group(tg, None)
:param group: group name to add the task generator to
:type group: string
"""
kw['bld'] = self
ret = TaskGen.task_gen(*k, **kw)
self.task_gen_cache_names = {} # reset the cache, each time
self.add_to_group(ret, group=kw.get('group'))
return ret
def __copy__(self):
"""
Build contexts cannot be copied
:raises: :py:class:`waflib.Errors.WafError`
"""
raise Errors.WafError('build contexts cannot be copied')
def load_envs(self):
"""
The configuration command creates files of the form ``build/c4che/NAMEcache.py``. This method
creates a :py:class:`waflib.ConfigSet.ConfigSet` instance for each ``NAME`` by reading those
files and stores them in :py:attr:`waflib.Build.BuildContext.allenvs`.
"""
node = self.root.find_node(self.cache_dir)
if not node:
raise Errors.WafError('The project was not configured: run "waf configure" first!')
lst = node.ant_glob('**/*%s' % CACHE_SUFFIX, quiet=True)
if not lst:
raise Errors.WafError('The cache directory is empty: reconfigure the project')
for x in lst:
name = x.path_from(node).replace(CACHE_SUFFIX, '').replace('\\', '/')
env = ConfigSet.ConfigSet(x.abspath())
self.all_envs[name] = env
for f in env[CFG_FILES]:
newnode = self.root.find_resource(f)
if not newnode or not newnode.exists():
raise Errors.WafError('Missing configuration file %r, reconfigure the project!' % f)
def init_dirs(self):
"""
Initialize the project directory and the build directory by creating the nodes
:py:attr:`waflib.Build.BuildContext.srcnode` and :py:attr:`waflib.Build.BuildContext.bldnode`
corresponding to ``top_dir`` and ``variant_dir`` respectively. The ``bldnode`` directory is
created if necessary.
"""
if not (os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)):
raise Errors.WafError('The project was not configured: run "waf configure" first!')
self.path = self.srcnode = self.root.find_dir(self.top_dir)
self.bldnode = self.root.make_node(self.variant_dir)
self.bldnode.mkdir()
def execute(self):
"""
Restore data from previous builds and call :py:meth:`waflib.Build.BuildContext.execute_build`.
Overrides from :py:func:`waflib.Context.Context.execute`
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.execute_build()
def execute_build(self):
"""
Execute the build by:
* reading the scripts (see :py:meth:`waflib.Context.Context.recurse`)
* calling :py:meth:`waflib.Build.BuildContext.pre_build` to call user build functions
* calling :py:meth:`waflib.Build.BuildContext.compile` to process the tasks
* calling :py:meth:`waflib.Build.BuildContext.post_build` to call user build functions
"""
Logs.info("Waf: Entering directory `%s'", self.variant_dir)
self.recurse([self.run_dir])
self.pre_build()
# display the time elapsed in the progress bar
self.timer = Utils.Timer()
try:
self.compile()
finally:
if self.progress_bar == 1 and sys.stderr.isatty():
c = self.producer.processed or 1
m = self.progress_line(c, c, Logs.colors.BLUE, Logs.colors.NORMAL)
Logs.info(m, extra={'stream': sys.stderr, 'c1': Logs.colors.cursor_off, 'c2' : Logs.colors.cursor_on})
Logs.info("Waf: Leaving directory `%s'", self.variant_dir)
try:
self.producer.bld = None
del self.producer
except AttributeError:
pass
self.post_build()
def restore(self):
"""
Load data from a previous run, sets the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`
"""
try:
env = ConfigSet.ConfigSet(os.path.join(self.cache_dir, 'build.config.py'))
except EnvironmentError:
pass
else:
if env.version < Context.HEXVERSION:
raise Errors.WafError('Project was configured with a different version of Waf, please reconfigure it')
for t in env.tools:
self.setup(**t)
dbfn = os.path.join(self.variant_dir, Context.DBFILE)
try:
data = Utils.readf(dbfn, 'rb')
except (EnvironmentError, EOFError):
# handle missing file/empty file
Logs.debug('build: Could not load the build cache %s (missing)', dbfn)
else:
try:
Node.pickle_lock.acquire()
Node.Nod3 = self.node_class
try:
data = cPickle.loads(data)
except Exception as e:
Logs.debug('build: Could not pickle the build cache %s: %r', dbfn, e)
else:
for x in SAVED_ATTRS:
setattr(self, x, data.get(x, {}))
finally:
Node.pickle_lock.release()
self.init_dirs()
def store(self):
"""
Store data for next runs, set the attributes listed in :py:const:`waflib.Build.SAVED_ATTRS`. Uses a temporary
file to avoid problems on ctrl+c.
"""
data = {}
for x in SAVED_ATTRS:
data[x] = getattr(self, x)
db = os.path.join(self.variant_dir, Context.DBFILE)
try:
Node.pickle_lock.acquire()
Node.Nod3 = self.node_class
x = cPickle.dumps(data, PROTOCOL)
finally:
Node.pickle_lock.release()
Utils.writef(db + '.tmp', x, m='wb')
try:
st = os.stat(db)
os.remove(db)
if not Utils.is_win32: # win32 has no chown but we're paranoid
os.chown(db + '.tmp', st.st_uid, st.st_gid)
except (AttributeError, OSError):
pass
# do not use shutil.move (copy is not thread-safe)
os.rename(db + '.tmp', db)
def compile(self):
"""
Run the build by creating an instance of :py:class:`waflib.Runner.Parallel`
The cache file is written when at least a task was executed.
:raises: :py:class:`waflib.Errors.BuildError` in case the build fails
"""
Logs.debug('build: compile()')
# delegate the producer-consumer logic to another object to reduce the complexity
self.producer = Runner.Parallel(self, self.jobs)
self.producer.biter = self.get_build_iterator()
try:
self.producer.start()
except KeyboardInterrupt:
if self.is_dirty():
self.store()
raise
else:
if self.is_dirty():
self.store()
if self.producer.error:
raise Errors.BuildError(self.producer.error)
def is_dirty(self):
return self.producer.dirty
def setup(self, tool, tooldir=None, funs=None):
"""
Import waf tools defined during the configuration::
def configure(conf):
conf.load('glib2')
def build(bld):
pass # glib2 is imported implicitly
:param tool: tool list
:type tool: list
:param tooldir: optional tool directory (sys.path)
:type tooldir: list of string
:param funs: unused variable
"""
if isinstance(tool, list):
for i in tool:
self.setup(i, tooldir)
return
module = Context.load_tool(tool, tooldir)
if hasattr(module, "setup"):
module.setup(self)
def get_env(self):
"""Getter for the env property"""
try:
return self.all_envs[self.variant]
except KeyError:
return self.all_envs['']
def set_env(self, val):
"""Setter for the env property"""
self.all_envs[self.variant] = val
env = property(get_env, set_env)
def add_manual_dependency(self, path, value):
"""
Adds a dependency from a node object to a value::
def build(bld):
bld.add_manual_dependency(
bld.path.find_resource('wscript'),
bld.root.find_resource('/etc/fstab'))
:param path: file path
:type path: string or :py:class:`waflib.Node.Node`
:param value: value to depend
:type value: :py:class:`waflib.Node.Node`, byte object, or function returning a byte object
"""
if not path:
raise ValueError('Invalid input path %r' % path)
if isinstance(path, Node.Node):
node = path
elif os.path.isabs(path):
node = self.root.find_resource(path)
else:
node = self.path.find_resource(path)
if not node:
raise ValueError('Could not find the path %r' % path)
if isinstance(value, list):
self.deps_man[node].extend(value)
else:
self.deps_man[node].append(value)
def launch_node(self):
"""Returns the launch directory as a :py:class:`waflib.Node.Node` object (cached)"""
try:
# private cache
return self.p_ln
except AttributeError:
self.p_ln = self.root.find_dir(self.launch_dir)
return self.p_ln
def hash_env_vars(self, env, vars_lst):
"""
Hashes configuration set variables::
def build(bld):
bld.hash_env_vars(bld.env, ['CXX', 'CC'])
This method uses an internal cache.
:param env: Configuration Set
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:param vars_lst: list of variables
:type vars_list: list of string
"""
if not env.table:
env = env.parent
if not env:
return Utils.SIG_NIL
idx = str(id(env)) + str(vars_lst)
try:
cache = self.cache_env
except AttributeError:
cache = self.cache_env = {}
else:
try:
return self.cache_env[idx]
except KeyError:
pass
lst = [env[a] for a in vars_lst]
cache[idx] = ret = Utils.h_list(lst)
Logs.debug('envhash: %s %r', Utils.to_hex(ret), lst)
return ret
def get_tgen_by_name(self, name):
"""
Fetches a task generator by its name or its target attribute;
the name must be unique in a build::
def build(bld):
tg = bld(name='foo')
tg == bld.get_tgen_by_name('foo')
This method use a private internal cache.
:param name: Task generator name
:raises: :py:class:`waflib.Errors.WafError` in case there is no task genenerator by that name
"""
cache = self.task_gen_cache_names
if not cache:
# create the index lazily
for g in self.groups:
for tg in g:
try:
cache[tg.name] = tg
except AttributeError:
# raised if not a task generator, which should be uncommon
pass
try:
return cache[name]
except KeyError:
raise Errors.WafError('Could not find a task generator for the name %r' % name)
def progress_line(self, idx, total, col1, col2):
"""
Computes a progress bar line displayed when running ``waf -p``
:returns: progress bar line
:rtype: string
"""
if not sys.stderr.isatty():
return ''
n = len(str(total))
Utils.rot_idx += 1
ind = Utils.rot_chr[Utils.rot_idx % 4]
pc = (100. * idx)/total
fs = "[%%%dd/%%d][%%s%%2d%%%%%%s][%s][" % (n, ind)
left = fs % (idx, total, col1, pc, col2)
right = '][%s%s%s]' % (col1, self.timer, col2)
cols = Logs.get_term_cols() - len(left) - len(right) + 2*len(col1) + 2*len(col2)
if cols < 7:
cols = 7
ratio = ((cols * idx)//total) - 1
bar = ('='*ratio+'>').ljust(cols)
msg = Logs.indicator % (left, bar, right)
return msg
def declare_chain(self, *k, **kw):
"""
Wraps :py:func:`waflib.TaskGen.declare_chain` for convenience
"""
return TaskGen.declare_chain(*k, **kw)
def pre_build(self):
"""Executes user-defined methods before the build starts, see :py:meth:`waflib.Build.BuildContext.add_pre_fun`"""
for m in getattr(self, 'pre_funs', []):
m(self)
def post_build(self):
"""Executes user-defined methods after the build is successful, see :py:meth:`waflib.Build.BuildContext.add_post_fun`"""
for m in getattr(self, 'post_funs', []):
m(self)
def add_pre_fun(self, meth):
"""
Binds a callback method to execute after the scripts are read and before the build starts::
def mycallback(bld):
print("Hello, world!")
def build(bld):
bld.add_pre_fun(mycallback)
"""
try:
self.pre_funs.append(meth)
except AttributeError:
self.pre_funs = [meth]
def add_post_fun(self, meth):
"""
Binds a callback method to execute immediately after the build is successful::
def call_ldconfig(bld):
bld.exec_command('/sbin/ldconfig')
def build(bld):
if bld.cmd == 'install':
bld.add_pre_fun(call_ldconfig)
"""
try:
self.post_funs.append(meth)
except AttributeError:
self.post_funs = [meth]
def get_group(self, x):
"""
Returns the build group named `x`, or the current group if `x` is None
:param x: name or number or None
:type x: string, int or None
"""
if not self.groups:
self.add_group()
if x is None:
return self.groups[self.current_group]
if x in self.group_names:
return self.group_names[x]
return self.groups[x]
def add_to_group(self, tgen, group=None):
"""Adds a task or a task generator to the build; there is no attempt to remove it if it was already added."""
assert(isinstance(tgen, TaskGen.task_gen) or isinstance(tgen, Task.Task))
tgen.bld = self
self.get_group(group).append(tgen)
def get_group_name(self, g):
"""
Returns the name of the input build group
:param g: build group object or build group index
:type g: integer or list
:return: name
:rtype: string
"""
if not isinstance(g, list):
g = self.groups[g]
for x in self.group_names:
if id(self.group_names[x]) == id(g):
return x
return ''
def get_group_idx(self, tg):
"""
Returns the index of the group containing the task generator given as argument::
def build(bld):
tg = bld(name='nada')
0 == bld.get_group_idx(tg)
:param tg: Task generator object
:type tg: :py:class:`waflib.TaskGen.task_gen`
:rtype: int
"""
se = id(tg)
for i, tmp in enumerate(self.groups):
for t in tmp:
if id(t) == se:
return i
return None
def add_group(self, name=None, move=True):
"""
Adds a new group of tasks/task generators. By default the new group becomes
the default group for new task generators (make sure to create build groups in order).
:param name: name for this group
:type name: string
:param move: set this new group as default group (True by default)
:type move: bool
:raises: :py:class:`waflib.Errors.WafError` if a group by the name given already exists
"""
if name and name in self.group_names:
raise Errors.WafError('add_group: name %s already present', name)
g = []
self.group_names[name] = g
self.groups.append(g)
if move:
self.current_group = len(self.groups) - 1
def set_group(self, idx):
"""
Sets the build group at position idx as current so that newly added
task generators are added to this one by default::
def build(bld):
bld(rule='touch ${TGT}', target='foo.txt')
bld.add_group() # now the current group is 1
bld(rule='touch ${TGT}', target='bar.txt')
bld.set_group(0) # now the current group is 0
bld(rule='touch ${TGT}', target='truc.txt') # build truc.txt before bar.txt
:param idx: group name or group index
:type idx: string or int
"""
if isinstance(idx, str):
g = self.group_names[idx]
for i, tmp in enumerate(self.groups):
if id(g) == id(tmp):
self.current_group = i
break
else:
self.current_group = idx
def total(self):
"""
Approximate task count: this value may be inaccurate if task generators
are posted lazily (see :py:attr:`waflib.Build.BuildContext.post_mode`).
The value :py:attr:`waflib.Runner.Parallel.total` is updated during the task execution.
:rtype: int
"""
total = 0
for group in self.groups:
for tg in group:
try:
total += len(tg.tasks)
except AttributeError:
total += 1
return total
def get_targets(self):
"""
This method returns a pair containing the index of the last build group to post,
and the list of task generator objects corresponding to the target names.
This is used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
to perform partial builds::
$ waf --targets=myprogram,myshlib
:return: the minimum build group index, and list of task generators
:rtype: tuple
"""
to_post = []
min_grp = 0
for name in self.targets.split(','):
tg = self.get_tgen_by_name(name)
m = self.get_group_idx(tg)
if m > min_grp:
min_grp = m
to_post = [tg]
elif m == min_grp:
to_post.append(tg)
return (min_grp, to_post)
def get_all_task_gen(self):
"""
Returns a list of all task generators for troubleshooting purposes.
"""
lst = []
for g in self.groups:
lst.extend(g)
return lst
def post_group(self):
"""
Post task generators from the group indexed by self.current_group; used internally
by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
"""
def tgpost(tg):
try:
f = tg.post
except AttributeError:
pass
else:
f()
if self.targets == '*':
for tg in self.groups[self.current_group]:
tgpost(tg)
elif self.targets:
if self.current_group < self._min_grp:
for tg in self.groups[self.current_group]:
tgpost(tg)
else:
for tg in self._exact_tg:
tg.post()
else:
ln = self.launch_node()
if ln.is_child_of(self.bldnode):
if Logs.verbose > 1:
Logs.warn('Building from the build directory, forcing --targets=*')
ln = self.srcnode
elif not ln.is_child_of(self.srcnode):
if Logs.verbose > 1:
Logs.warn('CWD %s is not under %s, forcing --targets=* (run distclean?)', ln.abspath(), self.srcnode.abspath())
ln = self.srcnode
def is_post(tg, ln):
try:
p = tg.path
except AttributeError:
pass
else:
if p.is_child_of(ln):
return True
def is_post_group():
for i, g in enumerate(self.groups):
if i > self.current_group:
for tg in g:
if is_post(tg, ln):
return True
if self.post_mode == POST_LAZY and ln != self.srcnode:
# partial folder builds require all targets from a previous build group
if is_post_group():
ln = self.srcnode
for tg in self.groups[self.current_group]:
if is_post(tg, ln):
tgpost(tg)
def get_tasks_group(self, idx):
"""
Returns all task instances for the build group at position idx,
used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
:rtype: list of :py:class:`waflib.Task.Task`
"""
tasks = []
for tg in self.groups[idx]:
try:
tasks.extend(tg.tasks)
except AttributeError: # not a task generator
tasks.append(tg)
return tasks
def get_build_iterator(self):
"""
Creates a Python generator object that returns lists of tasks that may be processed in parallel.
:return: tasks which can be executed immediately
:rtype: generator returning lists of :py:class:`waflib.Task.Task`
"""
if self.targets and self.targets != '*':
(self._min_grp, self._exact_tg) = self.get_targets()
if self.post_mode != POST_LAZY:
for self.current_group, _ in enumerate(self.groups):
self.post_group()
for self.current_group, _ in enumerate(self.groups):
# first post the task generators for the group
if self.post_mode != POST_AT_ONCE:
self.post_group()
# then extract the tasks
tasks = self.get_tasks_group(self.current_group)
# if the constraints are set properly (ext_in/ext_out, before/after)
# the call to set_file_constraints may be removed (can be a 15% penalty on no-op rebuilds)
# (but leave set_file_constraints for the installation step)
#
# if the tasks have only files, set_file_constraints is required but set_precedence_constraints is not necessary
#
Task.set_file_constraints(tasks)
Task.set_precedence_constraints(tasks)
self.cur_tasks = tasks
if tasks:
yield tasks
while 1:
# the build stops once there are no tasks to process
yield []
def install_files(self, dest, files, **kw):
"""
Creates a task generator to install files on the system::
def build(bld):
bld.install_files('${DATADIR}', self.path.find_resource('wscript'))
:param dest: path representing the destination directory
:type dest: :py:class:`waflib.Node.Node` or string (absolute path)
:param files: input files
:type files: list of strings or list of :py:class:`waflib.Node.Node`
:param env: configuration set to expand *dest*
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:param relative_trick: preserve the folder hierarchy when installing whole folders
:type relative_trick: bool
:param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
:type cwd: :py:class:`waflib.Node.Node`
:param postpone: execute the task immediately to perform the installation (False by default)
:type postpone: bool
"""
assert(dest)
tg = self(features='install_task', install_to=dest, install_from=files, **kw)
tg.dest = tg.install_to
tg.type = 'install_files'
if not kw.get('postpone', True):
tg.post()
return tg
def install_as(self, dest, srcfile, **kw):
"""
Creates a task generator to install a file on the system with a different name::
def build(bld):
bld.install_as('${PREFIX}/bin', 'myapp', chmod=Utils.O755)
:param dest: destination file
:type dest: :py:class:`waflib.Node.Node` or string (absolute path)
:param srcfile: input file
:type srcfile: string or :py:class:`waflib.Node.Node`
:param cwd: parent node for searching srcfile, when srcfile is not an instance of :py:class:`waflib.Node.Node`
:type cwd: :py:class:`waflib.Node.Node`
:param env: configuration set for performing substitutions in dest
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:param postpone: execute the task immediately to perform the installation (False by default)
:type postpone: bool
"""
assert(dest)
tg = self(features='install_task', install_to=dest, install_from=srcfile, **kw)
tg.dest = tg.install_to
tg.type = 'install_as'
if not kw.get('postpone', True):
tg.post()
return tg
def symlink_as(self, dest, src, **kw):
"""
Creates a task generator to install a symlink::
def build(bld):
bld.symlink_as('${PREFIX}/lib/libfoo.so', 'libfoo.so.1.2.3')
:param dest: absolute path of the symlink
:type dest: :py:class:`waflib.Node.Node` or string (absolute path)
:param src: link contents, which is a relative or absolute path which may exist or not
:type src: string
:param env: configuration set for performing substitutions in dest
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:param add: add the task created to a build group - set ``False`` only if the installation task is created after the build has started
:type add: bool
:param postpone: execute the task immediately to perform the installation
:type postpone: bool
:param relative_trick: make the symlink relative (default: ``False``)
:type relative_trick: bool
"""
assert(dest)
tg = self(features='install_task', install_to=dest, install_from=src, **kw)
tg.dest = tg.install_to
tg.type = 'symlink_as'
tg.link = src
# TODO if add: self.add_to_group(tsk)
if not kw.get('postpone', True):
tg.post()
return tg
@TaskGen.feature('install_task')
@TaskGen.before_method('process_rule', 'process_source')
def process_install_task(self):
"""Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally."""
self.add_install_task(**self.__dict__)
@TaskGen.taskgen_method
def add_install_task(self, **kw):
"""
Creates the installation task for the current task generator, and executes it immediately if necessary
:returns: An installation task
:rtype: :py:class:`waflib.Build.inst`
"""
if not self.bld.is_install:
return
if not kw['install_to']:
return
if kw['type'] == 'symlink_as' and Utils.is_win32:
if kw.get('win32_install'):
kw['type'] = 'install_as'
else:
# just exit
return
tsk = self.install_task = self.create_task('inst')
tsk.chmod = kw.get('chmod', Utils.O644)
tsk.link = kw.get('link', '') or kw.get('install_from', '')
tsk.relative_trick = kw.get('relative_trick', False)
tsk.type = kw['type']
tsk.install_to = tsk.dest = kw['install_to']
tsk.install_from = kw['install_from']
tsk.relative_base = kw.get('cwd') or kw.get('relative_base', self.path)
tsk.install_user = kw.get('install_user')
tsk.install_group = kw.get('install_group')
tsk.init_files()
if not kw.get('postpone', True):
tsk.run_now()
return tsk
@TaskGen.taskgen_method
def add_install_files(self, **kw):
"""
Creates an installation task for files
:returns: An installation task
:rtype: :py:class:`waflib.Build.inst`
"""
kw['type'] = 'install_files'
return self.add_install_task(**kw)
@TaskGen.taskgen_method
def add_install_as(self, **kw):
"""
Creates an installation task for a single file
:returns: An installation task
:rtype: :py:class:`waflib.Build.inst`
"""
kw['type'] = 'install_as'
return self.add_install_task(**kw)
@TaskGen.taskgen_method
def add_symlink_as(self, **kw):
"""
Creates an installation task for a symbolic link
:returns: An installation task
:rtype: :py:class:`waflib.Build.inst`
"""
kw['type'] = 'symlink_as'
return self.add_install_task(**kw)
class inst(Task.Task):
"""Task that installs files or symlinks; it is typically executed by :py:class:`waflib.Build.InstallContext` and :py:class:`waflib.Build.UnInstallContext`"""
def __str__(self):
"""Returns an empty string to disable the standard task display"""
return ''
def uid(self):
"""Returns a unique identifier for the task"""
lst = self.inputs + self.outputs + [self.link, self.generator.path.abspath()]
return Utils.h_list(lst)
def init_files(self):
"""
Initializes the task input and output nodes
"""
if self.type == 'symlink_as':
inputs = []
else:
inputs = self.generator.to_nodes(self.install_from)
if self.type == 'install_as':
assert len(inputs) == 1
self.set_inputs(inputs)
dest = self.get_install_path()
outputs = []
if self.type == 'symlink_as':
if self.relative_trick:
self.link = os.path.relpath(self.link, os.path.dirname(dest))
outputs.append(self.generator.bld.root.make_node(dest))
elif self.type == 'install_as':
outputs.append(self.generator.bld.root.make_node(dest))
else:
for y in inputs:
if self.relative_trick:
destfile = os.path.join(dest, y.path_from(self.relative_base))
else:
destfile = os.path.join(dest, y.name)
outputs.append(self.generator.bld.root.make_node(destfile))
self.set_outputs(outputs)
def runnable_status(self):
"""
Installation tasks are always executed, so this method returns either :py:const:`waflib.Task.ASK_LATER` or :py:const:`waflib.Task.RUN_ME`.
"""
ret = super(inst, self).runnable_status()
if ret == Task.SKIP_ME and self.generator.bld.is_install:
return Task.RUN_ME
return ret
def post_run(self):
"""
Disables any post-run operations
"""
pass
def get_install_path(self, destdir=True):
"""
Returns the destination path where files will be installed, pre-pending `destdir`.
Relative paths will be interpreted relative to `PREFIX` if no `destdir` is given.
:rtype: string
"""
if isinstance(self.install_to, Node.Node):
dest = self.install_to.abspath()
else:
dest = os.path.normpath(Utils.subst_vars(self.install_to, self.env))
if not os.path.isabs(dest):
dest = os.path.join(self.env.PREFIX, dest)
if destdir and Options.options.destdir:
dest = Options.options.destdir.rstrip(os.sep) + os.sep + os.path.splitdrive(dest)[1].lstrip(os.sep)
return dest
def copy_fun(self, src, tgt):
"""
Copies a file from src to tgt, preserving permissions and trying to work
around path limitations on Windows platforms. On Unix-like platforms,
the owner/group of the target file may be set through install_user/install_group
:param src: absolute path
:type src: string
:param tgt: absolute path
:type tgt: string
"""
# override this if you want to strip executables
# kw['tsk'].source is the task that created the files in the build
if Utils.is_win32 and len(tgt) > 259 and not tgt.startswith('\\\\?\\'):
tgt = '\\\\?\\' + tgt
shutil.copy2(src, tgt)
self.fix_perms(tgt)
def rm_empty_dirs(self, tgt):
"""
Removes empty folders recursively when uninstalling.
:param tgt: absolute path
:type tgt: string
"""
while tgt:
tgt = os.path.dirname(tgt)
try:
os.rmdir(tgt)
except OSError:
break
def run(self):
"""
Performs file or symlink installation
"""
is_install = self.generator.bld.is_install
if not is_install: # unnecessary?
return
for x in self.outputs:
if is_install == INSTALL:
x.parent.mkdir()
if self.type == 'symlink_as':
fun = is_install == INSTALL and self.do_link or self.do_unlink
fun(self.link, self.outputs[0].abspath())
else:
fun = is_install == INSTALL and self.do_install or self.do_uninstall
launch_node = self.generator.bld.launch_node()
for x, y in zip(self.inputs, self.outputs):
fun(x.abspath(), y.abspath(), x.path_from(launch_node))
def run_now(self):
"""
Try executing the installation task right now
:raises: :py:class:`waflib.Errors.TaskNotReady`
"""
status = self.runnable_status()
if status not in (Task.RUN_ME, Task.SKIP_ME):
raise Errors.TaskNotReady('Could not process %r: status %r' % (self, status))
self.run()
self.hasrun = Task.SUCCESS
def do_install(self, src, tgt, lbl, **kw):
"""
Copies a file from src to tgt with given file permissions. The actual copy is only performed
if the source and target file sizes or timestamps differ. When the copy occurs,
the file is always first removed and then copied so as to prevent stale inodes.
:param src: file name as absolute path
:type src: string
:param tgt: file destination, as absolute path
:type tgt: string
:param lbl: file source description
:type lbl: string
:param chmod: installation mode
:type chmod: int
:raises: :py:class:`waflib.Errors.WafError` if the file cannot be written
"""
if not Options.options.force:
# check if the file is already there to avoid a copy
try:
st1 = os.stat(tgt)
st2 = os.stat(src)
except OSError:
pass
else:
# same size and identical timestamps -> make no copy
if st1.st_mtime + 2 >= st2.st_mtime and st1.st_size == st2.st_size:
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s- install %s%s%s (from %s)', c1, c2, tgt, c1, lbl)
return False
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s+ install %s%s%s (from %s)', c1, c2, tgt, c1, lbl)
# Give best attempt at making destination overwritable,
# like the 'install' utility used by 'make install' does.
try:
os.chmod(tgt, Utils.O644 | stat.S_IMODE(os.stat(tgt).st_mode))
except EnvironmentError:
pass
# following is for shared libs and stale inodes (-_-)
try:
os.remove(tgt)
except OSError:
pass
try:
self.copy_fun(src, tgt)
except EnvironmentError as e:
if not os.path.exists(src):
Logs.error('File %r does not exist', src)
elif not os.path.isfile(src):
Logs.error('Input %r is not a file', src)
raise Errors.WafError('Could not install the file %r' % tgt, e)
def fix_perms(self, tgt):
"""
Change the ownership of the file/folder/link pointed by the given path
This looks up for `install_user` or `install_group` attributes
on the task or on the task generator::
def build(bld):
bld.install_as('${PREFIX}/wscript',
'wscript',
install_user='nobody', install_group='nogroup')
bld.symlink_as('${PREFIX}/wscript_link',
Utils.subst_vars('${PREFIX}/wscript', bld.env),
install_user='nobody', install_group='nogroup')
"""
if not Utils.is_win32:
user = getattr(self, 'install_user', None) or getattr(self.generator, 'install_user', None)
group = getattr(self, 'install_group', None) or getattr(self.generator, 'install_group', None)
if user or group:
Utils.lchown(tgt, user or -1, group or -1)
if not os.path.islink(tgt):
os.chmod(tgt, self.chmod)
def do_link(self, src, tgt, **kw):
"""
Creates a symlink from tgt to src.
:param src: file name as absolute path
:type src: string
:param tgt: file destination, as absolute path
:type tgt: string
"""
if os.path.islink(tgt) and os.readlink(tgt) == src:
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s- symlink %s%s%s (to %s)', c1, c2, tgt, c1, src)
else:
try:
os.remove(tgt)
except OSError:
pass
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s+ symlink %s%s%s (to %s)', c1, c2, tgt, c1, src)
os.symlink(src, tgt)
self.fix_perms(tgt)
def do_uninstall(self, src, tgt, lbl, **kw):
"""
See :py:meth:`waflib.Build.inst.do_install`
"""
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s- remove %s%s%s', c1, c2, tgt, c1)
#self.uninstall.append(tgt)
try:
os.remove(tgt)
except OSError as e:
if e.errno != errno.ENOENT:
if not getattr(self, 'uninstall_error', None):
self.uninstall_error = True
Logs.warn('build: some files could not be uninstalled (retry with -vv to list them)')
if Logs.verbose > 1:
Logs.warn('Could not remove %s (error code %r)', e.filename, e.errno)
self.rm_empty_dirs(tgt)
def do_unlink(self, src, tgt, **kw):
"""
See :py:meth:`waflib.Build.inst.do_link`
"""
try:
if not self.generator.bld.progress_bar:
c1 = Logs.colors.NORMAL
c2 = Logs.colors.BLUE
Logs.info('%s- remove %s%s%s', c1, c2, tgt, c1)
os.remove(tgt)
except OSError:
pass
self.rm_empty_dirs(tgt)
class InstallContext(BuildContext):
'''installs the targets on the system'''
cmd = 'install'
def __init__(self, **kw):
super(InstallContext, self).__init__(**kw)
self.is_install = INSTALL
class UninstallContext(InstallContext):
'''removes the targets installed'''
cmd = 'uninstall'
def __init__(self, **kw):
super(UninstallContext, self).__init__(**kw)
self.is_install = UNINSTALL
class CleanContext(BuildContext):
'''cleans the project'''
cmd = 'clean'
def execute(self):
"""
See :py:func:`waflib.Build.BuildContext.execute`.
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
try:
self.clean()
finally:
self.store()
def clean(self):
"""
Remove most files from the build directory, and reset all caches.
Custom lists of files to clean can be declared as `bld.clean_files`.
For example, exclude `build/program/myprogram` from getting removed::
def build(bld):
bld.clean_files = bld.bldnode.ant_glob('**',
excl='.lock* config.log c4che/* config.h program/myprogram',
quiet=True, generator=True)
"""
Logs.debug('build: clean called')
if hasattr(self, 'clean_files'):
for n in self.clean_files:
n.delete()
elif self.bldnode != self.srcnode:
# would lead to a disaster if top == out
lst = []
for env in self.all_envs.values():
lst.extend(self.root.find_or_declare(f) for f in env[CFG_FILES])
excluded_dirs = '.lock* *conf_check_*/** config.log %s/*' % CACHE_DIR
for n in self.bldnode.ant_glob('**/*', excl=excluded_dirs, quiet=True):
if n in lst:
continue
n.delete()
self.root.children = {}
for v in SAVED_ATTRS:
if v == 'root':
continue
setattr(self, v, {})
class ListContext(BuildContext):
'''lists the targets to execute'''
cmd = 'list'
def execute(self):
"""
In addition to printing the name of each build target,
a description column will include text for each task
generator which has a "description" field set.
See :py:func:`waflib.Build.BuildContext.execute`.
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
self.pre_build()
# display the time elapsed in the progress bar
self.timer = Utils.Timer()
for g in self.groups:
for tg in g:
try:
f = tg.post
except AttributeError:
pass
else:
f()
try:
# force the cache initialization
self.get_tgen_by_name('')
except Errors.WafError:
pass
targets = sorted(self.task_gen_cache_names)
# figure out how much to left-justify, for largest target name
line_just = max(len(t) for t in targets) if targets else 0
for target in targets:
tgen = self.task_gen_cache_names[target]
# Support displaying the description for the target
# if it was set on the tgen
descript = getattr(tgen, 'description', '')
if descript:
target = target.ljust(line_just)
descript = ': %s' % descript
Logs.pprint('GREEN', target, label=descript)
class StepContext(BuildContext):
'''executes tasks in a step-by-step fashion, for debugging'''
cmd = 'step'
def __init__(self, **kw):
super(StepContext, self).__init__(**kw)
self.files = Options.options.files
def compile(self):
"""
Overrides :py:meth:`waflib.Build.BuildContext.compile` to perform a partial build
on tasks matching the input/output pattern given (regular expression matching)::
$ waf step --files=foo.c,bar.c,in:truc.c,out:bar.o
$ waf step --files=in:foo.cpp.1.o # link task only
"""
if not self.files:
Logs.warn('Add a pattern for the debug build, for example "waf step --files=main.c,app"')
BuildContext.compile(self)
return
targets = []
if self.targets and self.targets != '*':
targets = self.targets.split(',')
for g in self.groups:
for tg in g:
if targets and tg.name not in targets:
continue
try:
f = tg.post
except AttributeError:
pass
else:
f()
for pat in self.files.split(','):
matcher = self.get_matcher(pat)
for tg in g:
if isinstance(tg, Task.Task):
lst = [tg]
else:
lst = tg.tasks
for tsk in lst:
do_exec = False
for node in tsk.inputs:
if matcher(node, output=False):
do_exec = True
break
for node in tsk.outputs:
if matcher(node, output=True):
do_exec = True
break
if do_exec:
ret = tsk.run()
Logs.info('%s -> exit %r', tsk, ret)
def get_matcher(self, pat):
"""
Converts a step pattern into a function
:param: pat: pattern of the form in:truc.c,out:bar.o
:returns: Python function that uses Node objects as inputs and returns matches
:rtype: function
"""
# this returns a function
inn = True
out = True
if pat.startswith('in:'):
out = False
pat = pat.replace('in:', '')
elif pat.startswith('out:'):
inn = False
pat = pat.replace('out:', '')
anode = self.root.find_node(pat)
pattern = None
if not anode:
if not pat.startswith('^'):
pat = '^.+?%s' % pat
if not pat.endswith('$'):
pat = '%s$' % pat
pattern = re.compile(pat)
def match(node, output):
if output and not out:
return False
if not output and not inn:
return False
if anode:
return anode == node
else:
return pattern.match(node.abspath())
return match
class EnvContext(BuildContext):
"""Subclass EnvContext to create commands that require configuration data in 'env'"""
fun = cmd = None
def execute(self):
"""
See :py:func:`waflib.Build.BuildContext.execute`.
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
| 43,520 | Python | .py | 1,269 | 30.669031 | 158 | 0.694038 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,575 | TaskGen.py | projecthamster_hamster/waflib/TaskGen.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Task generators
The class :py:class:`waflib.TaskGen.task_gen` encapsulates the creation of task objects (low-level code)
The instances can have various parameters, but the creation of task nodes (Task.py)
is deferred. To achieve this, various methods are called from the method "apply"
"""
import copy, re, os, functools
from waflib import Task, Utils, Logs, Errors, ConfigSet, Node
feats = Utils.defaultdict(set)
"""remember the methods declaring features"""
HEADER_EXTS = ['.h', '.hpp', '.hxx', '.hh']
class task_gen(object):
"""
Instances of this class create :py:class:`waflib.Task.Task` when
calling the method :py:meth:`waflib.TaskGen.task_gen.post` from the main thread.
A few notes:
* The methods to call (*self.meths*) can be specified dynamically (removing, adding, ..)
* The 'features' are used to add methods to self.meths and then execute them
* The attribute 'path' is a node representing the location of the task generator
* The tasks created are added to the attribute *tasks*
* The attribute 'idx' is a counter of task generators in the same path
"""
mappings = Utils.ordered_iter_dict()
"""Mappings are global file extension mappings that are retrieved in the order of definition"""
prec = Utils.defaultdict(set)
"""Dict that holds the precedence execution rules for task generator methods"""
def __init__(self, *k, **kw):
"""
Task generator objects predefine various attributes (source, target) for possible
processing by process_rule (make-like rules) or process_source (extensions, misc methods)
Tasks are stored on the attribute 'tasks'. They are created by calling methods
listed in ``self.meths`` or referenced in the attribute ``features``
A topological sort is performed to execute the methods in correct order.
The extra key/value elements passed in ``kw`` are set as attributes
"""
self.source = []
self.target = ''
self.meths = []
"""
List of method names to execute (internal)
"""
self.features = []
"""
List of feature names for bringing new methods in
"""
self.tasks = []
"""
Tasks created are added to this list
"""
if not 'bld' in kw:
# task generators without a build context :-/
self.env = ConfigSet.ConfigSet()
self.idx = 0
self.path = None
else:
self.bld = kw['bld']
self.env = self.bld.env.derive()
self.path = kw.get('path', self.bld.path) # by default, emulate chdir when reading scripts
# Provide a unique index per folder
# This is part of a measure to prevent output file name collisions
path = self.path.abspath()
try:
self.idx = self.bld.idx[path] = self.bld.idx.get(path, 0) + 1
except AttributeError:
self.bld.idx = {}
self.idx = self.bld.idx[path] = 1
# Record the global task generator count
try:
self.tg_idx_count = self.bld.tg_idx_count = self.bld.tg_idx_count + 1
except AttributeError:
self.tg_idx_count = self.bld.tg_idx_count = 1
for key, val in kw.items():
setattr(self, key, val)
def __str__(self):
"""Debugging helper"""
return "<task_gen %r declared in %s>" % (self.name, self.path.abspath())
def __repr__(self):
"""Debugging helper"""
lst = []
for x in self.__dict__:
if x not in ('env', 'bld', 'compiled_tasks', 'tasks'):
lst.append("%s=%s" % (x, repr(getattr(self, x))))
return "bld(%s) in %s" % (", ".join(lst), self.path.abspath())
def get_cwd(self):
"""
Current working directory for the task generator, defaults to the build directory.
This is still used in a few places but it should disappear at some point as the classes
define their own working directory.
:rtype: :py:class:`waflib.Node.Node`
"""
return self.bld.bldnode
def get_name(self):
"""
If the attribute ``name`` is not set on the instance,
the name is computed from the target name::
def build(bld):
x = bld(name='foo')
x.get_name() # foo
y = bld(target='bar')
y.get_name() # bar
:rtype: string
:return: name of this task generator
"""
try:
return self._name
except AttributeError:
if isinstance(self.target, list):
lst = [str(x) for x in self.target]
name = self._name = ','.join(lst)
else:
name = self._name = str(self.target)
return name
def set_name(self, name):
self._name = name
name = property(get_name, set_name)
def to_list(self, val):
"""
Ensures that a parameter is a list, see :py:func:`waflib.Utils.to_list`
:type val: string or list of string
:param val: input to return as a list
:rtype: list
"""
if isinstance(val, str):
return val.split()
else:
return val
def post(self):
"""
Creates tasks for this task generators. The following operations are performed:
#. The body of this method is called only once and sets the attribute ``posted``
#. The attribute ``features`` is used to add more methods in ``self.meths``
#. The methods are sorted by the precedence table ``self.prec`` or `:waflib:attr:waflib.TaskGen.task_gen.prec`
#. The methods are then executed in order
#. The tasks created are added to :py:attr:`waflib.TaskGen.task_gen.tasks`
"""
if getattr(self, 'posted', None):
return False
self.posted = True
keys = set(self.meths)
keys.update(feats['*'])
# add the methods listed in the features
self.features = Utils.to_list(self.features)
for x in self.features:
st = feats[x]
if st:
keys.update(st)
elif not x in Task.classes:
Logs.warn('feature %r does not exist - bind at least one method to it?', x)
# copy the precedence table
prec = {}
prec_tbl = self.prec
for x in prec_tbl:
if x in keys:
prec[x] = prec_tbl[x]
# elements disconnected
tmp = []
for a in keys:
for x in prec.values():
if a in x:
break
else:
tmp.append(a)
tmp.sort(reverse=True)
# topological sort
out = []
while tmp:
e = tmp.pop()
if e in keys:
out.append(e)
try:
nlst = prec[e]
except KeyError:
pass
else:
del prec[e]
for x in nlst:
for y in prec:
if x in prec[y]:
break
else:
tmp.append(x)
tmp.sort(reverse=True)
if prec:
buf = ['Cycle detected in the method execution:']
for k, v in prec.items():
buf.append('- %s after %s' % (k, [x for x in v if x in prec]))
raise Errors.WafError('\n'.join(buf))
self.meths = out
# then we run the methods in order
Logs.debug('task_gen: posting %s %d', self, id(self))
for x in out:
try:
v = getattr(self, x)
except AttributeError:
raise Errors.WafError('%r is not a valid task generator method' % x)
Logs.debug('task_gen: -> %s (%d)', x, id(self))
v()
Logs.debug('task_gen: posted %s', self.name)
return True
def get_hook(self, node):
"""
Returns the ``@extension`` method to call for a Node of a particular extension.
:param node: Input file to process
:type node: :py:class:`waflib.Tools.Node.Node`
:return: A method able to process the input node by looking at the extension
:rtype: function
"""
name = node.name
for k in self.mappings:
try:
if name.endswith(k):
return self.mappings[k]
except TypeError:
# regexps objects
if k.match(name):
return self.mappings[k]
keys = list(self.mappings.keys())
raise Errors.WafError("File %r has no mapping in %r (load a waf tool?)" % (node, keys))
def create_task(self, name, src=None, tgt=None, **kw):
"""
Creates task instances.
:param name: task class name
:type name: string
:param src: input nodes
:type src: list of :py:class:`waflib.Tools.Node.Node`
:param tgt: output nodes
:type tgt: list of :py:class:`waflib.Tools.Node.Node`
:return: A task object
:rtype: :py:class:`waflib.Task.Task`
"""
task = Task.classes[name](env=self.env.derive(), generator=self)
if src:
task.set_inputs(src)
if tgt:
task.set_outputs(tgt)
task.__dict__.update(kw)
self.tasks.append(task)
return task
def clone(self, env):
"""
Makes a copy of a task generator. Once the copy is made, it is necessary to ensure that the
it does not create the same output files as the original, or the same files may
be compiled several times.
:param env: A configuration set
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:return: A copy
:rtype: :py:class:`waflib.TaskGen.task_gen`
"""
newobj = self.bld()
for x in self.__dict__:
if x in ('env', 'bld'):
continue
elif x in ('path', 'features'):
setattr(newobj, x, getattr(self, x))
else:
setattr(newobj, x, copy.copy(getattr(self, x)))
newobj.posted = False
if isinstance(env, str):
newobj.env = self.bld.all_envs[env].derive()
else:
newobj.env = env.derive()
return newobj
def declare_chain(name='', rule=None, reentrant=None, color='BLUE',
ext_in=[], ext_out=[], before=[], after=[], decider=None, scan=None, install_path=None, shell=False):
"""
Creates a new mapping and a task class for processing files by extension.
See Tools/flex.py for an example.
:param name: name for the task class
:type name: string
:param rule: function to execute or string to be compiled in a function
:type rule: string or function
:param reentrant: re-inject the output file in the process (done automatically, set to 0 to disable)
:type reentrant: int
:param color: color for the task output
:type color: string
:param ext_in: execute the task only after the files of such extensions are created
:type ext_in: list of string
:param ext_out: execute the task only before files of such extensions are processed
:type ext_out: list of string
:param before: execute instances of this task before classes of the given names
:type before: list of string
:param after: execute instances of this task after classes of the given names
:type after: list of string
:param decider: if present, function that returns a list of output file extensions (overrides ext_out for output files, but not for the build order)
:type decider: function
:param scan: scanner function for the task
:type scan: function
:param install_path: installation path for the output nodes
:type install_path: string
"""
ext_in = Utils.to_list(ext_in)
ext_out = Utils.to_list(ext_out)
if not name:
name = rule
cls = Task.task_factory(name, rule, color=color, ext_in=ext_in, ext_out=ext_out, before=before, after=after, scan=scan, shell=shell)
def x_file(self, node):
if ext_in:
_ext_in = ext_in[0]
tsk = self.create_task(name, node)
cnt = 0
ext = decider(self, node) if decider else cls.ext_out
for x in ext:
k = node.change_ext(x, ext_in=_ext_in)
tsk.outputs.append(k)
if reentrant != None:
if cnt < int(reentrant):
self.source.append(k)
else:
# reinject downstream files into the build
for y in self.mappings: # ~ nfile * nextensions :-/
if k.name.endswith(y):
self.source.append(k)
break
cnt += 1
if install_path:
self.install_task = self.add_install_files(install_to=install_path, install_from=tsk.outputs)
return tsk
for x in cls.ext_in:
task_gen.mappings[x] = x_file
return x_file
def taskgen_method(func):
"""
Decorator that registers method as a task generator method.
The function must accept a task generator as first parameter::
from waflib.TaskGen import taskgen_method
@taskgen_method
def mymethod(self):
pass
:param func: task generator method to add
:type func: function
:rtype: function
"""
setattr(task_gen, func.__name__, func)
return func
def feature(*k):
"""
Decorator that registers a task generator method that will be executed when the
object attribute ``feature`` contains the corresponding key(s)::
from waflib.TaskGen import feature
@feature('myfeature')
def myfunction(self):
print('that is my feature!')
def build(bld):
bld(features='myfeature')
:param k: feature names
:type k: list of string
"""
def deco(func):
setattr(task_gen, func.__name__, func)
for name in k:
feats[name].update([func.__name__])
return func
return deco
def before_method(*k):
"""
Decorator that registera task generator method which will be executed
before the functions of given name(s)::
from waflib.TaskGen import feature, before
@feature('myfeature')
@before_method('fun2')
def fun1(self):
print('feature 1!')
@feature('myfeature')
def fun2(self):
print('feature 2!')
def build(bld):
bld(features='myfeature')
:param k: method names
:type k: list of string
"""
def deco(func):
setattr(task_gen, func.__name__, func)
for fun_name in k:
task_gen.prec[func.__name__].add(fun_name)
return func
return deco
before = before_method
def after_method(*k):
"""
Decorator that registers a task generator method which will be executed
after the functions of given name(s)::
from waflib.TaskGen import feature, after
@feature('myfeature')
@after_method('fun2')
def fun1(self):
print('feature 1!')
@feature('myfeature')
def fun2(self):
print('feature 2!')
def build(bld):
bld(features='myfeature')
:param k: method names
:type k: list of string
"""
def deco(func):
setattr(task_gen, func.__name__, func)
for fun_name in k:
task_gen.prec[fun_name].add(func.__name__)
return func
return deco
after = after_method
def extension(*k):
"""
Decorator that registers a task generator method which will be invoked during
the processing of source files for the extension given::
from waflib import Task
class mytask(Task):
run_str = 'cp ${SRC} ${TGT}'
@extension('.moo')
def create_maa_file(self, node):
self.create_task('mytask', node, node.change_ext('.maa'))
def build(bld):
bld(source='foo.moo')
"""
def deco(func):
setattr(task_gen, func.__name__, func)
for x in k:
task_gen.mappings[x] = func
return func
return deco
@taskgen_method
def to_nodes(self, lst, path=None):
"""
Flatten the input list of string/nodes/lists into a list of nodes.
It is used by :py:func:`waflib.TaskGen.process_source` and :py:func:`waflib.TaskGen.process_rule`.
It is designed for source files, for folders, see :py:func:`waflib.Tools.ccroot.to_incnodes`:
:param lst: input list
:type lst: list of string and nodes
:param path: path from which to search the nodes (by default, :py:attr:`waflib.TaskGen.task_gen.path`)
:type path: :py:class:`waflib.Tools.Node.Node`
:rtype: list of :py:class:`waflib.Tools.Node.Node`
"""
tmp = []
path = path or self.path
find = path.find_resource
if isinstance(lst, Node.Node):
lst = [lst]
for x in Utils.to_list(lst):
if isinstance(x, str):
node = find(x)
elif hasattr(x, 'name'):
node = x
else:
tmp.extend(self.to_nodes(x))
continue
if not node:
raise Errors.WafError('source not found: %r in %r' % (x, self))
tmp.append(node)
return tmp
@feature('*')
def process_source(self):
"""
Processes each element in the attribute ``source`` by extension.
#. The *source* list is converted through :py:meth:`waflib.TaskGen.to_nodes` to a list of :py:class:`waflib.Node.Node` first.
#. File extensions are mapped to methods having the signature: ``def meth(self, node)`` by :py:meth:`waflib.TaskGen.extension`
#. The method is retrieved through :py:meth:`waflib.TaskGen.task_gen.get_hook`
#. When called, the methods may modify self.source to append more source to process
#. The mappings can map an extension or a filename (see the code below)
"""
self.source = self.to_nodes(getattr(self, 'source', []))
for node in self.source:
self.get_hook(node)(self, node)
@feature('*')
@before_method('process_source')
def process_rule(self):
"""
Processes the attribute ``rule``. When present, :py:meth:`waflib.TaskGen.process_source` is disabled::
def build(bld):
bld(rule='cp ${SRC} ${TGT}', source='wscript', target='bar.txt')
Main attributes processed:
* rule: command to execute, it can be a tuple of strings for multiple commands
* chmod: permissions for the resulting files (integer value such as Utils.O755)
* shell: set to False to execute the command directly (default is True to use a shell)
* scan: scanner function
* vars: list of variables to trigger rebuilds, such as CFLAGS
* cls_str: string to display when executing the task
* cls_keyword: label to display when executing the task
* cache_rule: by default, try to re-use similar classes, set to False to disable
* source: list of Node or string objects representing the source files required by this task
* target: list of Node or string objects representing the files that this task creates
* cwd: current working directory (Node or string)
* stdout: standard output, set to None to prevent waf from capturing the text
* stderr: standard error, set to None to prevent waf from capturing the text
* timeout: timeout for command execution (Python 3)
* always: whether to always run the command (False by default)
* deep_inputs: whether the task must depend on the input file tasks too (False by default)
"""
if not getattr(self, 'rule', None):
return
# create the task class
name = str(getattr(self, 'name', None) or self.target or getattr(self.rule, '__name__', self.rule))
# or we can put the class in a cache for performance reasons
try:
cache = self.bld.cache_rule_attr
except AttributeError:
cache = self.bld.cache_rule_attr = {}
chmod = getattr(self, 'chmod', None)
shell = getattr(self, 'shell', True)
color = getattr(self, 'color', 'BLUE')
scan = getattr(self, 'scan', None)
_vars = getattr(self, 'vars', [])
cls_str = getattr(self, 'cls_str', None)
cls_keyword = getattr(self, 'cls_keyword', None)
use_cache = getattr(self, 'cache_rule', 'True')
deep_inputs = getattr(self, 'deep_inputs', False)
scan_val = has_deps = hasattr(self, 'deps')
if scan:
scan_val = id(scan)
key = Utils.h_list((name, self.rule, chmod, shell, color, cls_str, cls_keyword, scan_val, _vars, deep_inputs))
cls = None
if use_cache:
try:
cls = cache[key]
except KeyError:
pass
if not cls:
rule = self.rule
if chmod is not None:
def chmod_fun(tsk):
for x in tsk.outputs:
os.chmod(x.abspath(), tsk.generator.chmod)
if isinstance(rule, tuple):
rule = list(rule)
rule.append(chmod_fun)
rule = tuple(rule)
else:
rule = (rule, chmod_fun)
cls = Task.task_factory(name, rule, _vars, shell=shell, color=color)
if cls_str:
setattr(cls, '__str__', self.cls_str)
if cls_keyword:
setattr(cls, 'keyword', self.cls_keyword)
if deep_inputs:
Task.deep_inputs(cls)
if scan:
cls.scan = self.scan
elif has_deps:
def scan(self):
deps = getattr(self.generator, 'deps', None)
nodes = self.generator.to_nodes(deps)
return [nodes, []]
cls.scan = scan
if use_cache:
cache[key] = cls
# now create one instance
tsk = self.create_task(name)
for x in ('after', 'before', 'ext_in', 'ext_out'):
setattr(tsk, x, getattr(self, x, []))
if hasattr(self, 'stdout'):
tsk.stdout = self.stdout
if hasattr(self, 'stderr'):
tsk.stderr = self.stderr
if getattr(self, 'timeout', None):
tsk.timeout = self.timeout
if getattr(self, 'always', None):
tsk.always_run = True
if getattr(self, 'target', None):
if isinstance(self.target, str):
self.target = self.target.split()
if not isinstance(self.target, list):
self.target = [self.target]
for x in self.target:
if isinstance(x, str):
tsk.outputs.append(self.path.find_or_declare(x))
else:
x.parent.mkdir() # if a node was given, create the required folders
tsk.outputs.append(x)
if getattr(self, 'install_path', None):
self.install_task = self.add_install_files(install_to=self.install_path,
install_from=tsk.outputs, chmod=getattr(self, 'chmod', Utils.O644))
if getattr(self, 'source', None):
tsk.inputs = self.to_nodes(self.source)
# bypass the execution of process_source by setting the source to an empty list
self.source = []
if getattr(self, 'cwd', None):
tsk.cwd = self.cwd
if isinstance(tsk.run, functools.partial):
# Python documentation says: "partial objects defined in classes
# behave like static methods and do not transform into bound
# methods during instance attribute look-up."
tsk.run = functools.partial(tsk.run, tsk)
@feature('seq')
def sequence_order(self):
"""
Adds a strict sequential constraint between the tasks generated by task generators.
It works because task generators are posted in order.
It will not post objects which belong to other folders.
Example::
bld(features='javac seq')
bld(features='jar seq')
To start a new sequence, set the attribute seq_start, for example::
obj = bld(features='seq')
obj.seq_start = True
Note that the method is executed in last position. This is more an
example than a widely-used solution.
"""
if self.meths and self.meths[-1] != 'sequence_order':
self.meths.append('sequence_order')
return
if getattr(self, 'seq_start', None):
return
# all the tasks previously declared must be run before these
if getattr(self.bld, 'prev', None):
self.bld.prev.post()
for x in self.bld.prev.tasks:
for y in self.tasks:
y.set_run_after(x)
self.bld.prev = self
re_m4 = re.compile(r'@(\w+)@', re.M)
class subst_pc(Task.Task):
"""
Creates *.pc* files from *.pc.in*. The task is executed whenever an input variable used
in the substitution changes.
"""
def force_permissions(self):
"Private for the time being, we will probably refactor this into run_str=[run1,chmod]"
if getattr(self.generator, 'chmod', None):
for x in self.outputs:
os.chmod(x.abspath(), self.generator.chmod)
def run(self):
"Substitutes variables in a .in file"
if getattr(self.generator, 'is_copy', None):
for i, x in enumerate(self.outputs):
x.write(self.inputs[i].read('rb'), 'wb')
stat = os.stat(self.inputs[i].abspath()) # Preserve mtime of the copy
os.utime(self.outputs[i].abspath(), (stat.st_atime, stat.st_mtime))
self.force_permissions()
return None
if getattr(self.generator, 'fun', None):
ret = self.generator.fun(self)
if not ret:
self.force_permissions()
return ret
code = self.inputs[0].read(encoding=getattr(self.generator, 'encoding', 'latin-1'))
if getattr(self.generator, 'subst_fun', None):
code = self.generator.subst_fun(self, code)
if code is not None:
self.outputs[0].write(code, encoding=getattr(self.generator, 'encoding', 'latin-1'))
self.force_permissions()
return None
# replace all % by %% to prevent errors by % signs
code = code.replace('%', '%%')
# extract the vars foo into lst and replace @foo@ by %(foo)s
lst = []
def repl(match):
g = match.group
if g(1):
lst.append(g(1))
return "%%(%s)s" % g(1)
return ''
code = getattr(self.generator, 're_m4', re_m4).sub(repl, code)
try:
d = self.generator.dct
except AttributeError:
d = {}
for x in lst:
tmp = getattr(self.generator, x, '') or self.env[x] or self.env[x.upper()]
try:
tmp = ''.join(tmp)
except TypeError:
tmp = str(tmp)
d[x] = tmp
code = code % d
self.outputs[0].write(code, encoding=getattr(self.generator, 'encoding', 'latin-1'))
self.generator.bld.raw_deps[self.uid()] = lst
# make sure the signature is updated
try:
delattr(self, 'cache_sig')
except AttributeError:
pass
self.force_permissions()
def sig_vars(self):
"""
Compute a hash (signature) of the variables used in the substitution
"""
bld = self.generator.bld
env = self.env
upd = self.m.update
if getattr(self.generator, 'fun', None):
upd(Utils.h_fun(self.generator.fun).encode())
if getattr(self.generator, 'subst_fun', None):
upd(Utils.h_fun(self.generator.subst_fun).encode())
# raw_deps: persistent custom values returned by the scanner
vars = self.generator.bld.raw_deps.get(self.uid(), [])
# hash both env vars and task generator attributes
act_sig = bld.hash_env_vars(env, vars)
upd(act_sig)
lst = [getattr(self.generator, x, '') for x in vars]
upd(Utils.h_list(lst))
return self.m.digest()
@extension('.pc.in')
def add_pcfile(self, node):
"""
Processes *.pc.in* files to *.pc*. Installs the results to ``${PREFIX}/lib/pkgconfig/`` by default
def build(bld):
bld(source='foo.pc.in', install_path='${LIBDIR}/pkgconfig/')
"""
tsk = self.create_task('subst_pc', node, node.change_ext('.pc', '.pc.in'))
self.install_task = self.add_install_files(
install_to=getattr(self, 'install_path', '${LIBDIR}/pkgconfig/'), install_from=tsk.outputs)
class subst(subst_pc):
pass
@feature('subst')
@before_method('process_source', 'process_rule')
def process_subst(self):
"""
Defines a transformation that substitutes the contents of *source* files to *target* files::
def build(bld):
bld(
features='subst',
source='foo.c.in',
target='foo.c',
install_path='${LIBDIR}/pkgconfig',
VAR = 'val'
)
The input files are supposed to contain macros of the form *@VAR@*, where *VAR* is an argument
of the task generator object.
This method overrides the processing by :py:meth:`waflib.TaskGen.process_source`.
"""
src = Utils.to_list(getattr(self, 'source', []))
if isinstance(src, Node.Node):
src = [src]
tgt = Utils.to_list(getattr(self, 'target', []))
if isinstance(tgt, Node.Node):
tgt = [tgt]
if len(src) != len(tgt):
raise Errors.WafError('invalid number of source/target for %r' % self)
for x, y in zip(src, tgt):
if not x or not y:
raise Errors.WafError('null source or target for %r' % self)
a, b = None, None
if isinstance(x, str) and isinstance(y, str) and x == y:
a = self.path.find_node(x)
b = self.path.get_bld().make_node(y)
if not os.path.isfile(b.abspath()):
b.parent.mkdir()
else:
if isinstance(x, str):
a = self.path.find_resource(x)
elif isinstance(x, Node.Node):
a = x
if isinstance(y, str):
b = self.path.find_or_declare(y)
elif isinstance(y, Node.Node):
b = y
if not a:
raise Errors.WafError('could not find %r for %r' % (x, self))
tsk = self.create_task('subst', a, b)
for k in ('after', 'before', 'ext_in', 'ext_out'):
val = getattr(self, k, None)
if val:
setattr(tsk, k, val)
# paranoid safety measure for the general case foo.in->foo.h with ambiguous dependencies
for xt in HEADER_EXTS:
if b.name.endswith(xt):
tsk.ext_out = tsk.ext_out + ['.h']
break
inst_to = getattr(self, 'install_path', None)
if inst_to:
self.install_task = self.add_install_files(install_to=inst_to,
install_from=b, chmod=getattr(self, 'chmod', Utils.O644))
self.source = []
| 26,525 | Python | .py | 765 | 31.424837 | 149 | 0.69893 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,576 | Options.py | projecthamster_hamster/waflib/Options.py | #!/usr/bin/env python
# encoding: utf-8
# Scott Newton, 2005 (scottn)
# Thomas Nagy, 2006-2018 (ita)
"""
Support for waf command-line options
Provides default and command-line options, as well the command
that reads the ``options`` wscript function.
"""
import os, tempfile, optparse, sys, re
from waflib import Logs, Utils, Context, Errors
options = optparse.Values()
"""
A global dictionary representing user-provided command-line options::
$ waf --foo=bar
"""
commands = []
"""
List of commands to execute extracted from the command-line. This list
is consumed during the execution by :py:func:`waflib.Scripting.run_commands`.
"""
envvars = []
"""
List of environment variable declarations placed after the Waf executable name.
These are detected by searching for "=" in the remaining arguments.
You probably do not want to use this.
"""
lockfile = os.environ.get('WAFLOCK', '.lock-waf_%s_build' % sys.platform)
"""
Name of the lock file that marks a project as configured
"""
class opt_parser(optparse.OptionParser):
"""
Command-line options parser.
"""
def __init__(self, ctx, allow_unknown=False):
optparse.OptionParser.__init__(self, conflict_handler='resolve', add_help_option=False,
version='%s %s (%s)' % (Context.WAFNAME, Context.WAFVERSION, Context.WAFREVISION))
self.formatter.width = Logs.get_term_cols()
self.ctx = ctx
self.allow_unknown = allow_unknown
def _process_args(self, largs, rargs, values):
"""
Custom _process_args to allow unknown options according to the allow_unknown status
"""
while rargs:
try:
optparse.OptionParser._process_args(self,largs,rargs,values)
except (optparse.BadOptionError, optparse.AmbiguousOptionError) as e:
if self.allow_unknown:
largs.append(e.opt_str)
else:
self.error(str(e))
def _process_long_opt(self, rargs, values):
# --custom-option=-ftxyz is interpreted as -f -t... see #2280
if self.allow_unknown:
back = [] + rargs
try:
optparse.OptionParser._process_long_opt(self, rargs, values)
except optparse.BadOptionError:
while rargs:
rargs.pop()
rargs.extend(back)
rargs.pop(0)
raise
else:
optparse.OptionParser._process_long_opt(self, rargs, values)
def print_usage(self, file=None):
return self.print_help(file)
def get_usage(self):
"""
Builds the message to print on ``waf --help``
:rtype: string
"""
cmds_str = {}
for cls in Context.classes:
if not cls.cmd or cls.cmd == 'options' or cls.cmd.startswith( '_' ):
continue
s = cls.__doc__ or ''
cmds_str[cls.cmd] = s
if Context.g_module:
for (k, v) in Context.g_module.__dict__.items():
if k in ('options', 'init', 'shutdown'):
continue
if type(v) is type(Context.create_context):
if v.__doc__ and not k.startswith('_'):
cmds_str[k] = v.__doc__
just = 0
for k in cmds_str:
just = max(just, len(k))
lst = [' %s: %s' % (k.ljust(just), v) for (k, v) in cmds_str.items()]
lst.sort()
ret = '\n'.join(lst)
return '''%s [commands] [options]
Main commands (example: ./%s build -j4)
%s
''' % (Context.WAFNAME, Context.WAFNAME, ret)
class OptionsContext(Context.Context):
"""
Collects custom options from wscript files and parses the command line.
Sets the global :py:const:`waflib.Options.commands` and :py:const:`waflib.Options.options` values.
"""
cmd = 'options'
fun = 'options'
def __init__(self, **kw):
super(OptionsContext, self).__init__(**kw)
self.parser = opt_parser(self)
"""Instance of :py:class:`waflib.Options.opt_parser`"""
self.option_groups = {}
jobs = self.jobs()
p = self.add_option
color = os.environ.get('NOCOLOR', '') and 'no' or 'auto'
if os.environ.get('CLICOLOR', '') == '0':
color = 'no'
elif os.environ.get('CLICOLOR_FORCE', '') == '1':
color = 'yes'
p('-c', '--color', dest='colors', default=color, action='store', help='whether to use colors (yes/no/auto) [default: auto]', choices=('yes', 'no', 'auto'))
p('-j', '--jobs', dest='jobs', default=jobs, type='int', help='amount of parallel jobs (%r)' % jobs)
p('-k', '--keep', dest='keep', default=0, action='count', help='continue despite errors (-kk to try harder)')
p('-v', '--verbose', dest='verbose', default=0, action='count', help='verbosity level -v -vv or -vvv [default: 0]')
p('--zones', dest='zones', default='', action='store', help='debugging zones (task_gen, deps, tasks, etc)')
p('--profile', dest='profile', default=0, action='store_true', help=optparse.SUPPRESS_HELP)
p('--pdb', dest='pdb', default=0, action='store_true', help=optparse.SUPPRESS_HELP)
p('-h', '--help', dest='whelp', default=0, action='store_true', help="show this help message and exit")
gr = self.add_option_group('Configuration options')
self.option_groups['configure options'] = gr
gr.add_option('-o', '--out', action='store', default='', help='build dir for the project', dest='out')
gr.add_option('-t', '--top', action='store', default='', help='src dir for the project', dest='top')
gr.add_option('--no-lock-in-run', action='store_true', default=os.environ.get('NO_LOCK_IN_RUN', ''), help=optparse.SUPPRESS_HELP, dest='no_lock_in_run')
gr.add_option('--no-lock-in-out', action='store_true', default=os.environ.get('NO_LOCK_IN_OUT', ''), help=optparse.SUPPRESS_HELP, dest='no_lock_in_out')
gr.add_option('--no-lock-in-top', action='store_true', default=os.environ.get('NO_LOCK_IN_TOP', ''), help=optparse.SUPPRESS_HELP, dest='no_lock_in_top')
default_prefix = getattr(Context.g_module, 'default_prefix', os.environ.get('PREFIX'))
if not default_prefix:
if Utils.unversioned_sys_platform() == 'win32':
d = tempfile.gettempdir()
default_prefix = d[0].upper() + d[1:]
# win32 preserves the case, but gettempdir does not
else:
default_prefix = '/usr/local/'
gr.add_option('--prefix', dest='prefix', default=default_prefix, help='installation prefix [default: %r]' % default_prefix)
gr.add_option('--bindir', dest='bindir', help='bindir')
gr.add_option('--libdir', dest='libdir', help='libdir')
gr = self.add_option_group('Build and installation options')
self.option_groups['build and install options'] = gr
gr.add_option('-p', '--progress', dest='progress_bar', default=0, action='count', help= '-p: progress bar; -pp: ide output')
gr.add_option('--targets', dest='targets', default='', action='store', help='task generators, e.g. "target1,target2"')
gr = self.add_option_group('Step options')
self.option_groups['step options'] = gr
gr.add_option('--files', dest='files', default='', action='store', help='files to process, by regexp, e.g. "*/main.c,*/test/main.o"')
default_destdir = os.environ.get('DESTDIR', '')
gr = self.add_option_group('Installation and uninstallation options')
self.option_groups['install/uninstall options'] = gr
gr.add_option('--destdir', help='installation root [default: %r]' % default_destdir, default=default_destdir, dest='destdir')
gr.add_option('-f', '--force', dest='force', default=False, action='store_true', help='force file installation')
gr.add_option('--distcheck-args', metavar='ARGS', help='arguments to pass to distcheck', default=None, action='store')
def jobs(self):
"""
Finds the optimal amount of cpu cores to use for parallel jobs.
At runtime the options can be obtained from :py:const:`waflib.Options.options` ::
from waflib.Options import options
njobs = options.jobs
:return: the amount of cpu cores
:rtype: int
"""
count = int(os.environ.get('JOBS', 0))
if count < 1:
if 'NUMBER_OF_PROCESSORS' in os.environ:
# on Windows, use the NUMBER_OF_PROCESSORS environment variable
count = int(os.environ.get('NUMBER_OF_PROCESSORS', 1))
else:
# on everything else, first try the POSIX sysconf values
if hasattr(os, 'sysconf_names'):
if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
count = int(os.sysconf('SC_NPROCESSORS_ONLN'))
elif 'SC_NPROCESSORS_CONF' in os.sysconf_names:
count = int(os.sysconf('SC_NPROCESSORS_CONF'))
if not count and os.name not in ('nt', 'java'):
try:
tmp = self.cmd_and_log(['sysctl', '-n', 'hw.ncpu'], quiet=0)
except Errors.WafError:
pass
else:
if re.match('^[0-9]+$', tmp):
count = int(tmp)
if count < 1:
count = 1
elif count > 1024:
count = 1024
return count
def add_option(self, *k, **kw):
"""
Wraps ``optparse.add_option``::
def options(ctx):
ctx.add_option('-u', '--use', dest='use', default=False,
action='store_true', help='a boolean option')
:rtype: optparse option object
"""
return self.parser.add_option(*k, **kw)
def add_option_group(self, *k, **kw):
"""
Wraps ``optparse.add_option_group``::
def options(ctx):
gr = ctx.add_option_group('some options')
gr.add_option('-u', '--use', dest='use', default=False, action='store_true')
:rtype: optparse option group object
"""
try:
gr = self.option_groups[k[0]]
except KeyError:
gr = self.parser.add_option_group(*k, **kw)
self.option_groups[k[0]] = gr
return gr
def get_option_group(self, opt_str):
"""
Wraps ``optparse.get_option_group``::
def options(ctx):
gr = ctx.get_option_group('configure options')
gr.add_option('-o', '--out', action='store', default='',
help='build dir for the project', dest='out')
:rtype: optparse option group object
"""
try:
return self.option_groups[opt_str]
except KeyError:
for group in self.parser.option_groups:
if group.title == opt_str:
return group
return None
def sanitize_path(self, path, cwd=None):
if not cwd:
cwd = Context.launch_dir
p = os.path.expanduser(path)
p = os.path.join(cwd, p)
p = os.path.normpath(p)
p = os.path.abspath(p)
return p
def parse_cmd_args(self, _args=None, cwd=None, allow_unknown=False):
"""
Just parse the arguments
"""
self.parser.allow_unknown = allow_unknown
(options, leftover_args) = self.parser.parse_args(args=_args)
envvars = []
commands = []
for arg in leftover_args:
if '=' in arg:
envvars.append(arg)
elif arg != 'options':
commands.append(arg)
if options.jobs < 1:
options.jobs = 1
for name in 'top out destdir prefix bindir libdir'.split():
# those paths are usually expanded from Context.launch_dir
if getattr(options, name, None):
path = self.sanitize_path(getattr(options, name), cwd)
setattr(options, name, path)
return options, commands, envvars
def init_module_vars(self, arg_options, arg_commands, arg_envvars):
options.__dict__.clear()
del commands[:]
del envvars[:]
options.__dict__.update(arg_options.__dict__)
commands.extend(arg_commands)
envvars.extend(arg_envvars)
for var in envvars:
(name, value) = var.split('=', 1)
os.environ[name.strip()] = value
def init_logs(self, options, commands, envvars):
Logs.verbose = options.verbose
if options.verbose >= 1:
self.load('errcheck')
colors = {'yes' : 2, 'auto' : 1, 'no' : 0}[options.colors]
Logs.enable_colors(colors)
if options.zones:
Logs.zones = options.zones.split(',')
if not Logs.verbose:
Logs.verbose = 1
elif Logs.verbose > 0:
Logs.zones = ['runner']
if Logs.verbose > 2:
Logs.zones = ['*']
def parse_args(self, _args=None):
"""
Parses arguments from a list which is not necessarily the command-line.
Initializes the module variables options, commands and envvars
If help is requested, prints it and exit the application
:param _args: arguments
:type _args: list of strings
"""
options, commands, envvars = self.parse_cmd_args()
self.init_logs(options, commands, envvars)
self.init_module_vars(options, commands, envvars)
def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
super(OptionsContext, self).execute()
self.parse_args()
Utils.alloc_process_pool(options.jobs)
| 11,958 | Python | .py | 299 | 36.535117 | 161 | 0.67592 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,577 | Runner.py | projecthamster_hamster/waflib/Runner.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Runner.py: Task scheduling and execution
"""
import heapq, traceback
try:
from queue import Queue, PriorityQueue
except ImportError:
from Queue import Queue
try:
from Queue import PriorityQueue
except ImportError:
class PriorityQueue(Queue):
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _put(self, item):
heapq.heappush(self.queue, item)
def _get(self):
return heapq.heappop(self.queue)
from waflib import Utils, Task, Errors, Logs
GAP = 5
"""
Wait for at least ``GAP * njobs`` before trying to enqueue more tasks to run
"""
class PriorityTasks(object):
def __init__(self):
self.lst = []
def __len__(self):
return len(self.lst)
def __iter__(self):
return iter(self.lst)
def __str__(self):
return 'PriorityTasks: [%s]' % '\n '.join(str(x) for x in self.lst)
def clear(self):
self.lst = []
def append(self, task):
heapq.heappush(self.lst, task)
def appendleft(self, task):
"Deprecated, do not use"
heapq.heappush(self.lst, task)
def pop(self):
return heapq.heappop(self.lst)
def extend(self, lst):
if self.lst:
for x in lst:
self.append(x)
else:
if isinstance(lst, list):
self.lst = lst
heapq.heapify(lst)
else:
self.lst = lst.lst
class Consumer(Utils.threading.Thread):
"""
Daemon thread object that executes a task. It shares a semaphore with
the coordinator :py:class:`waflib.Runner.Spawner`. There is one
instance per task to consume.
"""
def __init__(self, spawner, task):
Utils.threading.Thread.__init__(self)
self.task = task
"""Task to execute"""
self.spawner = spawner
"""Coordinator object"""
self.daemon = True
self.start()
def run(self):
"""
Processes a single task
"""
try:
if not self.spawner.master.stop:
self.spawner.master.process_task(self.task)
finally:
self.spawner.sem.release()
self.spawner.master.out.put(self.task)
self.task = None
self.spawner = None
class Spawner(Utils.threading.Thread):
"""
Daemon thread that consumes tasks from :py:class:`waflib.Runner.Parallel` producer and
spawns a consuming thread :py:class:`waflib.Runner.Consumer` for each
:py:class:`waflib.Task.Task` instance.
"""
def __init__(self, master):
Utils.threading.Thread.__init__(self)
self.master = master
""":py:class:`waflib.Runner.Parallel` producer instance"""
self.sem = Utils.threading.Semaphore(master.numjobs)
"""Bounded semaphore that prevents spawning more than *n* concurrent consumers"""
self.daemon = True
self.start()
def run(self):
"""
Spawns new consumers to execute tasks by delegating to :py:meth:`waflib.Runner.Spawner.loop`
"""
try:
self.loop()
except Exception:
# Python 2 prints unnecessary messages when shutting down
# we also want to stop the thread properly
pass
def loop(self):
"""
Consumes task objects from the producer; ends when the producer has no more
task to provide.
"""
master = self.master
while 1:
task = master.ready.get()
self.sem.acquire()
if not master.stop:
task.log_display(task.generator.bld)
Consumer(self, task)
class Parallel(object):
"""
Schedule the tasks obtained from the build context for execution.
"""
def __init__(self, bld, j=2):
"""
The initialization requires a build context reference
for computing the total number of jobs.
"""
self.numjobs = j
"""
Amount of parallel consumers to use
"""
self.bld = bld
"""
Instance of :py:class:`waflib.Build.BuildContext`
"""
self.outstanding = PriorityTasks()
"""Heap of :py:class:`waflib.Task.Task` that may be ready to be executed"""
self.postponed = PriorityTasks()
"""Heap of :py:class:`waflib.Task.Task` which are not ready to run for non-DAG reasons"""
self.incomplete = set()
"""List of :py:class:`waflib.Task.Task` waiting for dependent tasks to complete (DAG)"""
self.ready = PriorityQueue(0)
"""List of :py:class:`waflib.Task.Task` ready to be executed by consumers"""
self.out = Queue(0)
"""List of :py:class:`waflib.Task.Task` returned by the task consumers"""
self.count = 0
"""Amount of tasks that may be processed by :py:class:`waflib.Runner.TaskConsumer`"""
self.processed = 0
"""Amount of tasks processed"""
self.stop = False
"""Error flag to stop the build"""
self.error = []
"""Tasks that could not be executed"""
self.biter = None
"""Task iterator which must give groups of parallelizable tasks when calling ``next()``"""
self.dirty = False
"""
Flag that indicates that the build cache must be saved when a task was executed
(calls :py:meth:`waflib.Build.BuildContext.store`)"""
self.revdeps = Utils.defaultdict(set)
"""
The reverse dependency graph of dependencies obtained from Task.run_after
"""
self.spawner = None
"""
Coordinating daemon thread that spawns thread consumers
"""
if self.numjobs > 1:
self.spawner = Spawner(self)
def get_next_task(self):
"""
Obtains the next Task instance to run
:rtype: :py:class:`waflib.Task.Task`
"""
if not self.outstanding:
return None
return self.outstanding.pop()
def postpone(self, tsk):
"""
Adds the task to the list :py:attr:`waflib.Runner.Parallel.postponed`.
The order is scrambled so as to consume as many tasks in parallel as possible.
:param tsk: task instance
:type tsk: :py:class:`waflib.Task.Task`
"""
self.postponed.append(tsk)
def refill_task_list(self):
"""
Pulls a next group of tasks to execute in :py:attr:`waflib.Runner.Parallel.outstanding`.
Ensures that all tasks in the current build group are complete before processing the next one.
"""
while self.count > self.numjobs * GAP:
self.get_out()
while not self.outstanding:
if self.count:
self.get_out()
if self.outstanding:
break
elif self.postponed:
try:
cond = self.deadlock == self.processed
except AttributeError:
pass
else:
if cond:
# The most common reason is conflicting build order declaration
# for example: "X run_after Y" and "Y run_after X"
# Another can be changing "run_after" dependencies while the build is running
# for example: updating "tsk.run_after" in the "runnable_status" method
lst = []
for tsk in self.postponed:
deps = [id(x) for x in tsk.run_after if not x.hasrun]
lst.append('%s\t-> %r' % (repr(tsk), deps))
if not deps:
lst.append('\n task %r dependencies are done, check its *runnable_status*?' % id(tsk))
raise Errors.WafError('Deadlock detected: check the task build order%s' % ''.join(lst))
self.deadlock = self.processed
if self.postponed:
self.outstanding.extend(self.postponed)
self.postponed.clear()
elif not self.count:
if self.incomplete:
for x in self.incomplete:
for k in x.run_after:
if not k.hasrun:
break
else:
# dependency added after the build started without updating revdeps
self.incomplete.remove(x)
self.outstanding.append(x)
break
else:
if self.stop or self.error:
break
raise Errors.WafError('Broken revdeps detected on %r' % self.incomplete)
else:
tasks = next(self.biter)
ready, waiting = self.prio_and_split(tasks)
self.outstanding.extend(ready)
self.incomplete.update(waiting)
self.total = self.bld.total()
break
def add_more_tasks(self, tsk):
"""
If a task provides :py:attr:`waflib.Task.Task.more_tasks`, then the tasks contained
in that list are added to the current build and will be processed before the next build group.
The priorities for dependent tasks are not re-calculated globally
:param tsk: task instance
:type tsk: :py:attr:`waflib.Task.Task`
"""
if getattr(tsk, 'more_tasks', None):
more = set(tsk.more_tasks)
groups_done = set()
def iteri(a, b):
for x in a:
yield x
for x in b:
yield x
# Update the dependency tree
# this assumes that task.run_after values were updated
for x in iteri(self.outstanding, self.incomplete):
for k in x.run_after:
if isinstance(k, Task.TaskGroup):
if k not in groups_done:
groups_done.add(k)
for j in k.prev & more:
self.revdeps[j].add(k)
elif k in more:
self.revdeps[k].add(x)
ready, waiting = self.prio_and_split(tsk.more_tasks)
self.outstanding.extend(ready)
self.incomplete.update(waiting)
self.total += len(tsk.more_tasks)
def mark_finished(self, tsk):
def try_unfreeze(x):
# DAG ancestors are likely to be in the incomplete set
# This assumes that the run_after contents have not changed
# after the build starts, else a deadlock may occur
if x in self.incomplete:
# TODO remove dependencies to free some memory?
# x.run_after.remove(tsk)
for k in x.run_after:
if not k.hasrun:
break
else:
self.incomplete.remove(x)
self.outstanding.append(x)
if tsk in self.revdeps:
for x in self.revdeps[tsk]:
if isinstance(x, Task.TaskGroup):
x.prev.remove(tsk)
if not x.prev:
for k in x.next:
# TODO necessary optimization?
k.run_after.remove(x)
try_unfreeze(k)
# TODO necessary optimization?
x.next = []
else:
try_unfreeze(x)
del self.revdeps[tsk]
if hasattr(tsk, 'semaphore'):
sem = tsk.semaphore
try:
sem.release(tsk)
except KeyError:
# TODO
pass
else:
while sem.waiting and not sem.is_locked():
# take a frozen task, make it ready to run
x = sem.waiting.pop()
self._add_task(x)
def get_out(self):
"""
Waits for a Task that task consumers add to :py:attr:`waflib.Runner.Parallel.out` after execution.
Adds more Tasks if necessary through :py:attr:`waflib.Runner.Parallel.add_more_tasks`.
:rtype: :py:attr:`waflib.Task.Task`
"""
tsk = self.out.get()
if not self.stop:
self.add_more_tasks(tsk)
self.mark_finished(tsk)
self.count -= 1
self.dirty = True
return tsk
def add_task(self, tsk):
"""
Enqueue a Task to :py:attr:`waflib.Runner.Parallel.ready` so that consumers can run them.
:param tsk: task instance
:type tsk: :py:attr:`waflib.Task.Task`
"""
# TODO change in waf 2.1
self.ready.put(tsk)
def _add_task(self, tsk):
if hasattr(tsk, 'semaphore'):
sem = tsk.semaphore
try:
sem.acquire(tsk)
except IndexError:
sem.waiting.add(tsk)
return
self.count += 1
self.processed += 1
if self.numjobs == 1:
tsk.log_display(tsk.generator.bld)
try:
self.process_task(tsk)
finally:
self.out.put(tsk)
else:
self.add_task(tsk)
def process_task(self, tsk):
"""
Processes a task and attempts to stop the build in case of errors
"""
tsk.process()
if tsk.hasrun != Task.SUCCESS:
self.error_handler(tsk)
def skip(self, tsk):
"""
Mark a task as skipped/up-to-date
"""
tsk.hasrun = Task.SKIPPED
self.mark_finished(tsk)
def cancel(self, tsk):
"""
Mark a task as failed because of unsatisfiable dependencies
"""
tsk.hasrun = Task.CANCELED
self.mark_finished(tsk)
def error_handler(self, tsk):
"""
Called when a task cannot be executed. The flag :py:attr:`waflib.Runner.Parallel.stop` is set,
unless the build is executed with::
$ waf build -k
:param tsk: task instance
:type tsk: :py:attr:`waflib.Task.Task`
"""
if not self.bld.keep:
self.stop = True
self.error.append(tsk)
def task_status(self, tsk):
"""
Obtains the task status to decide whether to run it immediately or not.
:return: the exit status, for example :py:attr:`waflib.Task.ASK_LATER`
:rtype: integer
"""
try:
return tsk.runnable_status()
except Exception:
self.processed += 1
tsk.err_msg = traceback.format_exc()
if not self.stop and self.bld.keep:
self.skip(tsk)
if self.bld.keep == 1:
# if -k stop on the first exception, if -kk try to go as far as possible
if Logs.verbose > 1 or not self.error:
self.error.append(tsk)
self.stop = True
else:
if Logs.verbose > 1:
self.error.append(tsk)
return Task.EXCEPTION
tsk.hasrun = Task.EXCEPTION
self.error_handler(tsk)
return Task.EXCEPTION
def start(self):
"""
Obtains Task instances from the BuildContext instance and adds the ones that need to be executed to
:py:class:`waflib.Runner.Parallel.ready` so that the :py:class:`waflib.Runner.Spawner` consumer thread
has them executed. Obtains the executed Tasks back from :py:class:`waflib.Runner.Parallel.out`
and marks the build as failed by setting the ``stop`` flag.
If only one job is used, then executes the tasks one by one, without consumers.
"""
self.total = self.bld.total()
while not self.stop:
self.refill_task_list()
# consider the next task
tsk = self.get_next_task()
if not tsk:
if self.count:
# tasks may add new ones after they are run
continue
else:
# no tasks to run, no tasks running, time to exit
break
if tsk.hasrun:
# if the task is marked as "run", just skip it
self.processed += 1
continue
if self.stop: # stop immediately after a failure is detected
break
st = self.task_status(tsk)
if st == Task.RUN_ME:
self._add_task(tsk)
elif st == Task.ASK_LATER:
self.postpone(tsk)
elif st == Task.SKIP_ME:
self.processed += 1
self.skip(tsk)
self.add_more_tasks(tsk)
elif st == Task.CANCEL_ME:
# A dependency problem has occurred, and the
# build is most likely run with `waf -k`
if Logs.verbose > 1:
self.error.append(tsk)
self.processed += 1
self.cancel(tsk)
# self.count represents the tasks that have been made available to the consumer threads
# collect all the tasks after an error else the message may be incomplete
while self.error and self.count:
self.get_out()
self.ready.put(None)
if not self.stop:
assert not self.count
assert not self.postponed
assert not self.incomplete
def prio_and_split(self, tasks):
"""
Label input tasks with priority values, and return a pair containing
the tasks that are ready to run and the tasks that are necessarily
waiting for other tasks to complete.
The priority system is really meant as an optional layer for optimization:
dependency cycles are found quickly, and builds should be more efficient.
A high priority number means that a task is processed first.
This method can be overridden to disable the priority system::
def prio_and_split(self, tasks):
return tasks, []
:return: A pair of task lists
:rtype: tuple
"""
# to disable:
#return tasks, []
for x in tasks:
x.visited = 0
reverse = self.revdeps
groups_done = set()
for x in tasks:
for k in x.run_after:
if isinstance(k, Task.TaskGroup):
if k not in groups_done:
groups_done.add(k)
for j in k.prev:
reverse[j].add(k)
else:
reverse[k].add(x)
# the priority number is not the tree depth
def visit(n):
if isinstance(n, Task.TaskGroup):
return sum(visit(k) for k in n.next)
if n.visited == 0:
n.visited = 1
if n in reverse:
rev = reverse[n]
n.prio_order = n.tree_weight + len(rev) + sum(visit(k) for k in rev)
else:
n.prio_order = n.tree_weight
n.visited = 2
elif n.visited == 1:
raise Errors.WafError('Dependency cycle found!')
return n.prio_order
for x in tasks:
if x.visited != 0:
# must visit all to detect cycles
continue
try:
visit(x)
except Errors.WafError:
self.debug_cycles(tasks, reverse)
ready = []
waiting = []
for x in tasks:
for k in x.run_after:
if not k.hasrun:
waiting.append(x)
break
else:
ready.append(x)
return (ready, waiting)
def debug_cycles(self, tasks, reverse):
tmp = {}
for x in tasks:
tmp[x] = 0
def visit(n, acc):
if isinstance(n, Task.TaskGroup):
for k in n.next:
visit(k, acc)
return
if tmp[n] == 0:
tmp[n] = 1
for k in reverse.get(n, []):
visit(k, [n] + acc)
tmp[n] = 2
elif tmp[n] == 1:
lst = []
for tsk in acc:
lst.append(repr(tsk))
if tsk is n:
# exclude prior nodes, we want the minimum cycle
break
raise Errors.WafError('Task dependency cycle in "run_after" constraints: %s' % ''.join(lst))
for x in tasks:
visit(x, [])
| 16,394 | Python | .py | 542 | 26.188192 | 104 | 0.687928 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,578 | Context.py | projecthamster_hamster/waflib/Context.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010-2018 (ita)
"""
Classes and functions enabling the command system
"""
import os, re, sys
from waflib import Utils, Errors, Logs
import waflib.Node
if sys.hexversion > 0x3040000:
import types
class imp(object):
new_module = lambda x: types.ModuleType(x)
else:
import imp
# the following 3 constants are updated on each new release (do not touch)
HEXVERSION=0x2001a00
"""Constant updated on new releases"""
WAFVERSION="2.0.26"
"""Constant updated on new releases"""
WAFREVISION="0fb985ce1932c6f3e7533f435e4ee209d673776e"
"""Git revision when the waf version is updated"""
WAFNAME="waf"
"""Application name displayed on --help"""
ABI = 20
"""Version of the build data cache file format (used in :py:const:`waflib.Context.DBFILE`)"""
DBFILE = '.wafpickle-%s-%d-%d' % (sys.platform, sys.hexversion, ABI)
"""Name of the pickle file for storing the build data"""
APPNAME = 'APPNAME'
"""Default application name (used by ``waf dist``)"""
VERSION = 'VERSION'
"""Default application version (used by ``waf dist``)"""
TOP = 'top'
"""The variable name for the top-level directory in wscript files"""
OUT = 'out'
"""The variable name for the output directory in wscript files"""
WSCRIPT_FILE = 'wscript'
"""Name of the waf script files"""
launch_dir = ''
"""Directory from which waf has been called"""
run_dir = ''
"""Location of the wscript file to use as the entry point"""
top_dir = ''
"""Location of the project directory (top), if the project was configured"""
out_dir = ''
"""Location of the build directory (out), if the project was configured"""
waf_dir = ''
"""Directory containing the waf modules"""
default_encoding = Utils.console_encoding()
"""Encoding to use when reading outputs from other processes"""
g_module = None
"""
Module representing the top-level wscript file (see :py:const:`waflib.Context.run_dir`)
"""
STDOUT = 1
STDERR = -1
BOTH = 0
classes = []
"""
List of :py:class:`waflib.Context.Context` subclasses that can be used as waf commands. The classes
are added automatically by a metaclass.
"""
def create_context(cmd_name, *k, **kw):
"""
Returns a new :py:class:`waflib.Context.Context` instance corresponding to the given command.
Used in particular by :py:func:`waflib.Scripting.run_command`
:param cmd_name: command name
:type cmd_name: string
:param k: arguments to give to the context class initializer
:type k: list
:param k: keyword arguments to give to the context class initializer
:type k: dict
:return: Context object
:rtype: :py:class:`waflib.Context.Context`
"""
for x in classes:
if x.cmd == cmd_name:
return x(*k, **kw)
ctx = Context(*k, **kw)
ctx.fun = cmd_name
return ctx
class store_context(type):
"""
Metaclass that registers command classes into the list :py:const:`waflib.Context.classes`
Context classes must provide an attribute 'cmd' representing the command name, and a function
attribute 'fun' representing the function name that the command uses.
"""
def __init__(cls, name, bases, dct):
super(store_context, cls).__init__(name, bases, dct)
name = cls.__name__
if name in ('ctx', 'Context'):
return
try:
cls.cmd
except AttributeError:
raise Errors.WafError('Missing command for the context class %r (cmd)' % name)
if not getattr(cls, 'fun', None):
cls.fun = cls.cmd
classes.insert(0, cls)
ctx = store_context('ctx', (object,), {})
"""Base class for all :py:class:`waflib.Context.Context` classes"""
class Context(ctx):
"""
Default context for waf commands, and base class for new command contexts.
Context objects are passed to top-level functions::
def foo(ctx):
print(ctx.__class__.__name__) # waflib.Context.Context
Subclasses must define the class attributes 'cmd' and 'fun':
:param cmd: command to execute as in ``waf cmd``
:type cmd: string
:param fun: function name to execute when the command is called
:type fun: string
.. inheritance-diagram:: waflib.Context.Context waflib.Build.BuildContext waflib.Build.InstallContext waflib.Build.UninstallContext waflib.Build.StepContext waflib.Build.ListContext waflib.Configure.ConfigurationContext waflib.Scripting.Dist waflib.Scripting.DistCheck waflib.Build.CleanContext
:top-classes: waflib.Context.Context
"""
errors = Errors
"""
Shortcut to :py:mod:`waflib.Errors` provided for convenience
"""
tools = {}
"""
A module cache for wscript files; see :py:meth:`Context.Context.load`
"""
def __init__(self, **kw):
try:
rd = kw['run_dir']
except KeyError:
rd = run_dir
# binds the context to the nodes in use to avoid a context singleton
self.node_class = type('Nod3', (waflib.Node.Node,), {})
self.node_class.__module__ = 'waflib.Node'
self.node_class.ctx = self
self.root = self.node_class('', None)
self.cur_script = None
self.path = self.root.find_dir(rd)
self.stack_path = []
self.exec_dict = {'ctx':self, 'conf':self, 'bld':self, 'opt':self}
self.logger = None
def finalize(self):
"""
Called to free resources such as logger files
"""
try:
logger = self.logger
except AttributeError:
pass
else:
Logs.free_logger(logger)
delattr(self, 'logger')
def load(self, tool_list, *k, **kw):
"""
Loads a Waf tool as a module, and try calling the function named :py:const:`waflib.Context.Context.fun`
from it. A ``tooldir`` argument may be provided as a list of module paths.
:param tool_list: list of Waf tool names to load
:type tool_list: list of string or space-separated string
"""
tools = Utils.to_list(tool_list)
path = Utils.to_list(kw.get('tooldir', ''))
with_sys_path = kw.get('with_sys_path', True)
for t in tools:
module = load_tool(t, path, with_sys_path=with_sys_path)
fun = getattr(module, kw.get('name', self.fun), None)
if fun:
fun(self)
def execute(self):
"""
Here, it calls the function name in the top-level wscript file. Most subclasses
redefine this method to provide additional functionality.
"""
self.recurse([os.path.dirname(g_module.root_path)])
def pre_recurse(self, node):
"""
Method executed immediately before a folder is read by :py:meth:`waflib.Context.Context.recurse`.
The current script is bound as a Node object on ``self.cur_script``, and the current path
is bound to ``self.path``
:param node: script
:type node: :py:class:`waflib.Node.Node`
"""
self.stack_path.append(self.cur_script)
self.cur_script = node
self.path = node.parent
def post_recurse(self, node):
"""
Restores ``self.cur_script`` and ``self.path`` right after :py:meth:`waflib.Context.Context.recurse` terminates.
:param node: script
:type node: :py:class:`waflib.Node.Node`
"""
self.cur_script = self.stack_path.pop()
if self.cur_script:
self.path = self.cur_script.parent
def recurse(self, dirs, name=None, mandatory=True, once=True, encoding=None):
"""
Runs user-provided functions from the supplied list of directories.
The directories can be either absolute, or relative to the directory
of the wscript file
The methods :py:meth:`waflib.Context.Context.pre_recurse` and
:py:meth:`waflib.Context.Context.post_recurse` are called immediately before
and after a script has been executed.
:param dirs: List of directories to visit
:type dirs: list of string or space-separated string
:param name: Name of function to invoke from the wscript
:type name: string
:param mandatory: whether sub wscript files are required to exist
:type mandatory: bool
:param once: read the script file once for a particular context
:type once: bool
"""
try:
cache = self.recurse_cache
except AttributeError:
cache = self.recurse_cache = {}
for d in Utils.to_list(dirs):
if not os.path.isabs(d):
# absolute paths only
d = os.path.join(self.path.abspath(), d)
WSCRIPT = os.path.join(d, WSCRIPT_FILE)
WSCRIPT_FUN = WSCRIPT + '_' + (name or self.fun)
node = self.root.find_node(WSCRIPT_FUN)
if node and (not once or node not in cache):
cache[node] = True
self.pre_recurse(node)
try:
function_code = node.read('r', encoding)
exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
finally:
self.post_recurse(node)
elif not node:
node = self.root.find_node(WSCRIPT)
tup = (node, name or self.fun)
if node and (not once or tup not in cache):
cache[tup] = True
self.pre_recurse(node)
try:
wscript_module = load_module(node.abspath(), encoding=encoding)
user_function = getattr(wscript_module, (name or self.fun), None)
if not user_function:
if not mandatory:
continue
raise Errors.WafError('No function %r defined in %s' % (name or self.fun, node.abspath()))
user_function(self)
finally:
self.post_recurse(node)
elif not node:
if not mandatory:
continue
try:
os.listdir(d)
except OSError:
raise Errors.WafError('Cannot read the folder %r' % d)
raise Errors.WafError('No wscript file in directory %s' % d)
def log_command(self, cmd, kw):
if Logs.verbose:
fmt = os.environ.get('WAF_CMD_FORMAT')
if fmt == 'string':
if not isinstance(cmd, str):
cmd = Utils.shell_escape(cmd)
Logs.debug('runner: %r', cmd)
Logs.debug('runner_env: kw=%s', kw)
def exec_command(self, cmd, **kw):
"""
Runs an external process and returns the exit status::
def run(tsk):
ret = tsk.generator.bld.exec_command('touch foo.txt')
return ret
If the context has the attribute 'log', then captures and logs the process stderr/stdout.
Unlike :py:meth:`waflib.Context.Context.cmd_and_log`, this method does not return the
stdout/stderr values captured.
:param cmd: command argument for subprocess.Popen
:type cmd: string or list
:param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
:type kw: dict
:returns: process exit status
:rtype: integer
:raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
:raises: :py:class:`waflib.Errors.WafError` in case of execution failure
"""
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
self.log_command(cmd, kw)
if self.logger:
self.logger.info(cmd)
if 'stdout' not in kw:
kw['stdout'] = subprocess.PIPE
if 'stderr' not in kw:
kw['stderr'] = subprocess.PIPE
if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0]):
raise Errors.WafError('Program %s not found!' % cmd[0])
cargs = {}
if 'timeout' in kw:
if sys.hexversion >= 0x3030000:
cargs['timeout'] = kw['timeout']
if not 'start_new_session' in kw:
kw['start_new_session'] = True
del kw['timeout']
if 'input' in kw:
if kw['input']:
cargs['input'] = kw['input']
kw['stdin'] = subprocess.PIPE
del kw['input']
if 'cwd' in kw:
if not isinstance(kw['cwd'], str):
kw['cwd'] = kw['cwd'].abspath()
encoding = kw.pop('decode_as', default_encoding)
try:
ret, out, err = Utils.run_process(cmd, kw, cargs)
except Exception as e:
raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
if out:
if not isinstance(out, str):
out = out.decode(encoding, errors='replace')
if self.logger:
self.logger.debug('out: %s', out)
else:
Logs.info(out, extra={'stream':sys.stdout, 'c1': ''})
if err:
if not isinstance(err, str):
err = err.decode(encoding, errors='replace')
if self.logger:
self.logger.error('err: %s' % err)
else:
Logs.info(err, extra={'stream':sys.stderr, 'c1': ''})
return ret
def cmd_and_log(self, cmd, **kw):
"""
Executes a process and returns stdout/stderr if the execution is successful.
An exception is thrown when the exit status is non-0. In that case, both stderr and stdout
will be bound to the WafError object (configuration tests)::
def configure(conf):
out = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.STDOUT, quiet=waflib.Context.BOTH)
(out, err) = conf.cmd_and_log(['echo', 'hello'], output=waflib.Context.BOTH)
(out, err) = conf.cmd_and_log(cmd, input='\\n'.encode(), output=waflib.Context.STDOUT)
try:
conf.cmd_and_log(['which', 'someapp'], output=waflib.Context.BOTH)
except Errors.WafError as e:
print(e.stdout, e.stderr)
:param cmd: args for subprocess.Popen
:type cmd: list or string
:param kw: keyword arguments for subprocess.Popen. The parameters input/timeout will be passed to wait/communicate.
:type kw: dict
:returns: a tuple containing the contents of stdout and stderr
:rtype: string
:raises: :py:class:`waflib.Errors.WafError` if an invalid executable is specified for a non-shell process
:raises: :py:class:`waflib.Errors.WafError` in case of execution failure; stdout/stderr/returncode are bound to the exception object
"""
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
self.log_command(cmd, kw)
quiet = kw.pop('quiet', None)
to_ret = kw.pop('output', STDOUT)
if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0]):
raise Errors.WafError('Program %r not found!' % cmd[0])
kw['stdout'] = kw['stderr'] = subprocess.PIPE
if quiet is None:
self.to_log(cmd)
cargs = {}
if 'timeout' in kw:
if sys.hexversion >= 0x3030000:
cargs['timeout'] = kw['timeout']
if not 'start_new_session' in kw:
kw['start_new_session'] = True
del kw['timeout']
if 'input' in kw:
if kw['input']:
cargs['input'] = kw['input']
kw['stdin'] = subprocess.PIPE
del kw['input']
if 'cwd' in kw:
if not isinstance(kw['cwd'], str):
kw['cwd'] = kw['cwd'].abspath()
encoding = kw.pop('decode_as', default_encoding)
try:
ret, out, err = Utils.run_process(cmd, kw, cargs)
except Exception as e:
raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
if not isinstance(out, str):
out = out.decode(encoding, errors='replace')
if not isinstance(err, str):
err = err.decode(encoding, errors='replace')
if out and quiet != STDOUT and quiet != BOTH:
self.to_log('out: %s' % out)
if err and quiet != STDERR and quiet != BOTH:
self.to_log('err: %s' % err)
if ret:
e = Errors.WafError('Command %r returned %r' % (cmd, ret))
e.returncode = ret
e.stderr = err
e.stdout = out
raise e
if to_ret == BOTH:
return (out, err)
elif to_ret == STDERR:
return err
return out
def fatal(self, msg, ex=None):
"""
Prints an error message in red and stops command execution; this is
usually used in the configuration section::
def configure(conf):
conf.fatal('a requirement is missing')
:param msg: message to display
:type msg: string
:param ex: optional exception object
:type ex: exception
:raises: :py:class:`waflib.Errors.ConfigurationError`
"""
if self.logger:
self.logger.info('from %s: %s' % (self.path.abspath(), msg))
try:
logfile = self.logger.handlers[0].baseFilename
except AttributeError:
pass
else:
if os.environ.get('WAF_PRINT_FAILURE_LOG'):
# see #1930
msg = 'Log from (%s):\n%s\n' % (logfile, Utils.readf(logfile))
else:
msg = '%s\n(complete log in %s)' % (msg, logfile)
raise self.errors.ConfigurationError(msg, ex=ex)
def to_log(self, msg):
"""
Logs information to the logger (if present), or to stderr.
Empty messages are not printed::
def build(bld):
bld.to_log('starting the build')
Provide a logger on the context class or override this method if necessary.
:param msg: message
:type msg: string
"""
if not msg:
return
if self.logger:
self.logger.info(msg)
else:
sys.stderr.write(str(msg))
sys.stderr.flush()
def msg(self, *k, **kw):
"""
Prints a configuration message of the form ``msg: result``.
The second part of the message will be in colors. The output
can be disabled easily by setting ``in_msg`` to a positive value::
def configure(conf):
self.in_msg = 1
conf.msg('Checking for library foo', 'ok')
# no output
:param msg: message to display to the user
:type msg: string
:param result: result to display
:type result: string or boolean
:param color: color to use, see :py:const:`waflib.Logs.colors_lst`
:type color: string
"""
try:
msg = kw['msg']
except KeyError:
msg = k[0]
self.start_msg(msg, **kw)
try:
result = kw['result']
except KeyError:
result = k[1]
color = kw.get('color')
if not isinstance(color, str):
color = result and 'GREEN' or 'YELLOW'
self.end_msg(result, color, **kw)
def start_msg(self, *k, **kw):
"""
Prints the beginning of a 'Checking for xxx' message. See :py:meth:`waflib.Context.Context.msg`
"""
if kw.get('quiet'):
return
msg = kw.get('msg') or k[0]
try:
if self.in_msg:
self.in_msg += 1
return
except AttributeError:
self.in_msg = 0
self.in_msg += 1
try:
self.line_just = max(self.line_just, len(msg))
except AttributeError:
self.line_just = max(40, len(msg))
for x in (self.line_just * '-', msg):
self.to_log(x)
Logs.pprint('NORMAL', "%s :" % msg.ljust(self.line_just), sep='')
def end_msg(self, *k, **kw):
"""Prints the end of a 'Checking for' message. See :py:meth:`waflib.Context.Context.msg`"""
if kw.get('quiet'):
return
self.in_msg -= 1
if self.in_msg:
return
result = kw.get('result') or k[0]
defcolor = 'GREEN'
if result is True:
msg = 'ok'
elif not result:
msg = 'not found'
defcolor = 'YELLOW'
else:
msg = str(result)
self.to_log(msg)
try:
color = kw['color']
except KeyError:
if len(k) > 1 and k[1] in Logs.colors_lst:
# compatibility waf 1.7
color = k[1]
else:
color = defcolor
Logs.pprint(color, msg)
def load_special_tools(self, var, ban=[]):
"""
Loads third-party extensions modules for certain programming languages
by trying to list certain files in the extras/ directory. This method
is typically called once for a programming language group, see for
example :py:mod:`waflib.Tools.compiler_c`
:param var: glob expression, for example 'cxx\\_\\*.py'
:type var: string
:param ban: list of exact file names to exclude
:type ban: list of string
"""
if os.path.isdir(waf_dir):
lst = self.root.find_node(waf_dir).find_node('waflib/extras').ant_glob(var)
for x in lst:
if not x.name in ban:
load_tool(x.name.replace('.py', ''))
else:
from zipfile import PyZipFile
waflibs = PyZipFile(waf_dir)
lst = waflibs.namelist()
for x in lst:
if not re.match('waflib/extras/%s' % var.replace('*', '.*'), var):
continue
f = os.path.basename(x)
doban = False
for b in ban:
r = b.replace('*', '.*')
if re.match(r, f):
doban = True
if not doban:
f = f.replace('.py', '')
load_tool(f)
cache_modules = {}
"""
Dictionary holding already loaded modules (wscript), indexed by their absolute path.
The modules are added automatically by :py:func:`waflib.Context.load_module`
"""
def load_module(path, encoding=None):
"""
Loads a wscript file as a python module. This method caches results in :py:attr:`waflib.Context.cache_modules`
:param path: file path
:type path: string
:return: Loaded Python module
:rtype: module
"""
try:
return cache_modules[path]
except KeyError:
pass
module = imp.new_module(WSCRIPT_FILE)
try:
code = Utils.readf(path, m='r', encoding=encoding)
except EnvironmentError:
raise Errors.WafError('Could not read the file %r' % path)
module_dir = os.path.dirname(path)
sys.path.insert(0, module_dir)
try:
exec(compile(code, path, 'exec'), module.__dict__)
finally:
sys.path.remove(module_dir)
cache_modules[path] = module
return module
def load_tool(tool, tooldir=None, ctx=None, with_sys_path=True):
"""
Imports a Waf tool as a python module, and stores it in the dict :py:const:`waflib.Context.Context.tools`
:type tool: string
:param tool: Name of the tool
:type tooldir: list
:param tooldir: List of directories to search for the tool module
:type with_sys_path: boolean
:param with_sys_path: whether or not to search the regular sys.path, besides waf_dir and potentially given tooldirs
"""
if tool == 'java':
tool = 'javaw' # jython
else:
tool = tool.replace('++', 'xx')
if not with_sys_path:
back_path = sys.path
sys.path = []
try:
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
__import__(tool)
except ImportError as e:
e.waf_sys_path = list(sys.path)
raise
finally:
for d in tooldir:
sys.path.remove(d)
ret = sys.modules[tool]
Context.tools[tool] = ret
return ret
else:
if not with_sys_path:
sys.path.insert(0, waf_dir)
try:
for x in ('waflib.Tools.%s', 'waflib.extras.%s', 'waflib.%s', '%s'):
try:
__import__(x % tool)
break
except ImportError:
x = None
else: # raise an exception
__import__(tool)
except ImportError as e:
e.waf_sys_path = list(sys.path)
raise
finally:
if not with_sys_path:
sys.path.remove(waf_dir)
ret = sys.modules[x % tool]
Context.tools[tool] = ret
return ret
finally:
if not with_sys_path:
sys.path += back_path
| 21,252 | Python | .py | 629 | 30.337043 | 295 | 0.693392 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,579 | fixpy2.py | projecthamster_hamster/waflib/fixpy2.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010-2018 (ita)
from __future__ import with_statement
import os
all_modifs = {}
def fixdir(dir):
"""Call all substitution functions on Waf folders"""
for k in all_modifs:
for v in all_modifs[k]:
modif(os.path.join(dir, 'waflib'), k, v)
def modif(dir, name, fun):
"""Call a substitution function"""
if name == '*':
lst = []
for y in '. Tools extras'.split():
for x in os.listdir(os.path.join(dir, y)):
if x.endswith('.py'):
lst.append(y + os.sep + x)
for x in lst:
modif(dir, x, fun)
return
filename = os.path.join(dir, name)
with open(filename, 'r') as f:
txt = f.read()
txt = fun(txt)
with open(filename, 'w') as f:
f.write(txt)
def subst(*k):
"""register a substitution function"""
def do_subst(fun):
for x in k:
try:
all_modifs[x].append(fun)
except KeyError:
all_modifs[x] = [fun]
return fun
return do_subst
@subst('*')
def r1(code):
"utf-8 fixes for python < 2.6"
code = code.replace('as e:', ',e:')
code = code.replace(".decode(sys.stdout.encoding or'latin-1',errors='replace')", '')
return code.replace('.encode()', '')
@subst('Runner.py')
def r4(code):
"generator syntax"
return code.replace('next(self.biter)', 'self.biter.next()').replace('self.daemon = True', 'self.setDaemon(1)')
@subst('Context.py')
def r5(code):
return code.replace("('Execution failure: %s'%str(e),ex=e)", "('Execution failure: %s'%str(e),ex=e),None,sys.exc_info()[2]")
| 1,488 | Python | .py | 51 | 26.588235 | 125 | 0.656601 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,580 | Task.py | projecthamster_hamster/waflib/Task.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Tasks represent atomic operations such as processes.
"""
import os, re, sys, tempfile, traceback
from waflib import Utils, Logs, Errors
# task states
NOT_RUN = 0
"""The task was not executed yet"""
MISSING = 1
"""The task has been executed but the files have not been created"""
CRASHED = 2
"""The task execution returned a non-zero exit status"""
EXCEPTION = 3
"""An exception occurred in the task execution"""
CANCELED = 4
"""A dependency for the task is missing so it was cancelled"""
SKIPPED = 8
"""The task did not have to be executed"""
SUCCESS = 9
"""The task was successfully executed"""
ASK_LATER = -1
"""The task is not ready to be executed"""
SKIP_ME = -2
"""The task does not need to be executed"""
RUN_ME = -3
"""The task must be executed"""
CANCEL_ME = -4
"""The task cannot be executed because of a dependency problem"""
COMPILE_TEMPLATE_SHELL = '''
def f(tsk):
env = tsk.env
gen = tsk.generator
bld = gen.bld
cwdx = tsk.get_cwd()
p = env.get_flat
def to_list(xx):
if isinstance(xx, str): return [xx]
return xx
tsk.last_cmd = cmd = \'\'\' %s \'\'\' % s
return tsk.exec_command(cmd, cwd=cwdx, env=env.env or None)
'''
COMPILE_TEMPLATE_NOSHELL = '''
def f(tsk):
env = tsk.env
gen = tsk.generator
bld = gen.bld
cwdx = tsk.get_cwd()
def to_list(xx):
if isinstance(xx, str): return [xx]
return xx
def merge(lst1, lst2):
if lst1 and lst2:
return lst1[:-1] + [lst1[-1] + lst2[0]] + lst2[1:]
return lst1 + lst2
lst = []
%s
if '' in lst:
lst = [x for x in lst if x]
tsk.last_cmd = lst
return tsk.exec_command(lst, cwd=cwdx, env=env.env or None)
'''
COMPILE_TEMPLATE_SIG_VARS = '''
def f(tsk):
sig = tsk.generator.bld.hash_env_vars(tsk.env, tsk.vars)
tsk.m.update(sig)
env = tsk.env
gen = tsk.generator
bld = gen.bld
cwdx = tsk.get_cwd()
p = env.get_flat
buf = []
%s
tsk.m.update(repr(buf).encode())
'''
classes = {}
"""
The metaclass :py:class:`waflib.Task.store_task_type` stores all class tasks
created by user scripts or Waf tools to this dict. It maps class names to class objects.
"""
class store_task_type(type):
"""
Metaclass: store the task classes into the dict pointed by the
class attribute 'register' which defaults to :py:const:`waflib.Task.classes`,
The attribute 'run_str' is compiled into a method 'run' bound to the task class.
"""
def __init__(cls, name, bases, dict):
super(store_task_type, cls).__init__(name, bases, dict)
name = cls.__name__
if name != 'evil' and name != 'Task':
if getattr(cls, 'run_str', None):
# if a string is provided, convert it to a method
(f, dvars) = compile_fun(cls.run_str, cls.shell)
cls.hcode = Utils.h_cmd(cls.run_str)
cls.orig_run_str = cls.run_str
# change the name of run_str or it is impossible to subclass with a function
cls.run_str = None
cls.run = f
# process variables
cls.vars = list(set(cls.vars + dvars))
cls.vars.sort()
if cls.vars:
fun = compile_sig_vars(cls.vars)
if fun:
cls.sig_vars = fun
elif getattr(cls, 'run', None) and not 'hcode' in cls.__dict__:
# getattr(cls, 'hcode') would look in the upper classes
cls.hcode = Utils.h_cmd(cls.run)
# be creative
getattr(cls, 'register', classes)[name] = cls
evil = store_task_type('evil', (object,), {})
"Base class provided to avoid writing a metaclass, so the code can run in python 2.6 and 3.x unmodified"
class Task(evil):
"""
Task objects represents actions to perform such as commands to execute by calling the `run` method.
Detecting when to execute a task occurs in the method :py:meth:`waflib.Task.Task.runnable_status`.
Detecting which tasks to execute is performed through a hash value returned by
:py:meth:`waflib.Task.Task.signature`. The task signature is persistent from build to build.
"""
vars = []
"""ConfigSet variables that should trigger a rebuild (class attribute used for :py:meth:`waflib.Task.Task.sig_vars`)"""
always_run = False
"""Specify whether task instances must always be executed or not (class attribute)"""
shell = False
"""Execute the command with the shell (class attribute)"""
color = 'GREEN'
"""Color for the console display, see :py:const:`waflib.Logs.colors_lst`"""
ext_in = []
"""File extensions that objects of this task class may use"""
ext_out = []
"""File extensions that objects of this task class may create"""
before = []
"""The instances of this class are executed before the instances of classes whose names are in this list"""
after = []
"""The instances of this class are executed after the instances of classes whose names are in this list"""
hcode = Utils.SIG_NIL
"""String representing an additional hash for the class representation"""
keep_last_cmd = False
"""Whether to keep the last command executed on the instance after execution.
This may be useful for certain extensions but it can a lot of memory.
"""
weight = 0
"""Optional weight to tune the priority for task instances.
The higher, the earlier. The weight only applies to single task objects."""
tree_weight = 0
"""Optional weight to tune the priority of task instances and whole subtrees.
The higher, the earlier."""
prio_order = 0
"""Priority order set by the scheduler on instances during the build phase.
You most likely do not need to set it.
"""
__slots__ = ('hasrun', 'generator', 'env', 'inputs', 'outputs', 'dep_nodes', 'run_after')
def __init__(self, *k, **kw):
self.hasrun = NOT_RUN
try:
self.generator = kw['generator']
except KeyError:
self.generator = self
self.env = kw['env']
""":py:class:`waflib.ConfigSet.ConfigSet` object (make sure to provide one)"""
self.inputs = []
"""List of input nodes, which represent the files used by the task instance"""
self.outputs = []
"""List of output nodes, which represent the files created by the task instance"""
self.dep_nodes = []
"""List of additional nodes to depend on"""
self.run_after = set()
"""Set of tasks that must be executed before this one"""
def __lt__(self, other):
return self.priority() > other.priority()
def __le__(self, other):
return self.priority() >= other.priority()
def __gt__(self, other):
return self.priority() < other.priority()
def __ge__(self, other):
return self.priority() <= other.priority()
def get_cwd(self):
"""
:return: current working directory
:rtype: :py:class:`waflib.Node.Node`
"""
bld = self.generator.bld
ret = getattr(self, 'cwd', None) or getattr(bld, 'cwd', bld.bldnode)
if isinstance(ret, str):
if os.path.isabs(ret):
ret = bld.root.make_node(ret)
else:
ret = self.generator.path.make_node(ret)
return ret
def quote_flag(self, x):
"""
Surround a process argument by quotes so that a list of arguments can be written to a file
:param x: flag
:type x: string
:return: quoted flag
:rtype: string
"""
old = x
if '\\' in x:
x = x.replace('\\', '\\\\')
if '"' in x:
x = x.replace('"', '\\"')
if old != x or ' ' in x or '\t' in x or "'" in x:
x = '"%s"' % x
return x
def priority(self):
"""
Priority of execution; the higher, the earlier
:return: the priority value
:rtype: a tuple of numeric values
"""
return (self.weight + self.prio_order, - getattr(self.generator, 'tg_idx_count', 0))
def split_argfile(self, cmd):
"""
Splits a list of process commands into the executable part and its list of arguments
:return: a tuple containing the executable first and then the rest of arguments
:rtype: tuple
"""
return ([cmd[0]], [self.quote_flag(x) for x in cmd[1:]])
def exec_command(self, cmd, **kw):
"""
Wrapper for :py:meth:`waflib.Context.Context.exec_command`.
This version set the current working directory (``build.variant_dir``),
applies PATH settings (if self.env.PATH is provided), and can run long
commands through a temporary ``@argfile``.
:param cmd: process command to execute
:type cmd: list of string (best) or string (process will use a shell)
:return: the return code
:rtype: int
Optional parameters:
#. cwd: current working directory (Node or string)
#. stdout: set to None to prevent waf from capturing the process standard output
#. stderr: set to None to prevent waf from capturing the process standard error
#. timeout: timeout value (Python 3)
"""
if not 'cwd' in kw:
kw['cwd'] = self.get_cwd()
if hasattr(self, 'timeout'):
kw['timeout'] = self.timeout
if self.env.PATH:
env = kw['env'] = dict(kw.get('env') or self.env.env or os.environ)
env['PATH'] = self.env.PATH if isinstance(self.env.PATH, str) else os.pathsep.join(self.env.PATH)
if hasattr(self, 'stdout'):
kw['stdout'] = self.stdout
if hasattr(self, 'stderr'):
kw['stderr'] = self.stderr
if not isinstance(cmd, str):
if Utils.is_win32:
# win32 compares the resulting length http://support.microsoft.com/kb/830473
too_long = sum([len(arg) for arg in cmd]) + len(cmd) > 8192
else:
# non-win32 counts the amount of arguments (200k)
too_long = len(cmd) > 200000
if too_long and getattr(self, 'allow_argsfile', True):
# Shunt arguments to a temporary file if the command is too long.
cmd, args = self.split_argfile(cmd)
try:
(fd, tmp) = tempfile.mkstemp()
os.write(fd, '\r\n'.join(args).encode())
os.close(fd)
if Logs.verbose:
Logs.debug('argfile: @%r -> %r', tmp, args)
return self.generator.bld.exec_command(cmd + ['@' + tmp], **kw)
finally:
try:
os.remove(tmp)
except OSError:
# anti-virus and indexers can keep files open -_-
pass
return self.generator.bld.exec_command(cmd, **kw)
def process(self):
"""
Runs the task and handles errors
:return: 0 or None if everything is fine
:rtype: integer
"""
# remove the task signature immediately before it is executed
# so that the task will be executed again in case of failure
try:
del self.generator.bld.task_sigs[self.uid()]
except KeyError:
pass
try:
ret = self.run()
except Exception:
self.err_msg = traceback.format_exc()
self.hasrun = EXCEPTION
else:
if ret:
self.err_code = ret
self.hasrun = CRASHED
else:
try:
self.post_run()
except Errors.WafError:
pass
except Exception:
self.err_msg = traceback.format_exc()
self.hasrun = EXCEPTION
else:
self.hasrun = SUCCESS
if self.hasrun != SUCCESS and self.scan:
# rescan dependencies on next run
try:
del self.generator.bld.imp_sigs[self.uid()]
except KeyError:
pass
def log_display(self, bld):
"Writes the execution status on the context logger"
if self.generator.bld.progress_bar == 3:
return
s = self.display()
if s:
if bld.logger:
logger = bld.logger
else:
logger = Logs
if self.generator.bld.progress_bar == 1:
c1 = Logs.colors.cursor_off
c2 = Logs.colors.cursor_on
logger.info(s, extra={'stream': sys.stderr, 'terminator':'', 'c1': c1, 'c2' : c2})
else:
logger.info(s, extra={'terminator':'', 'c1': '', 'c2' : ''})
def display(self):
"""
Returns an execution status for the console, the progress bar, or the IDE output.
:rtype: string
"""
col1 = Logs.colors(self.color)
col2 = Logs.colors.NORMAL
master = self.generator.bld.producer
def cur():
# the current task position, computed as late as possible
return master.processed - master.ready.qsize()
if self.generator.bld.progress_bar == 1:
return self.generator.bld.progress_line(cur(), master.total, col1, col2)
if self.generator.bld.progress_bar == 2:
ela = str(self.generator.bld.timer)
try:
ins = ','.join([n.name for n in self.inputs])
except AttributeError:
ins = ''
try:
outs = ','.join([n.name for n in self.outputs])
except AttributeError:
outs = ''
return '|Total %s|Current %s|Inputs %s|Outputs %s|Time %s|\n' % (master.total, cur(), ins, outs, ela)
s = str(self)
if not s:
return None
total = master.total
n = len(str(total))
fs = '[%%%dd/%%%dd] %%s%%s%%s%%s\n' % (n, n)
kw = self.keyword()
if kw:
kw += ' '
return fs % (cur(), total, kw, col1, s, col2)
def hash_constraints(self):
"""
Identifies a task type for all the constraints relevant for the scheduler: precedence, file production
:return: a hash value
:rtype: string
"""
return (tuple(self.before), tuple(self.after), tuple(self.ext_in), tuple(self.ext_out), self.__class__.__name__, self.hcode)
def format_error(self):
"""
Returns an error message to display the build failure reasons
:rtype: string
"""
if Logs.verbose:
msg = ': %r\n%r' % (self, getattr(self, 'last_cmd', ''))
else:
msg = ' (run with -v to display more information)'
name = getattr(self.generator, 'name', '')
if getattr(self, "err_msg", None):
return self.err_msg
elif not self.hasrun:
return 'task in %r was not executed for some reason: %r' % (name, self)
elif self.hasrun == CRASHED:
try:
return ' -> task in %r failed with exit status %r%s' % (name, self.err_code, msg)
except AttributeError:
return ' -> task in %r failed%s' % (name, msg)
elif self.hasrun == MISSING:
return ' -> missing files in %r%s' % (name, msg)
elif self.hasrun == CANCELED:
return ' -> %r canceled because of missing dependencies' % name
else:
return 'invalid status for task in %r: %r' % (name, self.hasrun)
def colon(self, var1, var2):
"""
Enable scriptlet expressions of the form ${FOO_ST:FOO}
If the first variable (FOO_ST) is empty, then an empty list is returned
The results will be slightly different if FOO_ST is a list, for example::
env.FOO = ['p1', 'p2']
env.FOO_ST = '-I%s'
# ${FOO_ST:FOO} returns
['-Ip1', '-Ip2']
env.FOO_ST = ['-a', '-b']
# ${FOO_ST:FOO} returns
['-a', '-b', 'p1', '-a', '-b', 'p2']
"""
tmp = self.env[var1]
if not tmp:
return []
if isinstance(var2, str):
it = self.env[var2]
else:
it = var2
if isinstance(tmp, str):
return [tmp % x for x in it]
else:
lst = []
for y in it:
lst.extend(tmp)
lst.append(y)
return lst
def __str__(self):
"string to display to the user"
name = self.__class__.__name__
if self.outputs:
if name.endswith(('lib', 'program')) or not self.inputs:
node = self.outputs[0]
return node.path_from(node.ctx.launch_node())
if not (self.inputs or self.outputs):
return self.__class__.__name__
if len(self.inputs) == 1:
node = self.inputs[0]
return node.path_from(node.ctx.launch_node())
src_str = ' '.join([a.path_from(a.ctx.launch_node()) for a in self.inputs])
tgt_str = ' '.join([a.path_from(a.ctx.launch_node()) for a in self.outputs])
if self.outputs:
sep = ' -> '
else:
sep = ''
return '%s: %s%s%s' % (self.__class__.__name__, src_str, sep, tgt_str)
def keyword(self):
"Display keyword used to prettify the console outputs"
name = self.__class__.__name__
if name.endswith(('lib', 'program')):
return 'Linking'
if len(self.inputs) == 1 and len(self.outputs) == 1:
return 'Compiling'
if not self.inputs:
if self.outputs:
return 'Creating'
else:
return 'Running'
return 'Processing'
def __repr__(self):
"for debugging purposes"
try:
ins = ",".join([x.name for x in self.inputs])
outs = ",".join([x.name for x in self.outputs])
except AttributeError:
ins = ",".join([str(x) for x in self.inputs])
outs = ",".join([str(x) for x in self.outputs])
return "".join(['\n\t{task %r: ' % id(self), self.__class__.__name__, " ", ins, " -> ", outs, '}'])
def uid(self):
"""
Returns an identifier used to determine if tasks are up-to-date. Since the
identifier will be stored between executions, it must be:
- unique for a task: no two tasks return the same value (for a given build context)
- the same for a given task instance
By default, the node paths, the class name, and the function are used
as inputs to compute a hash.
The pointer to the object (python built-in 'id') will change between build executions,
and must be avoided in such hashes.
:return: hash value
:rtype: string
"""
try:
return self.uid_
except AttributeError:
m = Utils.md5(self.__class__.__name__)
up = m.update
for x in self.inputs + self.outputs:
up(x.abspath())
self.uid_ = m.digest()
return self.uid_
def set_inputs(self, inp):
"""
Appends the nodes to the *inputs* list
:param inp: input nodes
:type inp: node or list of nodes
"""
if isinstance(inp, list):
self.inputs += inp
else:
self.inputs.append(inp)
def set_outputs(self, out):
"""
Appends the nodes to the *outputs* list
:param out: output nodes
:type out: node or list of nodes
"""
if isinstance(out, list):
self.outputs += out
else:
self.outputs.append(out)
def set_run_after(self, task):
"""
Run this task only after the given *task*.
Calling this method from :py:meth:`waflib.Task.Task.runnable_status` may cause
build deadlocks; see :py:meth:`waflib.Tools.fc.fc.runnable_status` for details.
:param task: task
:type task: :py:class:`waflib.Task.Task`
"""
assert isinstance(task, Task)
self.run_after.add(task)
def signature(self):
"""
Task signatures are stored between build executions, they are use to track the changes
made to the input nodes (not to the outputs!). The signature hashes data from various sources:
* explicit dependencies: files listed in the inputs (list of node objects) :py:meth:`waflib.Task.Task.sig_explicit_deps`
* implicit dependencies: list of nodes returned by scanner methods (when present) :py:meth:`waflib.Task.Task.sig_implicit_deps`
* hashed data: variables/values read from task.vars/task.env :py:meth:`waflib.Task.Task.sig_vars`
If the signature is expected to give a different result, clear the cache kept in ``self.cache_sig``::
from waflib import Task
class cls(Task.Task):
def signature(self):
sig = super(Task.Task, self).signature()
delattr(self, 'cache_sig')
return super(Task.Task, self).signature()
:return: the signature value
:rtype: string or bytes
"""
try:
return self.cache_sig
except AttributeError:
pass
self.m = Utils.md5(self.hcode)
# explicit deps
self.sig_explicit_deps()
# env vars
self.sig_vars()
# implicit deps / scanner results
if self.scan:
try:
self.sig_implicit_deps()
except Errors.TaskRescan:
return self.signature()
ret = self.cache_sig = self.m.digest()
return ret
def runnable_status(self):
"""
Returns the Task status
:return: a task state in :py:const:`waflib.Task.RUN_ME`,
:py:const:`waflib.Task.SKIP_ME`, :py:const:`waflib.Task.CANCEL_ME` or :py:const:`waflib.Task.ASK_LATER`.
:rtype: int
"""
bld = self.generator.bld
if bld.is_install < 0:
return SKIP_ME
for t in self.run_after:
if not t.hasrun:
return ASK_LATER
elif t.hasrun < SKIPPED:
# a dependency has an error
return CANCEL_ME
# first compute the signature
try:
new_sig = self.signature()
except Errors.TaskNotReady:
return ASK_LATER
# compare the signature to a signature computed previously
key = self.uid()
try:
prev_sig = bld.task_sigs[key]
except KeyError:
Logs.debug('task: task %r must run: it was never run before or the task code changed', self)
return RUN_ME
if new_sig != prev_sig:
Logs.debug('task: task %r must run: the task signature changed', self)
return RUN_ME
# compare the signatures of the outputs
for node in self.outputs:
sig = bld.node_sigs.get(node)
if not sig:
Logs.debug('task: task %r must run: an output node has no signature', self)
return RUN_ME
if sig != key:
Logs.debug('task: task %r must run: an output node was produced by another task', self)
return RUN_ME
if not node.exists():
Logs.debug('task: task %r must run: an output node does not exist', self)
return RUN_ME
return (self.always_run and RUN_ME) or SKIP_ME
def post_run(self):
"""
Called after successful execution to record that the task has run by
updating the entry in :py:attr:`waflib.Build.BuildContext.task_sigs`.
"""
bld = self.generator.bld
for node in self.outputs:
if not node.exists():
self.hasrun = MISSING
self.err_msg = '-> missing file: %r' % node.abspath()
raise Errors.WafError(self.err_msg)
bld.node_sigs[node] = self.uid() # make sure this task produced the files in question
bld.task_sigs[self.uid()] = self.signature()
if not self.keep_last_cmd:
try:
del self.last_cmd
except AttributeError:
pass
def sig_explicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.signature`; it hashes :py:attr:`waflib.Task.Task.inputs`
and :py:attr:`waflib.Task.Task.dep_nodes` signatures.
"""
bld = self.generator.bld
upd = self.m.update
# the inputs
for x in self.inputs + self.dep_nodes:
upd(x.get_bld_sig())
# manual dependencies, they can slow down the builds
if bld.deps_man:
additional_deps = bld.deps_man
for x in self.inputs + self.outputs:
try:
d = additional_deps[x]
except KeyError:
continue
for v in d:
try:
v = v.get_bld_sig()
except AttributeError:
if hasattr(v, '__call__'):
v = v() # dependency is a function, call it
upd(v)
def sig_deep_inputs(self):
"""
Enable rebuilds on input files task signatures. Not used by default.
Example: hashes of output programs can be unchanged after being re-linked,
despite the libraries being different. This method can thus prevent stale unit test
results (waf_unit_test.py).
Hashing input file timestamps is another possibility for the implementation.
This may cause unnecessary rebuilds when input tasks are frequently executed.
Here is an implementation example::
lst = []
for node in self.inputs + self.dep_nodes:
st = os.stat(node.abspath())
lst.append(st.st_mtime)
lst.append(st.st_size)
self.m.update(Utils.h_list(lst))
The downside of the implementation is that it absolutely requires all build directory
files to be declared within the current build.
"""
bld = self.generator.bld
lst = [bld.task_sigs[bld.node_sigs[node]] for node in (self.inputs + self.dep_nodes) if node.is_bld()]
self.m.update(Utils.h_list(lst))
def sig_vars(self):
"""
Used by :py:meth:`waflib.Task.Task.signature`; it hashes :py:attr:`waflib.Task.Task.env` variables/values
When overriding this method, and if scriptlet expressions are used, make sure to follow
the code in :py:meth:`waflib.Task.Task.compile_sig_vars` to enable dependencies on scriptlet results.
This method may be replaced on subclasses by the metaclass to force dependencies on scriptlet code.
"""
sig = self.generator.bld.hash_env_vars(self.env, self.vars)
self.m.update(sig)
scan = None
"""
This method, when provided, returns a tuple containing:
* a list of nodes corresponding to real files
* a list of names for files not found in path_lst
For example::
from waflib.Task import Task
class mytask(Task):
def scan(self, node):
return ([], [])
The first and second lists in the tuple are stored in :py:attr:`waflib.Build.BuildContext.node_deps` and
:py:attr:`waflib.Build.BuildContext.raw_deps` respectively.
"""
def sig_implicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.signature`; it hashes node signatures
obtained by scanning for dependencies (:py:meth:`waflib.Task.Task.scan`).
The exception :py:class:`waflib.Errors.TaskRescan` is thrown
when a file has changed. In this case, the method :py:meth:`waflib.Task.Task.signature` is called
once again, and return here to call :py:meth:`waflib.Task.Task.scan` and searching for dependencies.
"""
bld = self.generator.bld
# get the task signatures from previous runs
key = self.uid()
prev = bld.imp_sigs.get(key, [])
# for issue #379
if prev:
try:
if prev == self.compute_sig_implicit_deps():
return prev
except Errors.TaskNotReady:
raise
except EnvironmentError:
# when a file was renamed, remove the stale nodes (headers in folders without source files)
# this will break the order calculation for headers created during the build in the source directory (should be uncommon)
# the behaviour will differ when top != out
for x in bld.node_deps.get(self.uid(), []):
if not x.is_bld() and not x.exists():
try:
del x.parent.children[x.name]
except KeyError:
pass
del bld.imp_sigs[key]
raise Errors.TaskRescan('rescan')
# no previous run or the signature of the dependencies has changed, rescan the dependencies
(bld.node_deps[key], bld.raw_deps[key]) = self.scan()
if Logs.verbose:
Logs.debug('deps: scanner for %s: %r; unresolved: %r', self, bld.node_deps[key], bld.raw_deps[key])
# recompute the signature and return it
try:
bld.imp_sigs[key] = self.compute_sig_implicit_deps()
except EnvironmentError:
for k in bld.node_deps.get(self.uid(), []):
if not k.exists():
Logs.warn('Dependency %r for %r is missing: check the task declaration and the build order!', k, self)
raise
def compute_sig_implicit_deps(self):
"""
Used by :py:meth:`waflib.Task.Task.sig_implicit_deps` for computing the actual hash of the
:py:class:`waflib.Node.Node` returned by the scanner.
:return: a hash value for the implicit dependencies
:rtype: string or bytes
"""
upd = self.m.update
self.are_implicit_nodes_ready()
# scanner returns a node that does not have a signature
# just *ignore* the error and let them figure out from the compiler output
# waf -k behaviour
for k in self.generator.bld.node_deps.get(self.uid(), []):
upd(k.get_bld_sig())
return self.m.digest()
def are_implicit_nodes_ready(self):
"""
For each node returned by the scanner, see if there is a task that creates it,
and infer the build order
This has a low performance impact on null builds (1.86s->1.66s) thanks to caching (28s->1.86s)
"""
bld = self.generator.bld
try:
cache = bld.dct_implicit_nodes
except AttributeError:
bld.dct_implicit_nodes = cache = {}
# one cache per build group
try:
dct = cache[bld.current_group]
except KeyError:
dct = cache[bld.current_group] = {}
for tsk in bld.cur_tasks:
for x in tsk.outputs:
dct[x] = tsk
modified = False
for x in bld.node_deps.get(self.uid(), []):
if x in dct:
self.run_after.add(dct[x])
modified = True
if modified:
for tsk in self.run_after:
if not tsk.hasrun:
#print "task is not ready..."
raise Errors.TaskNotReady('not ready')
if sys.hexversion > 0x3000000:
def uid(self):
try:
return self.uid_
except AttributeError:
m = Utils.md5(self.__class__.__name__.encode('latin-1', 'xmlcharrefreplace'))
up = m.update
for x in self.inputs + self.outputs:
up(x.abspath().encode('latin-1', 'xmlcharrefreplace'))
self.uid_ = m.digest()
return self.uid_
uid.__doc__ = Task.uid.__doc__
Task.uid = uid
def is_before(t1, t2):
"""
Returns a non-zero value if task t1 is to be executed before task t2::
t1.ext_out = '.h'
t2.ext_in = '.h'
t2.after = ['t1']
t1.before = ['t2']
waflib.Task.is_before(t1, t2) # True
:param t1: Task object
:type t1: :py:class:`waflib.Task.Task`
:param t2: Task object
:type t2: :py:class:`waflib.Task.Task`
"""
to_list = Utils.to_list
for k in to_list(t2.ext_in):
if k in to_list(t1.ext_out):
return 1
if t1.__class__.__name__ in to_list(t2.after):
return 1
if t2.__class__.__name__ in to_list(t1.before):
return 1
return 0
def set_file_constraints(tasks):
"""
Updates the ``run_after`` attribute of all tasks based on the task inputs and outputs
:param tasks: tasks
:type tasks: list of :py:class:`waflib.Task.Task`
"""
ins = Utils.defaultdict(set)
outs = Utils.defaultdict(set)
for x in tasks:
for a in x.inputs:
ins[a].add(x)
for a in x.dep_nodes:
ins[a].add(x)
for a in x.outputs:
outs[a].add(x)
links = set(ins.keys()).intersection(outs.keys())
for k in links:
for a in ins[k]:
a.run_after.update(outs[k])
class TaskGroup(object):
"""
Wrap nxm task order constraints into a single object
to prevent the creation of large list/set objects
This is an optimization
"""
def __init__(self, prev, next):
self.prev = prev
self.next = next
self.done = False
def get_hasrun(self):
for k in self.prev:
if not k.hasrun:
return NOT_RUN
return SUCCESS
hasrun = property(get_hasrun, None)
def set_precedence_constraints(tasks):
"""
Updates the ``run_after`` attribute of all tasks based on the after/before/ext_out/ext_in attributes
:param tasks: tasks
:type tasks: list of :py:class:`waflib.Task.Task`
"""
cstr_groups = Utils.defaultdict(list)
for x in tasks:
h = x.hash_constraints()
cstr_groups[h].append(x)
keys = list(cstr_groups.keys())
maxi = len(keys)
# this list should be short
for i in range(maxi):
t1 = cstr_groups[keys[i]][0]
for j in range(i + 1, maxi):
t2 = cstr_groups[keys[j]][0]
# add the constraints based on the comparisons
if is_before(t1, t2):
a = i
b = j
elif is_before(t2, t1):
a = j
b = i
else:
continue
a = cstr_groups[keys[a]]
b = cstr_groups[keys[b]]
if len(a) < 2 or len(b) < 2:
for x in b:
x.run_after.update(a)
else:
group = TaskGroup(set(a), set(b))
for x in b:
x.run_after.add(group)
def funex(c):
"""
Compiles a scriptlet expression into a Python function
:param c: function to compile
:type c: string
:return: the function 'f' declared in the input string
:rtype: function
"""
dc = {}
exec(c, dc)
return dc['f']
re_cond = re.compile(r'(?P<var>\w+)|(?P<or>\|)|(?P<and>&)')
re_novar = re.compile(r'^(SRC|TGT)\W+.*?$')
reg_act = re.compile(r'(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<var>\w+)(?P<code>.*?)\})', re.M)
def compile_fun_shell(line):
"""
Creates a compiled function to execute a process through a sub-shell
"""
extr = []
def repl(match):
g = match.group
if g('dollar'):
return "$"
elif g('backslash'):
return '\\\\'
elif g('subst'):
extr.append((g('var'), g('code')))
return "%s"
return None
line = reg_act.sub(repl, line) or line
dvars = []
def add_dvar(x):
if x not in dvars:
dvars.append(x)
def replc(m):
# performs substitutions and populates dvars
if m.group('and'):
return ' and '
elif m.group('or'):
return ' or '
else:
x = m.group('var')
add_dvar(x)
return 'env[%r]' % x
parm = []
app = parm.append
for (var, meth) in extr:
if var == 'SRC':
if meth:
app('tsk.inputs%s' % meth)
else:
app('" ".join([a.path_from(cwdx) for a in tsk.inputs])')
elif var == 'TGT':
if meth:
app('tsk.outputs%s' % meth)
else:
app('" ".join([a.path_from(cwdx) for a in tsk.outputs])')
elif meth:
if meth.startswith(':'):
add_dvar(var)
m = meth[1:]
if m == 'SRC':
m = '[a.path_from(cwdx) for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.path_from(cwdx) for a in tsk.outputs]'
elif re_novar.match(m):
m = '[tsk.inputs%s]' % m[3:]
elif re_novar.match(m):
m = '[tsk.outputs%s]' % m[3:]
else:
add_dvar(m)
if m[:3] not in ('tsk', 'gen', 'bld'):
m = '%r' % m
app('" ".join(tsk.colon(%r, %s))' % (var, m))
elif meth.startswith('?'):
# In A?B|C output env.A if one of env.B or env.C is non-empty
expr = re_cond.sub(replc, meth[1:])
app('p(%r) if (%s) else ""' % (var, expr))
else:
call = '%s%s' % (var, meth)
add_dvar(call)
app(call)
else:
add_dvar(var)
app("p('%s')" % var)
if parm:
parm = "%% (%s) " % (',\n\t\t'.join(parm))
else:
parm = ''
c = COMPILE_TEMPLATE_SHELL % (line, parm)
Logs.debug('action: %s', c.strip().splitlines())
return (funex(c), dvars)
reg_act_noshell = re.compile(r"(?P<space>\s+)|(?P<subst>\$\{(?P<var>\w+)(?P<code>.*?)\})|(?P<text>([^$ \t\n\r\f\v]|\$\$)+)", re.M)
def compile_fun_noshell(line):
"""
Creates a compiled function to execute a process without a sub-shell
"""
buf = []
dvars = []
merge = False
app = buf.append
def add_dvar(x):
if x not in dvars:
dvars.append(x)
def replc(m):
# performs substitutions and populates dvars
if m.group('and'):
return ' and '
elif m.group('or'):
return ' or '
else:
x = m.group('var')
add_dvar(x)
return 'env[%r]' % x
for m in reg_act_noshell.finditer(line):
if m.group('space'):
merge = False
continue
elif m.group('text'):
app('[%r]' % m.group('text').replace('$$', '$'))
elif m.group('subst'):
var = m.group('var')
code = m.group('code')
if var == 'SRC':
if code:
app('[tsk.inputs%s]' % code)
else:
app('[a.path_from(cwdx) for a in tsk.inputs]')
elif var == 'TGT':
if code:
app('[tsk.outputs%s]' % code)
else:
app('[a.path_from(cwdx) for a in tsk.outputs]')
elif code:
if code.startswith(':'):
# a composed variable ${FOO:OUT}
add_dvar(var)
m = code[1:]
if m == 'SRC':
m = '[a.path_from(cwdx) for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.path_from(cwdx) for a in tsk.outputs]'
elif re_novar.match(m):
m = '[tsk.inputs%s]' % m[3:]
elif re_novar.match(m):
m = '[tsk.outputs%s]' % m[3:]
else:
add_dvar(m)
if m[:3] not in ('tsk', 'gen', 'bld'):
m = '%r' % m
app('tsk.colon(%r, %s)' % (var, m))
elif code.startswith('?'):
# In A?B|C output env.A if one of env.B or env.C is non-empty
expr = re_cond.sub(replc, code[1:])
app('to_list(env[%r] if (%s) else [])' % (var, expr))
else:
# plain code such as ${tsk.inputs[0].abspath()}
call = '%s%s' % (var, code)
add_dvar(call)
app('to_list(%s)' % call)
else:
# a plain variable such as # a plain variable like ${AR}
app('to_list(env[%r])' % var)
add_dvar(var)
if merge:
tmp = 'merge(%s, %s)' % (buf[-2], buf[-1])
del buf[-1]
buf[-1] = tmp
merge = True # next turn
buf = ['lst.extend(%s)' % x for x in buf]
fun = COMPILE_TEMPLATE_NOSHELL % "\n\t".join(buf)
Logs.debug('action: %s', fun.strip().splitlines())
return (funex(fun), dvars)
def compile_fun(line, shell=False):
"""
Parses a string expression such as '${CC} ${SRC} -o ${TGT}' and returns a pair containing:
* The function created (compiled) for use as :py:meth:`waflib.Task.Task.run`
* The list of variables that must cause rebuilds when *env* data is modified
for example::
from waflib.Task import compile_fun
compile_fun('cxx', '${CXX} -o ${TGT[0]} ${SRC} -I ${SRC[0].parent.bldpath()}')
def build(bld):
bld(source='wscript', rule='echo "foo\\${SRC[0].name}\\bar"')
The env variables (CXX, ..) on the task must not hold dicts so as to preserve a consistent order.
The reserved keywords ``TGT`` and ``SRC`` represent the task input and output nodes
"""
if isinstance(line, str):
if line.find('<') > 0 or line.find('>') > 0 or line.find('&&') > 0:
shell = True
else:
dvars_lst = []
funs_lst = []
for x in line:
if isinstance(x, str):
fun, dvars = compile_fun(x, shell)
dvars_lst += dvars
funs_lst.append(fun)
else:
# assume a function to let through
funs_lst.append(x)
def composed_fun(task):
for x in funs_lst:
ret = x(task)
if ret:
return ret
return None
return composed_fun, dvars_lst
if shell:
return compile_fun_shell(line)
else:
return compile_fun_noshell(line)
def compile_sig_vars(vars):
"""
This method produces a sig_vars method suitable for subclasses that provide
scriptlet code in their run_str code.
If no such method can be created, this method returns None.
The purpose of the sig_vars method returned is to ensures
that rebuilds occur whenever the contents of the expression changes.
This is the case B below::
import time
# case A: regular variables
tg = bld(rule='echo ${FOO}')
tg.env.FOO = '%s' % time.time()
# case B
bld(rule='echo ${gen.foo}', foo='%s' % time.time())
:param vars: env variables such as CXXFLAGS or gen.foo
:type vars: list of string
:return: A sig_vars method relevant for dependencies if adequate, else None
:rtype: A function, or None in most cases
"""
buf = []
for x in sorted(vars):
if x[:3] in ('tsk', 'gen', 'bld'):
buf.append('buf.append(%s)' % x)
if buf:
return funex(COMPILE_TEMPLATE_SIG_VARS % '\n\t'.join(buf))
return None
def task_factory(name, func=None, vars=None, color='GREEN', ext_in=[], ext_out=[], before=[], after=[], shell=False, scan=None):
"""
Returns a new task subclass with the function ``run`` compiled from the line given.
:param func: method run
:type func: string or function
:param vars: list of variables to hash
:type vars: list of string
:param color: color to use
:type color: string
:param shell: when *func* is a string, enable/disable the use of the shell
:type shell: bool
:param scan: method scan
:type scan: function
:rtype: :py:class:`waflib.Task.Task`
"""
params = {
'vars': vars or [], # function arguments are static, and this one may be modified by the class
'color': color,
'name': name,
'shell': shell,
'scan': scan,
}
if isinstance(func, str) or isinstance(func, tuple):
params['run_str'] = func
else:
params['run'] = func
cls = type(Task)(name, (Task,), params)
classes[name] = cls
if ext_in:
cls.ext_in = Utils.to_list(ext_in)
if ext_out:
cls.ext_out = Utils.to_list(ext_out)
if before:
cls.before = Utils.to_list(before)
if after:
cls.after = Utils.to_list(after)
return cls
def deep_inputs(cls):
"""
Task class decorator to enable rebuilds on input files task signatures
"""
def sig_explicit_deps(self):
Task.sig_explicit_deps(self)
Task.sig_deep_inputs(self)
cls.sig_explicit_deps = sig_explicit_deps
return cls
TaskBase = Task
"Provided for compatibility reasons, TaskBase should not be used"
class TaskSemaphore(object):
"""
Task semaphores provide a simple and efficient way of throttling the amount of
a particular task to run concurrently. The throttling value is capped
by the amount of maximum jobs, so for example, a `TaskSemaphore(10)`
has no effect in a `-j2` build.
Task semaphores are typically specified on the task class level::
class compile(waflib.Task.Task):
semaphore = waflib.Task.TaskSemaphore(2)
run_str = 'touch ${TGT}'
Task semaphores are meant to be used by the build scheduler in the main
thread, so there are no guarantees of thread safety.
"""
def __init__(self, num):
"""
:param num: maximum value of concurrent tasks
:type num: int
"""
self.num = num
self.locking = set()
self.waiting = set()
def is_locked(self):
"""Returns True if this semaphore cannot be acquired by more tasks"""
return len(self.locking) >= self.num
def acquire(self, tsk):
"""
Mark the semaphore as used by the given task (not re-entrant).
:param tsk: task object
:type tsk: :py:class:`waflib.Task.Task`
:raises: :py:class:`IndexError` in case the resource is already acquired
"""
if self.is_locked():
raise IndexError('Cannot lock more %r' % self.locking)
self.locking.add(tsk)
def release(self, tsk):
"""
Mark the semaphore as unused by the given task.
:param tsk: task object
:type tsk: :py:class:`waflib.Task.Task`
:raises: :py:class:`KeyError` in case the resource is not acquired by the task
"""
self.locking.remove(tsk)
| 39,486 | Python | .py | 1,195 | 29.598326 | 130 | 0.673766 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,581 | Utils.py | projecthamster_hamster/waflib/Utils.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Utilities and platform-specific fixes
The portability fixes try to provide a consistent behavior of the Waf API
through Python versions 2.5 to 3.X and across different platforms (win32, linux, etc)
"""
from __future__ import with_statement
import atexit, os, sys, errno, inspect, re, datetime, platform, base64, signal, functools, time, shlex
try:
import cPickle
except ImportError:
import pickle as cPickle
# leave this
if os.name == 'posix' and sys.version_info[0] < 3:
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
else:
import subprocess
try:
TimeoutExpired = subprocess.TimeoutExpired
except AttributeError:
class TimeoutExpired(Exception):
pass
from collections import deque, defaultdict
try:
import _winreg as winreg
except ImportError:
try:
import winreg
except ImportError:
winreg = None
from waflib import Errors
try:
from hashlib import md5
except ImportError:
try:
from hashlib import sha1 as md5
except ImportError:
# never fail to enable potential fixes from another module
pass
else:
try:
md5().digest()
except ValueError:
# Fips? #2213
from hashlib import sha1 as md5
try:
import threading
except ImportError:
if not 'JOBS' in os.environ:
# no threading :-(
os.environ['JOBS'] = '1'
class threading(object):
"""
A fake threading class for platforms lacking the threading module.
Use ``waf -j1`` on those platforms
"""
pass
class Lock(object):
"""Fake Lock class"""
def acquire(self):
pass
def release(self):
pass
threading.Lock = threading.Thread = Lock
SIG_NIL = 'SIG_NIL_SIG_NIL_'.encode()
"""Arbitrary null value for hashes. Modify this value according to the hash function in use"""
O644 = 420
"""Constant representing the permissions for regular files (0644 raises a syntax error on python 3)"""
O755 = 493
"""Constant representing the permissions for executable files (0755 raises a syntax error on python 3)"""
rot_chr = ['\\', '|', '/', '-']
"List of characters to use when displaying the throbber (progress bar)"
rot_idx = 0
"Index of the current throbber character (progress bar)"
class ordered_iter_dict(dict):
"""Ordered dictionary that provides iteration from the most recently inserted keys first"""
def __init__(self, *k, **kw):
self.lst = deque()
dict.__init__(self, *k, **kw)
def clear(self):
dict.clear(self)
self.lst = deque()
def __setitem__(self, key, value):
if key in dict.keys(self):
self.lst.remove(key)
dict.__setitem__(self, key, value)
self.lst.append(key)
def __delitem__(self, key):
dict.__delitem__(self, key)
try:
self.lst.remove(key)
except ValueError:
pass
def __iter__(self):
return reversed(self.lst)
def keys(self):
return reversed(self.lst)
class lru_node(object):
"""
Used by :py:class:`waflib.Utils.lru_cache`
"""
__slots__ = ('next', 'prev', 'key', 'val')
def __init__(self):
self.next = self
self.prev = self
self.key = None
self.val = None
class lru_cache(object):
"""
A simple least-recently used cache with lazy allocation
"""
__slots__ = ('maxlen', 'table', 'head')
def __init__(self, maxlen=100):
self.maxlen = maxlen
"""
Maximum amount of elements in the cache
"""
self.table = {}
"""
Mapping key-value
"""
self.head = lru_node()
self.head.next = self.head
self.head.prev = self.head
def __getitem__(self, key):
node = self.table[key]
# assert(key==node.key)
if node is self.head:
return node.val
# detach the node found
node.prev.next = node.next
node.next.prev = node.prev
# replace the head
node.next = self.head.next
node.prev = self.head
self.head = node.next.prev = node.prev.next = node
return node.val
def __setitem__(self, key, val):
if key in self.table:
# update the value for an existing key
node = self.table[key]
node.val = val
self.__getitem__(key)
else:
if len(self.table) < self.maxlen:
# the very first item is unused until the maximum is reached
node = lru_node()
node.prev = self.head
node.next = self.head.next
node.prev.next = node.next.prev = node
else:
node = self.head = self.head.next
try:
# that's another key
del self.table[node.key]
except KeyError:
pass
node.key = key
node.val = val
self.table[key] = node
class lazy_generator(object):
def __init__(self, fun, params):
self.fun = fun
self.params = params
def __iter__(self):
return self
def __next__(self):
try:
it = self.it
except AttributeError:
it = self.it = self.fun(*self.params)
return next(it)
next = __next__
is_win32 = os.sep == '\\' or sys.platform == 'win32' or os.name == 'nt' # msys2
"""
Whether this system is a Windows series
"""
def readf(fname, m='r', encoding='latin-1'):
"""
Reads an entire file into a string. See also :py:meth:`waflib.Node.Node.readf`::
def build(ctx):
from waflib import Utils
txt = Utils.readf(self.path.find_node('wscript').abspath())
txt = ctx.path.find_node('wscript').read()
:type fname: string
:param fname: Path to file
:type m: string
:param m: Open mode
:type encoding: string
:param encoding: encoding value, only used for python 3
:rtype: string
:return: Content of the file
"""
if sys.hexversion > 0x3000000 and not 'b' in m:
m += 'b'
with open(fname, m) as f:
txt = f.read()
if encoding:
txt = txt.decode(encoding)
else:
txt = txt.decode()
else:
with open(fname, m) as f:
txt = f.read()
return txt
def writef(fname, data, m='w', encoding='latin-1'):
"""
Writes an entire file from a string.
See also :py:meth:`waflib.Node.Node.writef`::
def build(ctx):
from waflib import Utils
txt = Utils.writef(self.path.make_node('i_like_kittens').abspath(), 'some data')
self.path.make_node('i_like_kittens').write('some data')
:type fname: string
:param fname: Path to file
:type data: string
:param data: The contents to write to the file
:type m: string
:param m: Open mode
:type encoding: string
:param encoding: encoding value, only used for python 3
"""
if sys.hexversion > 0x3000000 and not 'b' in m:
data = data.encode(encoding)
m += 'b'
with open(fname, m) as f:
f.write(data)
def h_file(fname):
"""
Computes a hash value for a file by using md5. Use the md5_tstamp
extension to get faster build hashes if necessary.
:type fname: string
:param fname: path to the file to hash
:return: hash of the file contents
:rtype: string or bytes
"""
m = md5()
with open(fname, 'rb') as f:
while fname:
fname = f.read(200000)
m.update(fname)
return m.digest()
def readf_win32(f, m='r', encoding='latin-1'):
flags = os.O_NOINHERIT | os.O_RDONLY
if 'b' in m:
flags |= os.O_BINARY
if '+' in m:
flags |= os.O_RDWR
try:
fd = os.open(f, flags)
except OSError:
raise IOError('Cannot read from %r' % f)
if sys.hexversion > 0x3000000 and not 'b' in m:
m += 'b'
with os.fdopen(fd, m) as f:
txt = f.read()
if encoding:
txt = txt.decode(encoding)
else:
txt = txt.decode()
else:
with os.fdopen(fd, m) as f:
txt = f.read()
return txt
def writef_win32(f, data, m='w', encoding='latin-1'):
if sys.hexversion > 0x3000000 and not 'b' in m:
data = data.encode(encoding)
m += 'b'
flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | os.O_NOINHERIT
if 'b' in m:
flags |= os.O_BINARY
if '+' in m:
flags |= os.O_RDWR
try:
fd = os.open(f, flags)
except OSError:
raise OSError('Cannot write to %r' % f)
with os.fdopen(fd, m) as f:
f.write(data)
def h_file_win32(fname):
try:
fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
except OSError:
raise OSError('Cannot read from %r' % fname)
m = md5()
with os.fdopen(fd, 'rb') as f:
while fname:
fname = f.read(200000)
m.update(fname)
return m.digest()
# always save these
readf_unix = readf
writef_unix = writef
h_file_unix = h_file
if hasattr(os, 'O_NOINHERIT') and sys.hexversion < 0x3040000:
# replace the default functions
readf = readf_win32
writef = writef_win32
h_file = h_file_win32
try:
x = ''.encode('hex')
except LookupError:
import binascii
def to_hex(s):
ret = binascii.hexlify(s)
if not isinstance(ret, str):
ret = ret.decode('utf-8')
return ret
else:
def to_hex(s):
return s.encode('hex')
to_hex.__doc__ = """
Return the hexadecimal representation of a string
:param s: string to convert
:type s: string
"""
def listdir_win32(s):
"""
Lists the contents of a folder in a portable manner.
On Win32, returns the list of drive letters: ['C:', 'X:', 'Z:'] when an empty string is given.
:type s: string
:param s: a string, which can be empty on Windows
"""
if not s:
try:
import ctypes
except ImportError:
# there is nothing much we can do
return [x + ':\\' for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
else:
dlen = 4 # length of "?:\\x00"
maxdrives = 26
buf = ctypes.create_string_buffer(maxdrives * dlen)
ndrives = ctypes.windll.kernel32.GetLogicalDriveStringsA(maxdrives*dlen, ctypes.byref(buf))
return [ str(buf.raw[4*i:4*i+2].decode('ascii')) for i in range(int(ndrives/dlen)) ]
if len(s) == 2 and s[1] == ":":
s += os.sep
if not os.path.isdir(s):
e = OSError('%s is not a directory' % s)
e.errno = errno.ENOENT
raise e
return os.listdir(s)
listdir = os.listdir
if is_win32:
listdir = listdir_win32
def num2ver(ver):
"""
Converts a string, tuple or version number into an integer. The number is supposed to have at most 4 digits::
from waflib.Utils import num2ver
num2ver('1.3.2') == num2ver((1,3,2)) == num2ver((1,3,2,0))
:type ver: string or tuple of numbers
:param ver: a version number
"""
if isinstance(ver, str):
ver = tuple(ver.split('.'))
if isinstance(ver, tuple):
ret = 0
for i in range(4):
if i < len(ver):
ret += 256**(3 - i) * int(ver[i])
return ret
return ver
def to_list(val):
"""
Converts a string argument to a list by splitting it by spaces.
Returns the object if not a string::
from waflib.Utils import to_list
lst = to_list('a b c d')
:param val: list of string or space-separated string
:rtype: list
:return: Argument converted to list
"""
if isinstance(val, str):
return val.split()
else:
return val
def console_encoding():
try:
import ctypes
except ImportError:
pass
else:
try:
codepage = ctypes.windll.kernel32.GetConsoleCP()
except AttributeError:
pass
else:
if codepage:
if 65001 == codepage and sys.version_info < (3, 3):
return 'utf-8'
return 'cp%d' % codepage
return sys.stdout.encoding or ('cp1252' if is_win32 else 'latin-1')
def split_path_unix(path):
return path.split('/')
def split_path_cygwin(path):
if path.startswith('//'):
ret = path.split('/')[2:]
ret[0] = '/' + ret[0]
return ret
return path.split('/')
re_sp = re.compile('[/\\\\]+')
def split_path_win32(path):
if path.startswith('\\\\'):
ret = re_sp.split(path)[1:]
ret[0] = '\\\\' + ret[0]
if ret[0] == '\\\\?':
return ret[1:]
return ret
return re_sp.split(path)
msysroot = None
def split_path_msys(path):
if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')):
# msys paths can be in the form /usr/bin
global msysroot
if not msysroot:
# msys has python 2.7 or 3, so we can use this
msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1')
msysroot = msysroot.strip()
path = os.path.normpath(msysroot + os.sep + path)
return split_path_win32(path)
if sys.platform == 'cygwin':
split_path = split_path_cygwin
elif is_win32:
# Consider this an MSYSTEM environment if $MSYSTEM is set and python
# reports is executable from a unix like path on a windows host.
if os.environ.get('MSYSTEM') and sys.executable.startswith('/'):
split_path = split_path_msys
else:
split_path = split_path_win32
else:
split_path = split_path_unix
split_path.__doc__ = """
Splits a path by / or \\; do not confuse this function with with ``os.path.split``
:type path: string
:param path: path to split
:return: list of string
"""
def check_dir(path):
"""
Ensures that a directory exists (similar to ``mkdir -p``).
:type path: string
:param path: Path to directory
:raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
"""
if not os.path.isdir(path):
try:
os.makedirs(path)
except OSError as e:
if not os.path.isdir(path):
raise Errors.WafError('Cannot create the folder %r' % path, ex=e)
def check_exe(name, env=None):
"""
Ensures that a program exists
:type name: string
:param name: path to the program
:param env: configuration object
:type env: :py:class:`waflib.ConfigSet.ConfigSet`
:return: path of the program or None
:raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
"""
if not name:
raise ValueError('Cannot execute an empty string!')
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(name)
if fpath and is_exe(name):
return os.path.abspath(name)
else:
env = env or os.environ
for path in env['PATH'].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, name)
if is_exe(exe_file):
return os.path.abspath(exe_file)
return None
def def_attrs(cls, **kw):
"""
Sets default attributes on a class instance
:type cls: class
:param cls: the class to update the given attributes in.
:type kw: dict
:param kw: dictionary of attributes names and values.
"""
for k, v in kw.items():
if not hasattr(cls, k):
setattr(cls, k, v)
def quote_define_name(s):
"""
Converts a string into an identifier suitable for C defines.
:type s: string
:param s: String to convert
:rtype: string
:return: Identifier suitable for C defines
"""
fu = re.sub('[^a-zA-Z0-9]', '_', s)
fu = re.sub('_+', '_', fu)
fu = fu.upper()
return fu
# shlex.quote didn't exist until python 3.3. Prior to that it was a non-documented
# function in pipes.
try:
shell_quote = shlex.quote
except AttributeError:
import pipes
shell_quote = pipes.quote
def shell_escape(cmd):
"""
Escapes a command:
['ls', '-l', 'arg space'] -> ls -l 'arg space'
"""
if isinstance(cmd, str):
return cmd
return ' '.join(shell_quote(x) for x in cmd)
def h_list(lst):
"""
Hashes lists of ordered data.
Using hash(tup) for tuples would be much more efficient,
but Python now enforces hash randomization
:param lst: list to hash
:type lst: list of strings
:return: hash of the list
"""
return md5(repr(lst).encode()).digest()
if sys.hexversion < 0x3000000:
def h_list_python2(lst):
return md5(repr(lst)).digest()
h_list_python2.__doc__ = h_list.__doc__
h_list = h_list_python2
def h_fun(fun):
"""
Hash functions
:param fun: function to hash
:type fun: function
:return: hash of the function
:rtype: string or bytes
"""
try:
return fun.code
except AttributeError:
if isinstance(fun, functools.partial):
code = list(fun.args)
# The method items() provides a sequence of tuples where the first element
# represents an optional argument of the partial function application
#
# The sorting result outcome will be consistent because:
# 1. tuples are compared in order of their elements
# 2. optional argument namess are unique
code.extend(sorted(fun.keywords.items()))
code.append(h_fun(fun.func))
fun.code = h_list(code)
return fun.code
try:
h = inspect.getsource(fun)
except EnvironmentError:
h = 'nocode'
try:
fun.code = h
except AttributeError:
pass
return h
def h_cmd(ins):
"""
Hashes objects recursively
:param ins: input object
:type ins: string or list or tuple or function
:rtype: string or bytes
"""
# this function is not meant to be particularly fast
if isinstance(ins, str):
# a command is either a string
ret = ins
elif isinstance(ins, list) or isinstance(ins, tuple):
# or a list of functions/strings
ret = str([h_cmd(x) for x in ins])
else:
# or just a python function
ret = str(h_fun(ins))
if sys.hexversion > 0x3000000:
ret = ret.encode('latin-1', 'xmlcharrefreplace')
return ret
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
def subst_vars(expr, params):
"""
Replaces ${VAR} with the value of VAR taken from a dict or a config set::
from waflib import Utils
s = Utils.subst_vars('${PREFIX}/bin', env)
:type expr: string
:param expr: String to perform substitution on
:param params: Dictionary or config set to look up variable values.
"""
def repl_var(m):
if m.group(1):
return '\\'
if m.group(2):
return '$'
try:
# ConfigSet instances may contain lists
return params.get_flat(m.group(3))
except AttributeError:
return params[m.group(3)]
# if you get a TypeError, it means that 'expr' is not a string...
# Utils.subst_vars(None, env) will not work
return reg_subst.sub(repl_var, expr)
def destos_to_binfmt(key):
"""
Returns the binary format based on the unversioned platform name,
and defaults to ``elf`` if nothing is found.
:param key: platform name
:type key: string
:return: string representing the binary format
"""
if key == 'darwin':
return 'mac-o'
elif key in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
return 'elf'
def unversioned_sys_platform():
"""
Returns the unversioned platform name.
Some Python platform names contain versions, that depend on
the build environment, e.g. linux2, freebsd6, etc.
This returns the name without the version number. Exceptions are
os2 and win32, which are returned verbatim.
:rtype: string
:return: Unversioned platform name
"""
s = sys.platform
if s.startswith('java'):
# The real OS is hidden under the JVM.
from java.lang import System
s = System.getProperty('os.name')
# see http://lopica.sourceforge.net/os.html for a list of possible values
if s == 'Mac OS X':
return 'darwin'
elif s.startswith('Windows '):
return 'win32'
elif s == 'OS/2':
return 'os2'
elif s == 'HP-UX':
return 'hp-ux'
elif s in ('SunOS', 'Solaris'):
return 'sunos'
else: s = s.lower()
# powerpc == darwin for our purposes
if s == 'powerpc':
return 'darwin'
if s == 'win32' or s == 'os2':
return s
if s == 'cli' and os.name == 'nt':
# ironpython is only on windows as far as we know
return 'win32'
return re.split(r'\d+$', s)[0]
def nada(*k, **kw):
"""
Does nothing
:return: None
"""
pass
class Timer(object):
"""
Simple object for timing the execution of commands.
Its string representation is the duration::
from waflib.Utils import Timer
timer = Timer()
a_few_operations()
s = str(timer)
"""
def __init__(self):
self.start_time = self.now()
def __str__(self):
delta = self.now() - self.start_time
if not isinstance(delta, datetime.timedelta):
delta = datetime.timedelta(seconds=delta)
days = delta.days
hours, rem = divmod(delta.seconds, 3600)
minutes, seconds = divmod(rem, 60)
seconds += delta.microseconds * 1e-6
result = ''
if days:
result += '%dd' % days
if days or hours:
result += '%dh' % hours
if days or hours or minutes:
result += '%dm' % minutes
return '%s%.3fs' % (result, seconds)
def now(self):
return datetime.datetime.utcnow()
if hasattr(time, 'perf_counter'):
def now(self):
return time.perf_counter()
def read_la_file(path):
"""
Reads property files, used by msvc.py
:param path: file to read
:type path: string
"""
sp = re.compile(r'^([^=]+)=\'(.*)\'$')
dc = {}
for line in readf(path).splitlines():
try:
_, left, right, _ = sp.split(line.strip())
dc[left] = right
except ValueError:
pass
return dc
def run_once(fun):
"""
Decorator: let a function cache its results, use like this::
@run_once
def foo(k):
return 345*2343
.. note:: in practice this can cause memory leaks, prefer a :py:class:`waflib.Utils.lru_cache`
:param fun: function to execute
:type fun: function
:return: the return value of the function executed
"""
cache = {}
def wrap(*k):
try:
return cache[k]
except KeyError:
ret = fun(*k)
cache[k] = ret
return ret
wrap.__cache__ = cache
wrap.__name__ = fun.__name__
return wrap
def get_registry_app_path(key, filename):
"""
Returns the value of a registry key for an executable
:type key: string
:type filename: list of string
"""
if not winreg:
return None
try:
result = winreg.QueryValue(key, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s.exe" % filename[0])
except OSError:
pass
else:
if os.path.isfile(result):
return result
def lib64():
"""
Guess the default ``/usr/lib`` extension for 64-bit applications
:return: '64' or ''
:rtype: string
"""
# default settings for /usr/lib
if os.sep == '/':
if platform.architecture()[0] == '64bit':
if os.path.exists('/usr/lib64') and not os.path.exists('/usr/lib32'):
return '64'
return ''
def loose_version(ver_str):
# private for the time being!
# see #2402
lst = re.split(r'([.]|\\d+|[a-zA-Z])', ver_str)
ver = []
for i, val in enumerate(lst):
try:
ver.append(int(val))
except ValueError:
if val != '.':
ver.append(val)
return ver
def sane_path(p):
# private function for the time being!
return os.path.abspath(os.path.expanduser(p))
process_pool = []
"""
List of processes started to execute sub-process commands
"""
def get_process():
"""
Returns a process object that can execute commands as sub-processes
:rtype: subprocess.Popen
"""
try:
return process_pool.pop()
except IndexError:
filepath = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'processor.py'
cmd = [sys.executable, '-c', readf(filepath)]
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0, close_fds=not is_win32)
def run_prefork_process(cmd, kwargs, cargs):
"""
Delegates process execution to a pre-forked process instance.
"""
if not kwargs.get('env'):
kwargs['env'] = dict(os.environ)
try:
obj = base64.b64encode(cPickle.dumps([cmd, kwargs, cargs]))
except (TypeError, AttributeError):
return run_regular_process(cmd, kwargs, cargs)
proc = get_process()
if not proc:
return run_regular_process(cmd, kwargs, cargs)
proc.stdin.write(obj)
proc.stdin.write('\n'.encode())
proc.stdin.flush()
obj = proc.stdout.readline()
if not obj:
raise OSError('Preforked sub-process %r died' % proc.pid)
process_pool.append(proc)
lst = cPickle.loads(base64.b64decode(obj))
# Jython wrapper failures (bash/execvp)
assert len(lst) == 5
ret, out, err, ex, trace = lst
if ex:
if ex == 'OSError':
raise OSError(trace)
elif ex == 'ValueError':
raise ValueError(trace)
elif ex == 'TimeoutExpired':
exc = TimeoutExpired(cmd, timeout=cargs['timeout'], output=out)
exc.stderr = err
raise exc
else:
raise Exception(trace)
return ret, out, err
def lchown(path, user=-1, group=-1):
"""
Change the owner/group of a path, raises an OSError if the
ownership change fails.
:param user: user to change
:type user: int or str
:param group: group to change
:type group: int or str
"""
if isinstance(user, str):
import pwd
entry = pwd.getpwnam(user)
if not entry:
raise OSError('Unknown user %r' % user)
user = entry[2]
if isinstance(group, str):
import grp
entry = grp.getgrnam(group)
if not entry:
raise OSError('Unknown group %r' % group)
group = entry[2]
return os.lchown(path, user, group)
def run_regular_process(cmd, kwargs, cargs={}):
"""
Executes a subprocess command by using subprocess.Popen
"""
proc = subprocess.Popen(cmd, **kwargs)
if kwargs.get('stdout') or kwargs.get('stderr'):
try:
out, err = proc.communicate(**cargs)
except TimeoutExpired:
if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
os.killpg(proc.pid, signal.SIGKILL)
else:
proc.kill()
out, err = proc.communicate()
exc = TimeoutExpired(proc.args, timeout=cargs['timeout'], output=out)
exc.stderr = err
raise exc
status = proc.returncode
else:
out, err = (None, None)
try:
status = proc.wait(**cargs)
except TimeoutExpired as e:
if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
os.killpg(proc.pid, signal.SIGKILL)
else:
proc.kill()
proc.wait()
raise e
return status, out, err
def run_process(cmd, kwargs, cargs={}):
"""
Executes a subprocess by using a pre-forked process when possible
or falling back to subprocess.Popen. See :py:func:`waflib.Utils.run_prefork_process`
and :py:func:`waflib.Utils.run_regular_process`
"""
if kwargs.get('stdout') and kwargs.get('stderr'):
return run_prefork_process(cmd, kwargs, cargs)
else:
return run_regular_process(cmd, kwargs, cargs)
def alloc_process_pool(n, force=False):
"""
Allocates an amount of processes to the default pool so its size is at least *n*.
It is useful to call this function early so that the pre-forked
processes use as little memory as possible.
:param n: pool size
:type n: integer
:param force: if True then *n* more processes are added to the existing pool
:type force: bool
"""
# mandatory on python2, unnecessary on python >= 3.2
global run_process, get_process, alloc_process_pool
if not force:
n = max(n - len(process_pool), 0)
try:
lst = [get_process() for x in range(n)]
except OSError:
run_process = run_regular_process
get_process = alloc_process_pool = nada
else:
for x in lst:
process_pool.append(x)
def atexit_pool():
for k in process_pool:
try:
os.kill(k.pid, 9)
except OSError:
pass
else:
k.wait()
# see #1889
if (sys.hexversion<0x207000f and not is_win32) or sys.hexversion>=0x306000f:
atexit.register(atexit_pool)
if os.environ.get('WAF_NO_PREFORK') or sys.platform == 'cli' or not sys.executable:
run_process = run_regular_process
get_process = alloc_process_pool = nada
| 25,802 | Python | .py | 923 | 25.326111 | 114 | 0.697442 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,582 | processor.py | projecthamster_hamster/waflib/processor.py | #! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2016-2018 (ita)
import os, sys, traceback, base64, signal
try:
import cPickle
except ImportError:
import pickle as cPickle
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
try:
TimeoutExpired = subprocess.TimeoutExpired
except AttributeError:
class TimeoutExpired(Exception):
pass
def run():
txt = sys.stdin.readline().strip()
if not txt:
# parent process probably ended
sys.exit(1)
[cmd, kwargs, cargs] = cPickle.loads(base64.b64decode(txt))
cargs = cargs or {}
if not 'close_fds' in kwargs:
# workers have no fds
kwargs['close_fds'] = False
ret = 1
out, err, ex, trace = (None, None, None, None)
try:
proc = subprocess.Popen(cmd, **kwargs)
try:
out, err = proc.communicate(**cargs)
except TimeoutExpired:
if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
os.killpg(proc.pid, signal.SIGKILL)
else:
proc.kill()
out, err = proc.communicate()
exc = TimeoutExpired(proc.args, timeout=cargs['timeout'], output=out)
exc.stderr = err
raise exc
ret = proc.returncode
except Exception as e:
exc_type, exc_value, tb = sys.exc_info()
exc_lines = traceback.format_exception(exc_type, exc_value, tb)
trace = str(cmd) + '\n' + ''.join(exc_lines)
ex = e.__class__.__name__
# it is just text so maybe we do not need to pickle()
tmp = [ret, out, err, ex, trace]
obj = base64.b64encode(cPickle.dumps(tmp))
sys.stdout.write(obj.decode())
sys.stdout.write('\n')
sys.stdout.flush()
while 1:
try:
run()
except KeyboardInterrupt:
break
| 1,601 | Python | .py | 59 | 24.59322 | 72 | 0.71559 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,583 | eclipse.py | projecthamster_hamster/waflib/extras/eclipse.py | #! /usr/bin/env python
# encoding: utf-8
# Eclipse CDT 5.0 generator for Waf
# Richard Quirk 2009-1011 (New BSD License)
# Thomas Nagy 2011 (ported to Waf 1.6)
"""
Usage:
def options(opt):
opt.load('eclipse')
To add additional targets beside standard ones (configure, dist, install, check)
the environment ECLIPSE_EXTRA_TARGETS can be set (ie. to ['test', 'lint', 'docs'])
$ waf configure eclipse
"""
import sys, os
from waflib import Utils, Logs, Context, Build, TaskGen, Scripting, Errors, Node
from xml.dom.minidom import Document
STANDARD_INCLUDES = [ '/usr/local/include', '/usr/include' ]
oe_cdt = 'org.eclipse.cdt'
cdt_mk = oe_cdt + '.make.core'
cdt_core = oe_cdt + '.core'
cdt_bld = oe_cdt + '.build.core'
extbuilder_dir = '.externalToolBuilders'
extbuilder_name = 'Waf_Builder.launch'
settings_dir = '.settings'
settings_name = 'language.settings.xml'
class eclipse(Build.BuildContext):
cmd = 'eclipse'
fun = Scripting.default_cmd
def execute(self):
"""
Entry point
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
appname = getattr(Context.g_module, Context.APPNAME, os.path.basename(self.srcnode.abspath()))
self.create_cproject(appname, pythonpath=self.env['ECLIPSE_PYTHON_PATH'])
# Helper to dump the XML document content to XML with UTF-8 encoding
def write_conf_to_xml(self, filename, document):
self.srcnode.make_node(filename).write(document.toprettyxml(encoding='UTF-8'), flags='wb')
def create_cproject(self, appname, workspace_includes=[], pythonpath=[]):
"""
Create the Eclipse CDT .project and .cproject files
@param appname The name that will appear in the Project Explorer
@param build The BuildContext object to extract includes from
@param workspace_includes Optional project includes to prevent
"Unresolved Inclusion" errors in the Eclipse editor
@param pythonpath Optional project specific python paths
"""
hasc = hasjava = haspython = False
source_dirs = []
cpppath = self.env['CPPPATH']
javasrcpath = []
javalibpath = []
includes = STANDARD_INCLUDES
if sys.platform != 'win32':
cc = self.env.CC or self.env.CXX
if cc:
cmd = cc + ['-xc++', '-E', '-Wp,-v', '-']
try:
gccout = self.cmd_and_log(cmd, output=Context.STDERR, quiet=Context.BOTH, input='\n'.encode()).splitlines()
except Errors.WafError:
pass
else:
includes = []
for ipath in gccout:
if ipath.startswith(' /'):
includes.append(ipath[1:])
cpppath += includes
Logs.warn('Generating Eclipse CDT project files')
for g in self.groups:
for tg in g:
if not isinstance(tg, TaskGen.task_gen):
continue
tg.post()
# Add local Python modules paths to configuration so object resolving will work in IDE
# This may also contain generated files (ie. pyqt5 or protoc) that get picked from build
if 'py' in tg.features:
pypath = tg.path.relpath()
py_installfrom = getattr(tg, 'install_from', None)
if isinstance(py_installfrom, Node.Node):
pypath = py_installfrom.path_from(self.root.make_node(self.top_dir))
if pypath not in pythonpath:
pythonpath.append(pypath)
haspython = True
# Add Java source directories so object resolving works in IDE
# This may also contain generated files (ie. protoc) that get picked from build
if 'javac' in tg.features:
java_src = tg.path.relpath()
java_srcdir = getattr(tg.javac_task, 'srcdir', None)
if java_srcdir:
if isinstance(java_srcdir, Node.Node):
java_srcdir = [java_srcdir]
for x in Utils.to_list(java_srcdir):
x = x.path_from(self.root.make_node(self.top_dir))
if x not in javasrcpath:
javasrcpath.append(x)
else:
if java_src not in javasrcpath:
javasrcpath.append(java_src)
hasjava = True
# Check if there are external dependencies and add them as external jar so they will be resolved by Eclipse
usedlibs=getattr(tg, 'use', [])
for x in Utils.to_list(usedlibs):
for cl in Utils.to_list(tg.env['CLASSPATH_'+x]):
if cl not in javalibpath:
javalibpath.append(cl)
if not getattr(tg, 'link_task', None):
continue
features = Utils.to_list(getattr(tg, 'features', ''))
is_cc = 'c' in features or 'cxx' in features
incnodes = tg.to_incnodes(tg.to_list(getattr(tg, 'includes', [])) + tg.env['INCLUDES'])
for p in incnodes:
path = p.path_from(self.srcnode)
if (path.startswith("/")):
if path not in cpppath:
cpppath.append(path)
else:
if path not in workspace_includes:
workspace_includes.append(path)
if is_cc and path not in source_dirs:
source_dirs.append(path)
hasc = True
waf_executable = os.path.abspath(sys.argv[0])
project = self.impl_create_project(sys.executable, appname, hasc, hasjava, haspython, waf_executable)
self.write_conf_to_xml('.project', project)
if hasc:
project = self.impl_create_cproject(sys.executable, waf_executable, appname, workspace_includes, cpppath, source_dirs)
self.write_conf_to_xml('.cproject', project)
if haspython:
project = self.impl_create_pydevproject(sys.path, pythonpath)
self.write_conf_to_xml('.pydevproject', project)
if hasjava:
project = self.impl_create_javaproject(javasrcpath, javalibpath)
self.write_conf_to_xml('.classpath', project)
# Create editor language settings to have correct standards applied in IDE, as per project configuration
try:
os.mkdir(settings_dir)
except OSError:
pass # Ignore if dir already exists
lang_settings = Document()
project = lang_settings.createElement('project')
# Language configurations for C and C++ via cdt
if hasc:
configuration = self.add(lang_settings, project, 'configuration',
{'id' : 'org.eclipse.cdt.core.default.config.1', 'name': 'Default'})
extension = self.add(lang_settings, configuration, 'extension', {'point': 'org.eclipse.cdt.core.LanguageSettingsProvider'})
provider = self.add(lang_settings, extension, 'provider',
{ 'copy-of': 'extension',
'id': 'org.eclipse.cdt.ui.UserLanguageSettingsProvider'})
provider = self.add(lang_settings, extension, 'provider-reference',
{ 'id': 'org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider',
'ref': 'shared-provider'})
provider = self.add(lang_settings, extension, 'provider-reference',
{ 'id': 'org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider',
'ref': 'shared-provider'})
# C and C++ are kept as separated providers so appropriate flags are used also in mixed projects
if self.env.CC:
provider = self.add(lang_settings, extension, 'provider',
{ 'class': 'org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector',
'console': 'false',
'id': 'org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector.1',
'keep-relative-paths' : 'false',
'name': 'CDT GCC Built-in Compiler Settings',
'parameter': '%s %s ${FLAGS} -E -P -v -dD "${INPUTS}"'%(self.env.CC[0],' '.join(self.env['CFLAGS'])),
'prefer-non-shared': 'true' })
self.add(lang_settings, provider, 'language-scope', { 'id': 'org.eclipse.cdt.core.gcc'})
if self.env.CXX:
provider = self.add(lang_settings, extension, 'provider',
{ 'class': 'org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector',
'console': 'false',
'id': 'org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector.2',
'keep-relative-paths' : 'false',
'name': 'CDT GCC Built-in Compiler Settings',
'parameter': '%s %s ${FLAGS} -E -P -v -dD "${INPUTS}"'%(self.env.CXX[0],' '.join(self.env['CXXFLAGS'])),
'prefer-non-shared': 'true' })
self.add(lang_settings, provider, 'language-scope', { 'id': 'org.eclipse.cdt.core.g++'})
lang_settings.appendChild(project)
self.write_conf_to_xml('%s%s%s'%(settings_dir, os.path.sep, settings_name), lang_settings)
def impl_create_project(self, executable, appname, hasc, hasjava, haspython, waf_executable):
doc = Document()
projectDescription = doc.createElement('projectDescription')
self.add(doc, projectDescription, 'name', appname)
self.add(doc, projectDescription, 'comment')
self.add(doc, projectDescription, 'projects')
buildSpec = self.add(doc, projectDescription, 'buildSpec')
buildCommand = self.add(doc, buildSpec, 'buildCommand')
self.add(doc, buildCommand, 'triggers', 'clean,full,incremental,')
arguments = self.add(doc, buildCommand, 'arguments')
dictionaries = {}
# If CDT is present, instruct this one to call waf as it is more flexible (separate build/clean ...)
if hasc:
self.add(doc, buildCommand, 'name', oe_cdt + '.managedbuilder.core.genmakebuilder')
# the default make-style targets are overwritten by the .cproject values
dictionaries = {
cdt_mk + '.contents': cdt_mk + '.activeConfigSettings',
cdt_mk + '.enableAutoBuild': 'false',
cdt_mk + '.enableCleanBuild': 'true',
cdt_mk + '.enableFullBuild': 'true',
}
else:
# Otherwise for Java/Python an external builder tool is created that will call waf build
self.add(doc, buildCommand, 'name', 'org.eclipse.ui.externaltools.ExternalToolBuilder')
dictionaries = {
'LaunchConfigHandle': '<project>/%s/%s'%(extbuilder_dir, extbuilder_name),
}
# The definition is in a separate directory XML file
try:
os.mkdir(extbuilder_dir)
except OSError:
pass # Ignore error if already exists
# Populate here the external builder XML calling waf
builder = Document()
launchConfiguration = doc.createElement('launchConfiguration')
launchConfiguration.setAttribute('type', 'org.eclipse.ui.externaltools.ProgramBuilderLaunchConfigurationType')
self.add(doc, launchConfiguration, 'booleanAttribute', {'key': 'org.eclipse.debug.ui.ATTR_LAUNCH_IN_BACKGROUND', 'value': 'false'})
self.add(doc, launchConfiguration, 'booleanAttribute', {'key': 'org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED', 'value': 'true'})
self.add(doc, launchConfiguration, 'stringAttribute', {'key': 'org.eclipse.ui.externaltools.ATTR_LOCATION', 'value': waf_executable})
self.add(doc, launchConfiguration, 'stringAttribute', {'key': 'org.eclipse.ui.externaltools.ATTR_RUN_BUILD_KINDS', 'value': 'full,incremental,'})
self.add(doc, launchConfiguration, 'stringAttribute', {'key': 'org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS', 'value': 'build'})
self.add(doc, launchConfiguration, 'stringAttribute', {'key': 'org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY', 'value': '${project_loc}'})
builder.appendChild(launchConfiguration)
# And write the XML to the file references before
self.write_conf_to_xml('%s%s%s'%(extbuilder_dir, os.path.sep, extbuilder_name), builder)
for k, v in dictionaries.items():
self.addDictionary(doc, arguments, k, v)
natures = self.add(doc, projectDescription, 'natures')
if hasc:
nature_list = """
core.ccnature
managedbuilder.core.ScannerConfigNature
managedbuilder.core.managedBuildNature
core.cnature
""".split()
for n in nature_list:
self.add(doc, natures, 'nature', oe_cdt + '.' + n)
if haspython:
self.add(doc, natures, 'nature', 'org.python.pydev.pythonNature')
if hasjava:
self.add(doc, natures, 'nature', 'org.eclipse.jdt.core.javanature')
doc.appendChild(projectDescription)
return doc
def impl_create_cproject(self, executable, waf_executable, appname, workspace_includes, cpppath, source_dirs=[]):
doc = Document()
doc.appendChild(doc.createProcessingInstruction('fileVersion', '4.0.0'))
cconf_id = cdt_core + '.default.config.1'
cproject = doc.createElement('cproject')
storageModule = self.add(doc, cproject, 'storageModule',
{'moduleId': cdt_core + '.settings'})
cconf = self.add(doc, storageModule, 'cconfiguration', {'id':cconf_id})
storageModule = self.add(doc, cconf, 'storageModule',
{'buildSystemId': oe_cdt + '.managedbuilder.core.configurationDataProvider',
'id': cconf_id,
'moduleId': cdt_core + '.settings',
'name': 'Default'})
self.add(doc, storageModule, 'externalSettings')
extensions = self.add(doc, storageModule, 'extensions')
extension_list = """
VCErrorParser
MakeErrorParser
GCCErrorParser
GASErrorParser
GLDErrorParser
""".split()
self.add(doc, extensions, 'extension', {'id': cdt_core + '.ELF', 'point':cdt_core + '.BinaryParser'})
for e in extension_list:
self.add(doc, extensions, 'extension', {'id': cdt_core + '.' + e, 'point':cdt_core + '.ErrorParser'})
storageModule = self.add(doc, cconf, 'storageModule',
{'moduleId': 'cdtBuildSystem', 'version': '4.0.0'})
config = self.add(doc, storageModule, 'configuration',
{'artifactName': appname,
'id': cconf_id,
'name': 'Default',
'parent': cdt_bld + '.prefbase.cfg'})
folderInfo = self.add(doc, config, 'folderInfo',
{'id': cconf_id+'.', 'name': '/', 'resourcePath': ''})
toolChain = self.add(doc, folderInfo, 'toolChain',
{'id': cdt_bld + '.prefbase.toolchain.1',
'name': 'No ToolChain',
'resourceTypeBasedDiscovery': 'false',
'superClass': cdt_bld + '.prefbase.toolchain'})
self.add(doc, toolChain, 'targetPlatform', {'binaryParser': 'org.eclipse.cdt.core.ELF', 'id': cdt_bld + '.prefbase.toolchain.1', 'name': ''})
waf_build = '"%s" %s'%(waf_executable, eclipse.fun)
waf_clean = '"%s" clean'%(waf_executable)
self.add(doc, toolChain, 'builder',
{'autoBuildTarget': waf_build,
'command': executable,
'enableAutoBuild': 'false',
'cleanBuildTarget': waf_clean,
'enableIncrementalBuild': 'true',
'id': cdt_bld + '.settings.default.builder.1',
'incrementalBuildTarget': waf_build,
'managedBuildOn': 'false',
'name': 'Gnu Make Builder',
'superClass': cdt_bld + '.settings.default.builder'})
tool_index = 1;
for tool_name in ("Assembly", "GNU C++", "GNU C"):
tool = self.add(doc, toolChain, 'tool',
{'id': cdt_bld + '.settings.holder.' + str(tool_index),
'name': tool_name,
'superClass': cdt_bld + '.settings.holder'})
if cpppath or workspace_includes:
incpaths = cdt_bld + '.settings.holder.incpaths'
option = self.add(doc, tool, 'option',
{'id': incpaths + '.' + str(tool_index),
'name': 'Include Paths',
'superClass': incpaths,
'valueType': 'includePath'})
for i in workspace_includes:
self.add(doc, option, 'listOptionValue',
{'builtIn': 'false',
'value': '"${workspace_loc:/%s/%s}"'%(appname, i)})
for i in cpppath:
self.add(doc, option, 'listOptionValue',
{'builtIn': 'false',
'value': '"%s"'%(i)})
if tool_name == "GNU C++" or tool_name == "GNU C":
self.add(doc,tool,'inputType',{ 'id':'org.eclipse.cdt.build.core.settings.holder.inType.' + str(tool_index), \
'languageId':'org.eclipse.cdt.core.gcc' if tool_name == "GNU C" else 'org.eclipse.cdt.core.g++','languageName':tool_name, \
'sourceContentType':'org.eclipse.cdt.core.cSource,org.eclipse.cdt.core.cHeader', \
'superClass':'org.eclipse.cdt.build.core.settings.holder.inType' })
tool_index += 1
if source_dirs:
sourceEntries = self.add(doc, config, 'sourceEntries')
for i in source_dirs:
self.add(doc, sourceEntries, 'entry',
{'excluding': i,
'flags': 'VALUE_WORKSPACE_PATH|RESOLVED',
'kind': 'sourcePath',
'name': ''})
self.add(doc, sourceEntries, 'entry',
{
'flags': 'VALUE_WORKSPACE_PATH|RESOLVED',
'kind': 'sourcePath',
'name': i})
storageModule = self.add(doc, cconf, 'storageModule',
{'moduleId': cdt_mk + '.buildtargets'})
buildTargets = self.add(doc, storageModule, 'buildTargets')
def addTargetWrap(name, runAll):
return self.addTarget(doc, buildTargets, executable, name,
'"%s" %s'%(waf_executable, name), runAll)
addTargetWrap('configure', True)
addTargetWrap('dist', False)
addTargetWrap('install', False)
addTargetWrap('check', False)
for addTgt in self.env.ECLIPSE_EXTRA_TARGETS or []:
addTargetWrap(addTgt, False)
storageModule = self.add(doc, cproject, 'storageModule',
{'moduleId': 'cdtBuildSystem',
'version': '4.0.0'})
self.add(doc, storageModule, 'project', {'id': '%s.null.1'%appname, 'name': appname})
storageModule = self.add(doc, cproject, 'storageModule',
{'moduleId': 'org.eclipse.cdt.core.LanguageSettingsProviders'})
storageModule = self.add(doc, cproject, 'storageModule',
{'moduleId': 'scannerConfiguration'})
doc.appendChild(cproject)
return doc
def impl_create_pydevproject(self, system_path, user_path):
# create a pydevproject file
doc = Document()
doc.appendChild(doc.createProcessingInstruction('eclipse-pydev', 'version="1.0"'))
pydevproject = doc.createElement('pydev_project')
prop = self.add(doc, pydevproject,
'pydev_property',
'python %d.%d'%(sys.version_info[0], sys.version_info[1]))
prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_VERSION')
prop = self.add(doc, pydevproject, 'pydev_property', 'Default')
prop.setAttribute('name', 'org.python.pydev.PYTHON_PROJECT_INTERPRETER')
# add waf's paths
wafadmin = [p for p in system_path if p.find('wafadmin') != -1]
if wafadmin:
prop = self.add(doc, pydevproject, 'pydev_pathproperty',
{'name':'org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH'})
for i in wafadmin:
self.add(doc, prop, 'path', i)
if user_path:
prop = self.add(doc, pydevproject, 'pydev_pathproperty',
{'name':'org.python.pydev.PROJECT_SOURCE_PATH'})
for i in user_path:
self.add(doc, prop, 'path', '/${PROJECT_DIR_NAME}/'+i)
doc.appendChild(pydevproject)
return doc
def impl_create_javaproject(self, javasrcpath, javalibpath):
# create a .classpath file for java usage
doc = Document()
javaproject = doc.createElement('classpath')
if javasrcpath:
for i in javasrcpath:
self.add(doc, javaproject, 'classpathentry',
{'kind': 'src', 'path': i})
if javalibpath:
for i in javalibpath:
self.add(doc, javaproject, 'classpathentry',
{'kind': 'lib', 'path': i})
self.add(doc, javaproject, 'classpathentry', {'kind': 'con', 'path': 'org.eclipse.jdt.launching.JRE_CONTAINER'})
self.add(doc, javaproject, 'classpathentry', {'kind': 'output', 'path': self.bldnode.name })
doc.appendChild(javaproject)
return doc
def addDictionary(self, doc, parent, k, v):
dictionary = self.add(doc, parent, 'dictionary')
self.add(doc, dictionary, 'key', k)
self.add(doc, dictionary, 'value', v)
return dictionary
def addTarget(self, doc, buildTargets, executable, name, buildTarget, runAllBuilders=True):
target = self.add(doc, buildTargets, 'target',
{'name': name,
'path': '',
'targetID': oe_cdt + '.build.MakeTargetBuilder'})
self.add(doc, target, 'buildCommand', executable)
self.add(doc, target, 'buildArguments', None)
self.add(doc, target, 'buildTarget', buildTarget)
self.add(doc, target, 'stopOnError', 'true')
self.add(doc, target, 'useDefaultCommand', 'false')
self.add(doc, target, 'runAllBuilders', str(runAllBuilders).lower())
def add(self, doc, parent, tag, value = None):
el = doc.createElement(tag)
if (value):
if type(value) == type(str()):
el.appendChild(doc.createTextNode(value))
elif type(value) == type(dict()):
self.setAttributes(el, value)
parent.appendChild(el)
return el
def setAttributes(self, node, attrs):
for k, v in attrs.items():
node.setAttribute(k, v)
| 19,719 | Python | .py | 427 | 41.419204 | 148 | 0.690915 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,584 | pytest.py | projecthamster_hamster/waflib/extras/pytest.py | #! /usr/bin/env python
# encoding: utf-8
# Calle Rosenquist, 2016-2018 (xbreak)
"""
Provides Python unit test support using :py:class:`waflib.Tools.waf_unit_test.utest`
task via the **pytest** feature.
To use pytest the following is needed:
1. Load `pytest` and the dependency `waf_unit_test` tools.
2. Create a task generator with feature `pytest` (not `test`) and customize behaviour with
the following attributes:
- `pytest_source`: Test input files.
- `ut_str`: Test runner command, e.g. ``${PYTHON} -B -m unittest discover`` or
if nose is used: ``${NOSETESTS} --no-byte-compile ${SRC}``.
- `ut_shell`: Determines if ``ut_str`` is executed in a shell. Default: False.
- `ut_cwd`: Working directory for test runner. Defaults to directory of
first ``pytest_source`` file.
Additionally the following `pytest` specific attributes are used in dependent taskgens:
- `pytest_path`: Node or string list of additional Python paths.
- `pytest_libpath`: Node or string list of additional library paths.
The `use` dependencies are used for both update calculation and to populate
the following environment variables for the `pytest` test runner:
1. `PYTHONPATH` (`sys.path`) of any dependent taskgen that has the feature `py`:
- `install_from` attribute is used to determine where the root of the Python sources
are located. If `install_from` is not specified the default is to use the taskgen path
as the root.
- `pytest_path` attribute is used to manually specify additional Python paths.
2. Dynamic linker search path variable (e.g. `LD_LIBRARY_PATH`) of any dependent taskgen with
non-static link_task.
- `pytest_libpath` attribute is used to manually specify additional linker paths.
3. Java class search path (CLASSPATH) of any Java/Javalike dependency
Note: `pytest` cannot automatically determine the correct `PYTHONPATH` for `pyext` taskgens
because the extension might be part of a Python package or used standalone:
- When used as part of another `py` package, the `PYTHONPATH` is provided by
that taskgen so no additional action is required.
- When used as a standalone module, the user needs to specify the `PYTHONPATH` explicitly
via the `pytest_path` attribute on the `pyext` taskgen.
For details c.f. the pytest playground examples.
For example::
# A standalone Python C extension that demonstrates unit test environment population
# of PYTHONPATH and LD_LIBRARY_PATH/PATH/DYLD_LIBRARY_PATH.
#
# Note: `pytest_path` is provided here because pytest cannot automatically determine
# if the extension is part of another Python package or is used standalone.
bld(name = 'foo_ext',
features = 'c cshlib pyext',
source = 'src/foo_ext.c',
target = 'foo_ext',
pytest_path = [ bld.path.get_bld() ])
# Python package under test that also depend on the Python module `foo_ext`
#
# Note: `install_from` is added automatically to `PYTHONPATH`.
bld(name = 'foo',
features = 'py',
use = 'foo_ext',
source = bld.path.ant_glob('src/foo/*.py'),
install_from = 'src')
# Unit test example using the built in module unittest and let that discover
# any test cases.
bld(name = 'foo_test',
features = 'pytest',
use = 'foo',
pytest_source = bld.path.ant_glob('test/*.py'),
ut_str = '${PYTHON} -B -m unittest discover')
"""
import os
from waflib import Task, TaskGen, Errors, Utils, Logs
from waflib.Tools import ccroot
def _process_use_rec(self, name):
"""
Recursively process ``use`` for task generator with name ``name``..
Used by pytest_process_use.
"""
if name in self.pytest_use_not or name in self.pytest_use_seen:
return
try:
tg = self.bld.get_tgen_by_name(name)
except Errors.WafError:
self.pytest_use_not.add(name)
return
self.pytest_use_seen.append(name)
tg.post()
for n in self.to_list(getattr(tg, 'use', [])):
_process_use_rec(self, n)
@TaskGen.feature('pytest')
@TaskGen.after_method('process_source', 'apply_link')
def pytest_process_use(self):
"""
Process the ``use`` attribute which contains a list of task generator names and store
paths that later is used to populate the unit test runtime environment.
"""
self.pytest_use_not = set()
self.pytest_use_seen = []
self.pytest_paths = [] # strings or Nodes
self.pytest_libpaths = [] # strings or Nodes
self.pytest_javapaths = [] # strings or Nodes
self.pytest_dep_nodes = []
names = self.to_list(getattr(self, 'use', []))
for name in names:
_process_use_rec(self, name)
def extend_unique(lst, varlst):
ext = []
for x in varlst:
if x not in lst:
ext.append(x)
lst.extend(ext)
# Collect type specific info needed to construct a valid runtime environment
# for the test.
for name in self.pytest_use_seen:
tg = self.bld.get_tgen_by_name(name)
extend_unique(self.pytest_paths, Utils.to_list(getattr(tg, 'pytest_path', [])))
extend_unique(self.pytest_libpaths, Utils.to_list(getattr(tg, 'pytest_libpath', [])))
if 'py' in tg.features:
# Python dependencies are added to PYTHONPATH
pypath = getattr(tg, 'install_from', tg.path)
if 'buildcopy' in tg.features:
# Since buildcopy is used we assume that PYTHONPATH in build should be used,
# not source
extend_unique(self.pytest_paths, [pypath.get_bld().abspath()])
# Add buildcopy output nodes to dependencies
extend_unique(self.pytest_dep_nodes, [o for task in getattr(tg, 'tasks', []) \
for o in getattr(task, 'outputs', [])])
else:
# If buildcopy is not used, depend on sources instead
extend_unique(self.pytest_dep_nodes, tg.source)
extend_unique(self.pytest_paths, [pypath.abspath()])
if 'javac' in tg.features:
# If a JAR is generated point to that, otherwise to directory
if getattr(tg, 'jar_task', None):
extend_unique(self.pytest_javapaths, [tg.jar_task.outputs[0].abspath()])
else:
extend_unique(self.pytest_javapaths, [tg.path.get_bld()])
# And add respective dependencies if present
if tg.use_lst:
extend_unique(self.pytest_javapaths, tg.use_lst)
if getattr(tg, 'link_task', None):
# For tasks with a link_task (C, C++, D et.c.) include their library paths:
if not isinstance(tg.link_task, ccroot.stlink_task):
extend_unique(self.pytest_dep_nodes, tg.link_task.outputs)
extend_unique(self.pytest_libpaths, tg.link_task.env.LIBPATH)
if 'pyext' in tg.features:
# If the taskgen is extending Python we also want to add the interpreter libpath.
extend_unique(self.pytest_libpaths, tg.link_task.env.LIBPATH_PYEXT)
else:
# Only add to libpath if the link task is not a Python extension
extend_unique(self.pytest_libpaths, [tg.link_task.outputs[0].parent.abspath()])
@TaskGen.feature('pytest')
@TaskGen.after_method('pytest_process_use')
def make_pytest(self):
"""
Creates a ``utest`` task with a populated environment for Python if not specified in ``ut_env``:
- Paths in `pytest_paths` attribute are used to populate PYTHONPATH
- Paths in `pytest_libpaths` attribute are used to populate the system library path (e.g. LD_LIBRARY_PATH)
"""
nodes = self.to_nodes(self.pytest_source)
tsk = self.create_task('utest', nodes)
tsk.dep_nodes.extend(self.pytest_dep_nodes)
if getattr(self, 'ut_str', None):
self.ut_run, lst = Task.compile_fun(self.ut_str, shell=getattr(self, 'ut_shell', False))
tsk.vars = lst + tsk.vars
if getattr(self, 'ut_cwd', None):
if isinstance(self.ut_cwd, str):
# we want a Node instance
if os.path.isabs(self.ut_cwd):
self.ut_cwd = self.bld.root.make_node(self.ut_cwd)
else:
self.ut_cwd = self.path.make_node(self.ut_cwd)
else:
if tsk.inputs:
self.ut_cwd = tsk.inputs[0].parent
else:
raise Errors.WafError("no valid input files for pytest task, check pytest_source value")
if not self.ut_cwd.exists():
self.ut_cwd.mkdir()
if not hasattr(self, 'ut_env'):
self.ut_env = dict(os.environ)
def add_paths(var, lst):
# Add list of paths to a variable, lst can contain strings or nodes
lst = [ str(n) for n in lst ]
Logs.debug("ut: %s: Adding paths %s=%s", self, var, lst)
self.ut_env[var] = os.pathsep.join(lst) + os.pathsep + self.ut_env.get(var, '')
# Prepend dependency paths to PYTHONPATH, CLASSPATH and LD_LIBRARY_PATH
add_paths('PYTHONPATH', self.pytest_paths)
add_paths('CLASSPATH', self.pytest_javapaths)
if Utils.is_win32:
add_paths('PATH', self.pytest_libpaths)
elif Utils.unversioned_sys_platform() == 'darwin':
add_paths('DYLD_LIBRARY_PATH', self.pytest_libpaths)
add_paths('LD_LIBRARY_PATH', self.pytest_libpaths)
else:
add_paths('LD_LIBRARY_PATH', self.pytest_libpaths)
| 8,866 | Python | .py | 190 | 42.547368 | 107 | 0.702922 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,585 | cpplint.py | projecthamster_hamster/waflib/extras/cpplint.py | #! /usr/bin/env python
# encoding: utf-8
#
# written by Sylvain Rouquette, 2014
'''
This is an extra tool, not bundled with the default waf binary.
To add the cpplint tool to the waf file:
$ ./waf-light --tools=compat15,cpplint
this tool also requires cpplint for python.
If you have PIP, you can install it like this: pip install cpplint
When using this tool, the wscript will look like:
def options(opt):
opt.load('compiler_cxx cpplint')
def configure(conf):
conf.load('compiler_cxx cpplint')
# optional, you can also specify them on the command line
conf.env.CPPLINT_FILTERS = ','.join((
'-whitespace/newline', # c++11 lambda
'-readability/braces', # c++11 constructor
'-whitespace/braces', # c++11 constructor
'-build/storage_class', # c++11 for-range
'-whitespace/blank_line', # user pref
'-whitespace/labels' # user pref
))
def build(bld):
bld(features='cpplint', source='main.cpp', target='app')
# add include files, because they aren't usually built
bld(features='cpplint', source=bld.path.ant_glob('**/*.hpp'))
'''
from __future__ import absolute_import
import sys, re
import logging
from waflib import Errors, Task, TaskGen, Logs, Options, Node, Utils
critical_errors = 0
CPPLINT_FORMAT = '[CPPLINT] %(filename)s:\nline %(linenum)s, severity %(confidence)s, category: %(category)s\n%(message)s\n'
RE_EMACS = re.compile(r'(?P<filename>.*):(?P<linenum>\d+): (?P<message>.*) \[(?P<category>.*)\] \[(?P<confidence>\d+)\]')
CPPLINT_RE = {
'waf': RE_EMACS,
'emacs': RE_EMACS,
'vs7': re.compile(r'(?P<filename>.*)\((?P<linenum>\d+)\): (?P<message>.*) \[(?P<category>.*)\] \[(?P<confidence>\d+)\]'),
'eclipse': re.compile(r'(?P<filename>.*):(?P<linenum>\d+): warning: (?P<message>.*) \[(?P<category>.*)\] \[(?P<confidence>\d+)\]'),
}
CPPLINT_STR = ('${CPPLINT} '
'--verbose=${CPPLINT_LEVEL} '
'--output=${CPPLINT_OUTPUT} '
'--filter=${CPPLINT_FILTERS} '
'--root=${CPPLINT_ROOT} '
'--linelength=${CPPLINT_LINE_LENGTH} ')
def options(opt):
opt.add_option('--cpplint-filters', type='string',
default='', dest='CPPLINT_FILTERS',
help='add filters to cpplint')
opt.add_option('--cpplint-length', type='int',
default=80, dest='CPPLINT_LINE_LENGTH',
help='specify the line length (default: 80)')
opt.add_option('--cpplint-level', default=1, type='int', dest='CPPLINT_LEVEL',
help='specify the log level (default: 1)')
opt.add_option('--cpplint-break', default=5, type='int', dest='CPPLINT_BREAK',
help='break the build if error >= level (default: 5)')
opt.add_option('--cpplint-root', type='string',
default='', dest='CPPLINT_ROOT',
help='root directory used to derive header guard')
opt.add_option('--cpplint-skip', action='store_true',
default=False, dest='CPPLINT_SKIP',
help='skip cpplint during build')
opt.add_option('--cpplint-output', type='string',
default='waf', dest='CPPLINT_OUTPUT',
help='select output format (waf, emacs, vs7, eclipse)')
def configure(conf):
try:
conf.find_program('cpplint', var='CPPLINT')
except Errors.ConfigurationError:
conf.env.CPPLINT_SKIP = True
class cpplint_formatter(Logs.formatter, object):
def __init__(self, fmt):
logging.Formatter.__init__(self, CPPLINT_FORMAT)
self.fmt = fmt
def format(self, rec):
if self.fmt == 'waf':
result = CPPLINT_RE[self.fmt].match(rec.msg).groupdict()
rec.msg = CPPLINT_FORMAT % result
if rec.levelno <= logging.INFO:
rec.c1 = Logs.colors.CYAN
return super(cpplint_formatter, self).format(rec)
class cpplint_handler(Logs.log_handler, object):
def __init__(self, stream=sys.stderr, **kw):
super(cpplint_handler, self).__init__(stream, **kw)
self.stream = stream
def emit(self, rec):
rec.stream = self.stream
self.emit_override(rec)
self.flush()
class cpplint_wrapper(object):
def __init__(self, logger, threshold, fmt):
self.logger = logger
self.threshold = threshold
self.fmt = fmt
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if isinstance(exc_value, Utils.subprocess.CalledProcessError):
messages = [m for m in exc_value.output.splitlines()
if 'Done processing' not in m
and 'Total errors found' not in m]
for message in messages:
self.write(message)
return True
def write(self, message):
global critical_errors
result = CPPLINT_RE[self.fmt].match(message)
if not result:
return
level = int(result.groupdict()['confidence'])
if level >= self.threshold:
critical_errors += 1
if level <= 2:
self.logger.info(message)
elif level <= 4:
self.logger.warning(message)
else:
self.logger.error(message)
cpplint_logger = None
def get_cpplint_logger(fmt):
global cpplint_logger
if cpplint_logger:
return cpplint_logger
cpplint_logger = logging.getLogger('cpplint')
hdlr = cpplint_handler()
hdlr.setFormatter(cpplint_formatter(fmt))
cpplint_logger.addHandler(hdlr)
cpplint_logger.setLevel(logging.DEBUG)
return cpplint_logger
class cpplint(Task.Task):
color = 'PINK'
def __init__(self, *k, **kw):
super(cpplint, self).__init__(*k, **kw)
def run(self):
global critical_errors
with cpplint_wrapper(get_cpplint_logger(self.env.CPPLINT_OUTPUT), self.env.CPPLINT_BREAK, self.env.CPPLINT_OUTPUT):
params = {key: str(self.env[key]) for key in self.env if 'CPPLINT_' in key}
if params['CPPLINT_OUTPUT'] == 'waf':
params['CPPLINT_OUTPUT'] = 'emacs'
params['CPPLINT'] = self.env.get_flat('CPPLINT')
cmd = Utils.subst_vars(CPPLINT_STR, params)
env = self.env.env or None
Utils.subprocess.check_output(cmd + self.inputs[0].abspath(),
stderr=Utils.subprocess.STDOUT,
env=env, shell=True)
return critical_errors
@TaskGen.extension('.h', '.hh', '.hpp', '.hxx')
def cpplint_includes(self, node):
pass
@TaskGen.feature('cpplint')
@TaskGen.before_method('process_source')
def post_cpplint(self):
if not self.env.CPPLINT_INITIALIZED:
for key, value in Options.options.__dict__.items():
if not key.startswith('CPPLINT_') or self.env[key]:
continue
self.env[key] = value
self.env.CPPLINT_INITIALIZED = True
if self.env.CPPLINT_SKIP:
return
if not self.env.CPPLINT_OUTPUT in CPPLINT_RE:
return
for src in self.to_list(getattr(self, 'source', [])):
if isinstance(src, Node.Node):
node = src
else:
node = self.path.find_or_declare(src)
if not node:
self.bld.fatal('Could not find %r' % src)
self.create_task('cpplint', node)
| 7,522 | Python | .py | 173 | 34.450867 | 136 | 0.595515 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,586 | slow_qt4.py | projecthamster_hamster/waflib/extras/slow_qt4.py | #! /usr/bin/env python
# Thomas Nagy, 2011 (ita)
"""
Create _moc.cpp files
The builds are 30-40% faster when .moc files are included,
you should NOT use this tool. If you really
really want it:
def configure(conf):
conf.load('compiler_cxx qt4')
conf.load('slow_qt4')
See playground/slow_qt/wscript for a complete example.
"""
from waflib.TaskGen import extension
from waflib import Task
import waflib.Tools.qt4
import waflib.Tools.cxx
@extension(*waflib.Tools.qt4.EXT_QT4)
def cxx_hook(self, node):
return self.create_compiled_task('cxx_qt', node)
class cxx_qt(Task.classes['cxx']):
def runnable_status(self):
ret = Task.classes['cxx'].runnable_status(self)
if ret != Task.ASK_LATER and not getattr(self, 'moc_done', None):
try:
cache = self.generator.moc_cache
except AttributeError:
cache = self.generator.moc_cache = {}
deps = self.generator.bld.node_deps[self.uid()]
for x in [self.inputs[0]] + deps:
if x.read().find('Q_OBJECT') > 0:
# process "foo.h -> foo.moc" only if "foo.cpp" is in the sources for the current task generator
# this code will work because it is in the main thread (runnable_status)
if x.name.rfind('.') > -1: # a .h file...
name = x.name[:x.name.rfind('.')]
for tsk in self.generator.compiled_tasks:
if tsk.inputs and tsk.inputs[0].name.startswith(name):
break
else:
# no corresponding file, continue
continue
# the file foo.cpp could be compiled for a static and a shared library - hence the %number in the name
cxx_node = x.parent.get_bld().make_node(x.name.replace('.', '_') + '_%d_moc.cpp' % self.generator.idx)
if cxx_node in cache:
continue
cache[cxx_node] = self
tsk = Task.classes['moc'](env=self.env, generator=self.generator)
tsk.set_inputs(x)
tsk.set_outputs(cxx_node)
if x.name.endswith('.cpp'):
# moc is trying to be too smart but it is too dumb:
# why forcing the #include when Q_OBJECT is in the cpp file?
gen = self.generator.bld.producer
gen.outstanding.append(tsk)
gen.total += 1
self.set_run_after(tsk)
else:
cxxtsk = Task.classes['cxx'](env=self.env, generator=self.generator)
cxxtsk.set_inputs(tsk.outputs)
cxxtsk.set_outputs(cxx_node.change_ext('.o'))
cxxtsk.set_run_after(tsk)
try:
self.more_tasks.extend([tsk, cxxtsk])
except AttributeError:
self.more_tasks = [tsk, cxxtsk]
try:
link = self.generator.link_task
except AttributeError:
pass
else:
link.set_run_after(cxxtsk)
link.inputs.extend(cxxtsk.outputs)
link.inputs.sort(key=lambda x: x.abspath())
self.moc_done = True
for t in self.run_after:
if not t.hasrun:
return Task.ASK_LATER
return ret
| 2,814 | Python | .py | 77 | 31.428571 | 107 | 0.672921 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,587 | boo.py | projecthamster_hamster/waflib/extras/boo.py | #! /usr/bin/env python
# encoding: utf-8
# Yannick LM 2011
"""
Support for the boo programming language, for example::
bld(features = "boo", # necessary feature
source = "src.boo", # list of boo files
gen = "world.dll", # target
type = "library", # library/exe ("-target:xyz" flag)
name = "world" # necessary if the target is referenced by 'use'
)
"""
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, after_method, before_method, extension
@extension('.boo')
def boo_hook(self, node):
# Nothing here yet ...
# TODO filter the non-boo source files in 'apply_booc' and remove this method
pass
@feature('boo')
@before_method('process_source')
def apply_booc(self):
"""Create a booc task """
src_nodes = self.to_nodes(self.source)
out_node = self.path.find_or_declare(self.gen)
self.boo_task = self.create_task('booc', src_nodes, [out_node])
# Set variables used by the 'booc' task
self.boo_task.env.OUT = '-o:%s' % out_node.abspath()
# type is "exe" by default
type = getattr(self, "type", "exe")
self.boo_task.env.BOO_TARGET_TYPE = "-target:%s" % type
@feature('boo')
@after_method('apply_boo')
def use_boo(self):
""""
boo applications honor the **use** keyword::
"""
dep_names = self.to_list(getattr(self, 'use', []))
for dep_name in dep_names:
dep_task_gen = self.bld.get_tgen_by_name(dep_name)
if not dep_task_gen:
continue
dep_task_gen.post()
dep_task = getattr(dep_task_gen, 'boo_task', None)
if not dep_task:
# Try a cs task:
dep_task = getattr(dep_task_gen, 'cs_task', None)
if not dep_task:
# Try a link task:
dep_task = getattr(dep_task, 'link_task', None)
if not dep_task:
# Abort ...
continue
self.boo_task.set_run_after(dep_task) # order
self.boo_task.dep_nodes.extend(dep_task.outputs) # dependency
self.boo_task.env.append_value('BOO_FLAGS', '-reference:%s' % dep_task.outputs[0].abspath())
class booc(Task.Task):
"""Compiles .boo files """
color = 'YELLOW'
run_str = '${BOOC} ${BOO_FLAGS} ${BOO_TARGET_TYPE} ${OUT} ${SRC}'
@conf
def check_booc(self):
self.find_program('booc', 'BOOC')
self.env.BOO_FLAGS = ['-nologo']
def configure(self):
"""Check that booc is available """
self.check_booc()
| 2,280 | Python | .py | 68 | 31.102941 | 94 | 0.678035 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,588 | relocation.py | projecthamster_hamster/waflib/extras/relocation.py | #! /usr/bin/env python
# encoding: utf-8
"""
Waf 1.6
Try to detect if the project directory was relocated, and if it was,
change the node representing the project directory. Just call:
waf configure build
Note that if the project directory name changes, the signatures for the tasks using
files in that directory will change, causing a partial build.
"""
import os
from waflib import Build, ConfigSet, Task, Utils, Errors
from waflib.TaskGen import feature, after_method
EXTRA_LOCK = '.old_srcdir'
old1 = Build.BuildContext.store
def store(self):
old1(self)
db = os.path.join(self.variant_dir, EXTRA_LOCK)
env = ConfigSet.ConfigSet()
env.SRCDIR = self.srcnode.abspath()
env.store(db)
Build.BuildContext.store = store
old2 = Build.BuildContext.init_dirs
def init_dirs(self):
if not (os.path.isabs(self.top_dir) and os.path.isabs(self.out_dir)):
raise Errors.WafError('The project was not configured: run "waf configure" first!')
srcdir = None
db = os.path.join(self.variant_dir, EXTRA_LOCK)
env = ConfigSet.ConfigSet()
try:
env.load(db)
srcdir = env.SRCDIR
except:
pass
if srcdir:
d = self.root.find_node(srcdir)
if d and srcdir != self.top_dir and getattr(d, 'children', ''):
srcnode = self.root.make_node(self.top_dir)
print("relocating the source directory %r -> %r" % (srcdir, self.top_dir))
srcnode.children = {}
for (k, v) in d.children.items():
srcnode.children[k] = v
v.parent = srcnode
d.children = {}
old2(self)
Build.BuildContext.init_dirs = init_dirs
def uid(self):
try:
return self.uid_
except AttributeError:
# this is not a real hot zone, but we want to avoid surprises here
m = Utils.md5()
up = m.update
up(self.__class__.__name__.encode())
for x in self.inputs + self.outputs:
up(x.path_from(x.ctx.srcnode).encode())
self.uid_ = m.digest()
return self.uid_
Task.Task.uid = uid
@feature('c', 'cxx', 'd', 'go', 'asm', 'fc', 'includes')
@after_method('propagate_uselib_vars', 'process_source')
def apply_incpaths(self):
lst = self.to_incnodes(self.to_list(getattr(self, 'includes', [])) + self.env['INCLUDES'])
self.includes_nodes = lst
bld = self.bld
self.env['INCPATHS'] = [x.is_child_of(bld.srcnode) and x.path_from(bld.bldnode) or x.abspath() for x in lst]
| 2,267 | Python | .py | 66 | 31.939394 | 109 | 0.721815 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,589 | build_logs.py | projecthamster_hamster/waflib/extras/build_logs.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2013 (ita)
"""
A system for recording all outputs to a log file. Just add the following to your wscript file::
def init(ctx):
ctx.load('build_logs')
"""
import atexit, sys, time, os, shutil, threading
from waflib import ansiterm, Logs, Context
# adding the logs under the build/ directory will clash with the clean/ command
try:
up = os.path.dirname(Context.g_module.__file__)
except AttributeError:
up = '.'
LOGFILE = os.path.join(up, 'logs', time.strftime('%Y_%m_%d_%H_%M.log'))
wlock = threading.Lock()
class log_to_file(object):
def __init__(self, stream, fileobj, filename):
self.stream = stream
self.encoding = self.stream.encoding
self.fileobj = fileobj
self.filename = filename
self.is_valid = True
def replace_colors(self, data):
for x in Logs.colors_lst.values():
if isinstance(x, str):
data = data.replace(x, '')
return data
def write(self, data):
try:
wlock.acquire()
self.stream.write(data)
self.stream.flush()
if self.is_valid:
self.fileobj.write(self.replace_colors(data))
finally:
wlock.release()
def fileno(self):
return self.stream.fileno()
def flush(self):
self.stream.flush()
if self.is_valid:
self.fileobj.flush()
def isatty(self):
return self.stream.isatty()
def init(ctx):
global LOGFILE
filename = os.path.abspath(LOGFILE)
try:
os.makedirs(os.path.dirname(os.path.abspath(filename)))
except OSError:
pass
if hasattr(os, 'O_NOINHERIT'):
fd = os.open(LOGFILE, os.O_CREAT | os.O_TRUNC | os.O_WRONLY | os.O_NOINHERIT)
fileobj = os.fdopen(fd, 'w')
else:
fileobj = open(LOGFILE, 'w')
old_stderr = sys.stderr
# sys.stdout has already been replaced, so __stdout__ will be faster
#sys.stdout = log_to_file(sys.stdout, fileobj, filename)
#sys.stderr = log_to_file(sys.stderr, fileobj, filename)
def wrap(stream):
if stream.isatty():
return ansiterm.AnsiTerm(stream)
return stream
sys.stdout = log_to_file(wrap(sys.__stdout__), fileobj, filename)
sys.stderr = log_to_file(wrap(sys.__stderr__), fileobj, filename)
# now mess with the logging module...
for x in Logs.log.handlers:
try:
stream = x.stream
except AttributeError:
pass
else:
if id(stream) == id(old_stderr):
x.stream = sys.stderr
def exit_cleanup():
try:
fileobj = sys.stdout.fileobj
except AttributeError:
pass
else:
sys.stdout.is_valid = False
sys.stderr.is_valid = False
fileobj.close()
filename = sys.stdout.filename
Logs.info('Output logged to %r', filename)
# then copy the log file to "latest.log" if possible
up = os.path.dirname(os.path.abspath(filename))
try:
shutil.copy(filename, os.path.join(up, 'latest.log'))
except OSError:
# this may fail on windows due to processes spawned
pass
atexit.register(exit_cleanup)
| 2,824 | Python | .py | 96 | 26.666667 | 95 | 0.71776 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,590 | why.py | projecthamster_hamster/waflib/extras/why.py | #! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010 (ita)
"""
This tool modifies the task signature scheme to store and obtain
information about the task execution (why it must run, etc)::
def configure(conf):
conf.load('why')
After adding the tool, a full rebuild is necessary:
waf clean build --zones=task
"""
from waflib import Task, Utils, Logs, Errors
def signature(self):
# compute the result one time, and suppose the scan_signature will give the good result
try:
return self.cache_sig
except AttributeError:
pass
self.m = Utils.md5()
self.m.update(self.hcode)
id_sig = self.m.digest()
# explicit deps
self.m = Utils.md5()
self.sig_explicit_deps()
exp_sig = self.m.digest()
# env vars
self.m = Utils.md5()
self.sig_vars()
var_sig = self.m.digest()
# implicit deps / scanner results
self.m = Utils.md5()
if self.scan:
try:
self.sig_implicit_deps()
except Errors.TaskRescan:
return self.signature()
impl_sig = self.m.digest()
ret = self.cache_sig = impl_sig + id_sig + exp_sig + var_sig
return ret
Task.Task.signature = signature
old = Task.Task.runnable_status
def runnable_status(self):
ret = old(self)
if ret == Task.RUN_ME:
try:
old_sigs = self.generator.bld.task_sigs[self.uid()]
except (KeyError, AttributeError):
Logs.debug("task: task must run as no previous signature exists")
else:
new_sigs = self.cache_sig
def v(x):
return Utils.to_hex(x)
Logs.debug('Task %r', self)
msgs = ['* Implicit or scanner dependency', '* Task code', '* Source file, explicit or manual dependency', '* Configuration data variable']
tmp = 'task: -> %s: %s %s'
for x in range(len(msgs)):
l = len(Utils.SIG_NIL)
a = new_sigs[x*l : (x+1)*l]
b = old_sigs[x*l : (x+1)*l]
if (a != b):
Logs.debug(tmp, msgs[x].ljust(35), v(a), v(b))
return ret
Task.Task.runnable_status = runnable_status
| 1,891 | Python | .py | 63 | 27.269841 | 142 | 0.696084 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,591 | fast_partial.py | projecthamster_hamster/waflib/extras/fast_partial.py | #! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2017-2018 (ita)
"""
A system for fast partial rebuilds
Creating a large amount of task objects up front can take some time.
By making a few assumptions, it is possible to avoid posting creating
task objects for targets that are already up-to-date.
On a silly benchmark the gain observed for 1M tasks can be 5m->10s
for a single file change.
Usage::
def options(opt):
opt.load('fast_partial')
Assumptions:
* Start with a clean build (run "waf distclean" after enabling)
* Mostly for C/C++/Fortran targets with link tasks (object-only targets are not handled)
try it in the folder generated by utils/genbench.py
* For full project builds: no --targets and no pruning from subfolders
* The installation phase is ignored
* `use=` dependencies are specified up front even across build groups
* Task generator source files are not obtained from globs
Implementation details:
* The first layer obtains file timestamps to recalculate file hashes only
when necessary (similar to md5_tstamp); the timestamps are then stored
in a dedicated pickle file
* A second layer associates each task generator to a file set to help
detecting changes. Task generators are to create their tasks only when
the related files have been modified. A specific db file is created
to store such data (5m -> 1m10)
* A third layer binds build context proxies onto task generators, replacing
the default context. While loading data for the full build uses more memory
(4GB -> 9GB), partial builds are then much faster (1m10 -> 13s)
* A fourth layer enables a 2-level cache on file signatures to
reduce the size of the main pickle file (13s -> 10s)
"""
import os
from waflib import Build, Context, Errors, Logs, Task, TaskGen, Utils
from waflib.TaskGen import feature, after_method, taskgen_method
import waflib.Node
DONE = 0
DIRTY = 1
NEEDED = 2
SKIPPABLE = ['cshlib', 'cxxshlib', 'cstlib', 'cxxstlib', 'cprogram', 'cxxprogram']
TSTAMP_DB = '.wafpickle_tstamp_db_file'
SAVED_ATTRS = 'root node_sigs task_sigs imp_sigs raw_deps node_deps'.split()
class bld_proxy(object):
def __init__(self, bld):
object.__setattr__(self, 'bld', bld)
object.__setattr__(self, 'node_class', type('Nod3', (waflib.Node.Node,), {}))
self.node_class.__module__ = 'waflib.Node'
self.node_class.ctx = self
object.__setattr__(self, 'root', self.node_class('', None))
for x in SAVED_ATTRS:
if x != 'root':
object.__setattr__(self, x, {})
self.fix_nodes()
def __setattr__(self, name, value):
bld = object.__getattribute__(self, 'bld')
setattr(bld, name, value)
def __delattr__(self, name):
bld = object.__getattribute__(self, 'bld')
delattr(bld, name)
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
bld = object.__getattribute__(self, 'bld')
return getattr(bld, name)
def __call__(self, *k, **kw):
return self.bld(*k, **kw)
def fix_nodes(self):
for x in ('srcnode', 'path', 'bldnode'):
node = self.root.find_dir(getattr(self.bld, x).abspath())
object.__setattr__(self, x, node)
def set_key(self, store_key):
object.__setattr__(self, 'store_key', store_key)
def fix_tg_path(self, *tgs):
# changing Node objects on task generators is possible
# yet, all Node objects must belong to the same parent
for tg in tgs:
tg.path = self.root.make_node(tg.path.abspath())
def restore(self):
dbfn = os.path.join(self.variant_dir, Context.DBFILE + self.store_key)
Logs.debug('rev_use: reading %s', dbfn)
try:
data = Utils.readf(dbfn, 'rb')
except (EnvironmentError, EOFError):
# handle missing file/empty file
Logs.debug('rev_use: Could not load the build cache %s (missing)', dbfn)
else:
try:
waflib.Node.pickle_lock.acquire()
waflib.Node.Nod3 = self.node_class
try:
data = Build.cPickle.loads(data)
except Exception as e:
Logs.debug('rev_use: Could not pickle the build cache %s: %r', dbfn, e)
else:
for x in SAVED_ATTRS:
object.__setattr__(self, x, data.get(x, {}))
finally:
waflib.Node.pickle_lock.release()
self.fix_nodes()
def store(self):
data = {}
for x in Build.SAVED_ATTRS:
data[x] = getattr(self, x)
db = os.path.join(self.variant_dir, Context.DBFILE + self.store_key)
with waflib.Node.pickle_lock:
waflib.Node.Nod3 = self.node_class
try:
x = Build.cPickle.dumps(data, Build.PROTOCOL)
except Build.cPickle.PicklingError:
root = data['root']
for node_deps in data['node_deps'].values():
for idx, node in enumerate(node_deps):
# there may be more cross-context Node objects to fix,
# but this should be the main source
node_deps[idx] = root.find_node(node.abspath())
x = Build.cPickle.dumps(data, Build.PROTOCOL)
Logs.debug('rev_use: storing %s', db)
Utils.writef(db + '.tmp', x, m='wb')
try:
st = os.stat(db)
os.remove(db)
if not Utils.is_win32:
os.chown(db + '.tmp', st.st_uid, st.st_gid)
except (AttributeError, OSError):
pass
os.rename(db + '.tmp', db)
class bld(Build.BuildContext):
def __init__(self, **kw):
super(bld, self).__init__(**kw)
self.hashes_md5_tstamp = {}
def __call__(self, *k, **kw):
# this is one way of doing it, one could use a task generator method too
bld = kw['bld'] = bld_proxy(self)
ret = TaskGen.task_gen(*k, **kw)
self.task_gen_cache_names = {}
self.add_to_group(ret, group=kw.get('group'))
ret.bld = bld
bld.set_key(ret.path.abspath().replace(os.sep, '') + str(ret.idx))
return ret
def is_dirty(self):
return True
def store_tstamps(self):
# Called after a build is finished
# For each task generator, record all files involved in task objects
# optimization: done only if there was something built
do_store = False
try:
f_deps = self.f_deps
except AttributeError:
f_deps = self.f_deps = {}
self.f_tstamps = {}
allfiles = set()
for g in self.groups:
for tg in g:
try:
staleness = tg.staleness
except AttributeError:
staleness = DIRTY
if staleness != DIRTY:
# DONE case: there was nothing built
# NEEDED case: the tg was brought in because of 'use' propagation
# but nothing really changed for them, there may be incomplete
# tasks (object files) and in this case it is best to let the next build
# figure out if an input/output file changed
continue
do_cache = False
for tsk in tg.tasks:
if tsk.hasrun == Task.SUCCESS:
do_cache = True
pass
elif tsk.hasrun == Task.SKIPPED:
pass
else:
# one failed task, clear the cache for this tg
try:
del f_deps[(tg.path.abspath(), tg.idx)]
except KeyError:
pass
else:
# just store the new state because there is a change
do_store = True
# skip the rest because there is no valid cache possible
break
else:
if not do_cache:
# all skipped, but is there anything in cache?
try:
f_deps[(tg.path.abspath(), tg.idx)]
except KeyError:
# probably cleared because a wscript file changed
# store it
do_cache = True
if do_cache:
# there was a rebuild, store the data structure too
tg.bld.store()
# all tasks skipped but no cache
# or a successful task build
do_store = True
st = set()
for tsk in tg.tasks:
st.update(tsk.inputs)
st.update(self.node_deps.get(tsk.uid(), []))
# TODO do last/when loading the tgs?
lst = []
for k in ('wscript', 'wscript_build'):
n = tg.path.find_node(k)
if n:
n.get_bld_sig()
lst.append(n.abspath())
lst.extend(sorted(x.abspath() for x in st))
allfiles.update(lst)
f_deps[(tg.path.abspath(), tg.idx)] = lst
for x in allfiles:
# f_tstamps has everything, while md5_tstamp can be relatively empty on partial builds
self.f_tstamps[x] = self.hashes_md5_tstamp[x][0]
if do_store:
dbfn = os.path.join(self.variant_dir, TSTAMP_DB)
Logs.debug('rev_use: storing %s', dbfn)
dbfn_tmp = dbfn + '.tmp'
x = Build.cPickle.dumps([self.f_tstamps, f_deps], Build.PROTOCOL)
Utils.writef(dbfn_tmp, x, m='wb')
os.rename(dbfn_tmp, dbfn)
Logs.debug('rev_use: stored %s', dbfn)
def store(self):
self.store_tstamps()
if self.producer.dirty:
Build.BuildContext.store(self)
def compute_needed_tgs(self):
# assume the 'use' keys are not modified during the build phase
dbfn = os.path.join(self.variant_dir, TSTAMP_DB)
Logs.debug('rev_use: Loading %s', dbfn)
try:
data = Utils.readf(dbfn, 'rb')
except (EnvironmentError, EOFError):
Logs.debug('rev_use: Could not load the build cache %s (missing)', dbfn)
self.f_deps = {}
self.f_tstamps = {}
else:
try:
self.f_tstamps, self.f_deps = Build.cPickle.loads(data)
except Exception as e:
Logs.debug('rev_use: Could not pickle the build cache %s: %r', dbfn, e)
self.f_deps = {}
self.f_tstamps = {}
else:
Logs.debug('rev_use: Loaded %s', dbfn)
# 1. obtain task generators that contain rebuilds
# 2. obtain the 'use' graph and its dual
stales = set()
reverse_use_map = Utils.defaultdict(list)
use_map = Utils.defaultdict(list)
for g in self.groups:
for tg in g:
if tg.is_stale():
stales.add(tg)
try:
lst = tg.use = Utils.to_list(tg.use)
except AttributeError:
pass
else:
for x in lst:
try:
xtg = self.get_tgen_by_name(x)
except Errors.WafError:
pass
else:
use_map[tg].append(xtg)
reverse_use_map[xtg].append(tg)
Logs.debug('rev_use: found %r stale tgs', len(stales))
# 3. dfs to post downstream tg as stale
visited = set()
def mark_down(tg):
if tg in visited:
return
visited.add(tg)
Logs.debug('rev_use: marking down %r as stale', tg.name)
tg.staleness = DIRTY
for x in reverse_use_map[tg]:
mark_down(x)
for tg in stales:
mark_down(tg)
# 4. dfs to find ancestors tg to mark as needed
self.needed_tgs = needed_tgs = set()
def mark_needed(tg):
if tg in needed_tgs:
return
needed_tgs.add(tg)
if tg.staleness == DONE:
Logs.debug('rev_use: marking up %r as needed', tg.name)
tg.staleness = NEEDED
for x in use_map[tg]:
mark_needed(x)
for xx in visited:
mark_needed(xx)
# so we have the whole tg trees to post in the set "needed"
# load their build trees
for tg in needed_tgs:
tg.bld.restore()
tg.bld.fix_tg_path(tg)
# the stale ones should be fully build, while the needed ones
# may skip a few tasks, see create_compiled_task and apply_link_after below
Logs.debug('rev_use: amount of needed task gens: %r', len(needed_tgs))
def post_group(self):
# assumption: we can ignore the folder/subfolders cuts
def tgpost(tg):
try:
f = tg.post
except AttributeError:
pass
else:
f()
if not self.targets or self.targets == '*':
for tg in self.groups[self.current_group]:
# this can cut quite a lot of tg objects
if tg in self.needed_tgs:
tgpost(tg)
else:
# default implementation
return Build.BuildContext.post_group()
def get_build_iterator(self):
if not self.targets or self.targets == '*':
self.compute_needed_tgs()
return Build.BuildContext.get_build_iterator(self)
@taskgen_method
def is_stale(self):
# assume no globs
self.staleness = DIRTY
# 1. the case of always stale targets
if getattr(self, 'always_stale', False):
return True
# 2. check if the db file exists
db = os.path.join(self.bld.variant_dir, Context.DBFILE)
try:
dbstat = os.stat(db).st_mtime
except OSError:
Logs.debug('rev_use: must post %r because this is a clean build')
return True
# 3.a check if the configuration exists
cache_node = self.bld.bldnode.find_node('c4che/build.config.py')
if not cache_node:
return True
# 3.b check if the configuration changed
if os.stat(cache_node.abspath()).st_mtime > dbstat:
Logs.debug('rev_use: must post %r because the configuration has changed', self.name)
return True
# 3.c any tstamp data?
try:
f_deps = self.bld.f_deps
except AttributeError:
Logs.debug('rev_use: must post %r because there is no f_deps', self.name)
return True
# 4. check if this is the first build (no cache)
try:
lst = f_deps[(self.path.abspath(), self.idx)]
except KeyError:
Logs.debug('rev_use: must post %r because there it has no cached data', self.name)
return True
try:
cache = self.bld.cache_tstamp_rev_use
except AttributeError:
cache = self.bld.cache_tstamp_rev_use = {}
# 5. check the timestamp of each dependency files listed is unchanged
f_tstamps = self.bld.f_tstamps
for x in lst:
try:
old_ts = f_tstamps[x]
except KeyError:
Logs.debug('rev_use: must post %r because %r is not in cache', self.name, x)
return True
try:
try:
ts = cache[x]
except KeyError:
ts = cache[x] = os.stat(x).st_mtime
except OSError:
del f_deps[(self.path.abspath(), self.idx)]
Logs.debug('rev_use: must post %r because %r does not exist anymore', self.name, x)
return True
else:
if ts != old_ts:
Logs.debug('rev_use: must post %r because the timestamp on %r changed %r %r', self.name, x, old_ts, ts)
return True
self.staleness = DONE
return False
@taskgen_method
def create_compiled_task(self, name, node):
# skip the creation of object files
# assumption: object-only targets are not skippable
if self.staleness == NEEDED:
# only libraries/programs can skip object files
for x in SKIPPABLE:
if x in self.features:
return None
out = '%s.%d.o' % (node.name, self.idx)
task = self.create_task(name, node, node.parent.find_or_declare(out))
try:
self.compiled_tasks.append(task)
except AttributeError:
self.compiled_tasks = [task]
return task
@feature(*SKIPPABLE)
@after_method('apply_link')
def apply_link_after(self):
# cprogram/cxxprogram might be unnecessary
if self.staleness != NEEDED:
return
for tsk in self.tasks:
tsk.hasrun = Task.SKIPPED
def path_from(self, node):
# handle nodes of distinct types
if node.ctx is not self.ctx:
node = self.ctx.root.make_node(node.abspath())
return self.default_path_from(node)
waflib.Node.Node.default_path_from = waflib.Node.Node.path_from
waflib.Node.Node.path_from = path_from
def h_file(self):
# similar to md5_tstamp.py, but with 2-layer cache
# global_cache for the build context common for all task generators
# local_cache for the build context proxy (one by task generator)
#
# the global cache is not persistent
# the local cache is persistent and meant for partial builds
#
# assume all calls are made from a single thread
#
filename = self.abspath()
st = os.stat(filename)
global_cache = self.ctx.bld.hashes_md5_tstamp
local_cache = self.ctx.hashes_md5_tstamp
if filename in global_cache:
# value already calculated in this build
cval = global_cache[filename]
# the value in global cache is assumed to be calculated once
# reverifying it could cause task generators
# to get distinct tstamp values, thus missing rebuilds
local_cache[filename] = cval
return cval[1]
if filename in local_cache:
cval = local_cache[filename]
if cval[0] == st.st_mtime:
# correct value from a previous build
# put it in the global cache
global_cache[filename] = cval
return cval[1]
ret = Utils.h_file(filename)
local_cache[filename] = global_cache[filename] = (st.st_mtime, ret)
return ret
waflib.Node.Node.h_file = h_file
| 15,511 | Python | .py | 452 | 30.533186 | 107 | 0.694459 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,592 | freeimage.py | projecthamster_hamster/waflib/extras/freeimage.py | #!/usr/bin/env python
# encoding: utf-8
#
# written by Sylvain Rouquette, 2011
'''
To add the freeimage tool to the waf file:
$ ./waf-light --tools=compat15,freeimage
or, if you have waf >= 1.6.2
$ ./waf update --files=freeimage
The wscript will look like:
def options(opt):
opt.load('compiler_cxx freeimage')
def configure(conf):
conf.load('compiler_cxx freeimage')
# you can call check_freeimage with some parameters.
# It's optional on Linux, it's 'mandatory' on Windows if
# you didn't use --fi-path on the command-line
# conf.check_freeimage(path='FreeImage/Dist', fip=True)
def build(bld):
bld(source='main.cpp', target='app', use='FREEIMAGE')
'''
from waflib import Utils
from waflib.Configure import conf
def options(opt):
opt.add_option('--fi-path', type='string', default='', dest='fi_path',
help='''path to the FreeImage directory \
where the files are e.g. /FreeImage/Dist''')
opt.add_option('--fip', action='store_true', default=False, dest='fip',
help='link with FreeImagePlus')
opt.add_option('--fi-static', action='store_true',
default=False, dest='fi_static',
help="link as shared libraries")
@conf
def check_freeimage(self, path=None, fip=False):
self.start_msg('Checking FreeImage')
if not self.env['CXX']:
self.fatal('you must load compiler_cxx before loading freeimage')
prefix = self.options.fi_static and 'ST' or ''
platform = Utils.unversioned_sys_platform()
if platform == 'win32':
if not path:
self.fatal('you must specify the path to FreeImage. \
use --fi-path=/FreeImage/Dist')
else:
self.env['INCLUDES_FREEIMAGE'] = path
self.env['%sLIBPATH_FREEIMAGE' % prefix] = path
libs = ['FreeImage']
if self.options.fip:
libs.append('FreeImagePlus')
if platform == 'win32':
self.env['%sLIB_FREEIMAGE' % prefix] = libs
else:
self.env['%sLIB_FREEIMAGE' % prefix] = [i.lower() for i in libs]
self.end_msg('ok')
def configure(conf):
platform = Utils.unversioned_sys_platform()
if platform == 'win32' and not conf.options.fi_path:
return
conf.check_freeimage(conf.options.fi_path, conf.options.fip)
| 2,117 | Python | .py | 59 | 33.118644 | 72 | 0.712677 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,593 | ocaml.py | projecthamster_hamster/waflib/extras/ocaml.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"ocaml support"
import os, re
from waflib import Utils, Task
from waflib.Logs import error
from waflib.TaskGen import feature, before_method, after_method, extension
EXT_MLL = ['.mll']
EXT_MLY = ['.mly']
EXT_MLI = ['.mli']
EXT_MLC = ['.c']
EXT_ML = ['.ml']
open_re = re.compile(r'^\s*open\s+([a-zA-Z]+)(;;){0,1}$', re.M)
foo = re.compile(r"""(\(\*)|(\*\))|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^()*"'\\]*)""", re.M)
def filter_comments(txt):
meh = [0]
def repl(m):
if m.group(1):
meh[0] += 1
elif m.group(2):
meh[0] -= 1
elif not meh[0]:
return m.group()
return ''
return foo.sub(repl, txt)
def scan(self):
node = self.inputs[0]
code = filter_comments(node.read())
global open_re
names = []
import_iterator = open_re.finditer(code)
if import_iterator:
for import_match in import_iterator:
names.append(import_match.group(1))
found_lst = []
raw_lst = []
for name in names:
nd = None
for x in self.incpaths:
nd = x.find_resource(name.lower()+'.ml')
if not nd:
nd = x.find_resource(name+'.ml')
if nd:
found_lst.append(nd)
break
else:
raw_lst.append(name)
return (found_lst, raw_lst)
native_lst=['native', 'all', 'c_object']
bytecode_lst=['bytecode', 'all']
@feature('ocaml')
def init_ml(self):
Utils.def_attrs(self,
type = 'all',
incpaths_lst = [],
bld_incpaths_lst = [],
mlltasks = [],
mlytasks = [],
mlitasks = [],
native_tasks = [],
bytecode_tasks = [],
linktasks = [],
bytecode_env = None,
native_env = None,
compiled_tasks = [],
includes = '',
uselib = '',
are_deps_set = 0)
@feature('ocaml')
@after_method('init_ml')
def init_envs_ml(self):
self.islibrary = getattr(self, 'islibrary', False)
global native_lst, bytecode_lst
self.native_env = None
if self.type in native_lst:
self.native_env = self.env.derive()
if self.islibrary:
self.native_env['OCALINKFLAGS'] = '-a'
self.bytecode_env = None
if self.type in bytecode_lst:
self.bytecode_env = self.env.derive()
if self.islibrary:
self.bytecode_env['OCALINKFLAGS'] = '-a'
if self.type == 'c_object':
self.native_env.append_unique('OCALINKFLAGS_OPT', '-output-obj')
@feature('ocaml')
@before_method('apply_vars_ml')
@after_method('init_envs_ml')
def apply_incpaths_ml(self):
inc_lst = self.includes.split()
lst = self.incpaths_lst
for dir in inc_lst:
node = self.path.find_dir(dir)
if not node:
error("node not found: " + str(dir))
continue
if not node in lst:
lst.append(node)
self.bld_incpaths_lst.append(node)
# now the nodes are added to self.incpaths_lst
@feature('ocaml')
@before_method('process_source')
def apply_vars_ml(self):
for i in self.incpaths_lst:
if self.bytecode_env:
app = self.bytecode_env.append_value
app('OCAMLPATH', ['-I', i.bldpath(), '-I', i.srcpath()])
if self.native_env:
app = self.native_env.append_value
app('OCAMLPATH', ['-I', i.bldpath(), '-I', i.srcpath()])
varnames = ['INCLUDES', 'OCAMLFLAGS', 'OCALINKFLAGS', 'OCALINKFLAGS_OPT']
for name in self.uselib.split():
for vname in varnames:
cnt = self.env[vname+'_'+name]
if cnt:
if self.bytecode_env:
self.bytecode_env.append_value(vname, cnt)
if self.native_env:
self.native_env.append_value(vname, cnt)
@feature('ocaml')
@after_method('process_source')
def apply_link_ml(self):
if self.bytecode_env:
ext = self.islibrary and '.cma' or '.run'
linktask = self.create_task('ocalink')
linktask.bytecode = 1
linktask.set_outputs(self.path.find_or_declare(self.target + ext))
linktask.env = self.bytecode_env
self.linktasks.append(linktask)
if self.native_env:
if self.type == 'c_object':
ext = '.o'
elif self.islibrary:
ext = '.cmxa'
else:
ext = ''
linktask = self.create_task('ocalinkx')
linktask.set_outputs(self.path.find_or_declare(self.target + ext))
linktask.env = self.native_env
self.linktasks.append(linktask)
# we produce a .o file to be used by gcc
self.compiled_tasks.append(linktask)
@extension(*EXT_MLL)
def mll_hook(self, node):
mll_task = self.create_task('ocamllex', node, node.change_ext('.ml'))
mll_task.env = self.native_env.derive()
self.mlltasks.append(mll_task)
self.source.append(mll_task.outputs[0])
@extension(*EXT_MLY)
def mly_hook(self, node):
mly_task = self.create_task('ocamlyacc', node, [node.change_ext('.ml'), node.change_ext('.mli')])
mly_task.env = self.native_env.derive()
self.mlytasks.append(mly_task)
self.source.append(mly_task.outputs[0])
task = self.create_task('ocamlcmi', mly_task.outputs[1], mly_task.outputs[1].change_ext('.cmi'))
task.env = self.native_env.derive()
@extension(*EXT_MLI)
def mli_hook(self, node):
task = self.create_task('ocamlcmi', node, node.change_ext('.cmi'))
task.env = self.native_env.derive()
self.mlitasks.append(task)
@extension(*EXT_MLC)
def mlc_hook(self, node):
task = self.create_task('ocamlcc', node, node.change_ext('.o'))
task.env = self.native_env.derive()
self.compiled_tasks.append(task)
@extension(*EXT_ML)
def ml_hook(self, node):
if self.native_env:
task = self.create_task('ocamlx', node, node.change_ext('.cmx'))
task.env = self.native_env.derive()
task.incpaths = self.bld_incpaths_lst
self.native_tasks.append(task)
if self.bytecode_env:
task = self.create_task('ocaml', node, node.change_ext('.cmo'))
task.env = self.bytecode_env.derive()
task.bytecode = 1
task.incpaths = self.bld_incpaths_lst
self.bytecode_tasks.append(task)
def compile_may_start(self):
if not getattr(self, 'flag_deps', ''):
self.flag_deps = 1
# the evil part is that we can only compute the dependencies after the
# source files can be read (this means actually producing the source files)
if getattr(self, 'bytecode', ''):
alltasks = self.generator.bytecode_tasks
else:
alltasks = self.generator.native_tasks
self.signature() # ensure that files are scanned - unfortunately
tree = self.generator.bld
for node in self.inputs:
lst = tree.node_deps[self.uid()]
for depnode in lst:
for t in alltasks:
if t == self:
continue
if depnode in t.inputs:
self.set_run_after(t)
# TODO necessary to get the signature right - for now
delattr(self, 'cache_sig')
self.signature()
return Task.Task.runnable_status(self)
class ocamlx(Task.Task):
"""native caml compilation"""
color = 'GREEN'
run_str = '${OCAMLOPT} ${OCAMLPATH} ${OCAMLFLAGS} ${OCAMLINCLUDES} -c -o ${TGT} ${SRC}'
scan = scan
runnable_status = compile_may_start
class ocaml(Task.Task):
"""bytecode caml compilation"""
color = 'GREEN'
run_str = '${OCAMLC} ${OCAMLPATH} ${OCAMLFLAGS} ${OCAMLINCLUDES} -c -o ${TGT} ${SRC}'
scan = scan
runnable_status = compile_may_start
class ocamlcmi(Task.Task):
"""interface generator (the .i files?)"""
color = 'BLUE'
run_str = '${OCAMLC} ${OCAMLPATH} ${OCAMLINCLUDES} -o ${TGT} -c ${SRC}'
before = ['ocamlcc', 'ocaml', 'ocamlcc']
class ocamlcc(Task.Task):
"""ocaml to c interfaces"""
color = 'GREEN'
run_str = 'cd ${TGT[0].bld_dir()} && ${OCAMLOPT} ${OCAMLFLAGS} ${OCAMLPATH} ${OCAMLINCLUDES} -c ${SRC[0].abspath()}'
class ocamllex(Task.Task):
"""lexical generator"""
color = 'BLUE'
run_str = '${OCAMLLEX} ${SRC} -o ${TGT}'
before = ['ocamlcmi', 'ocaml', 'ocamlcc']
class ocamlyacc(Task.Task):
"""parser generator"""
color = 'BLUE'
run_str = '${OCAMLYACC} -b ${tsk.base()} ${SRC}'
before = ['ocamlcmi', 'ocaml', 'ocamlcc']
def base(self):
node = self.outputs[0]
s = os.path.splitext(node.name)[0]
return node.bld_dir() + os.sep + s
def link_may_start(self):
if getattr(self, 'bytecode', 0):
alltasks = self.generator.bytecode_tasks
else:
alltasks = self.generator.native_tasks
for x in alltasks:
if not x.hasrun:
return Task.ASK_LATER
if not getattr(self, 'order', ''):
# now reorder the inputs given the task dependencies
# this part is difficult, we do not have a total order on the tasks
# if the dependencies are wrong, this may not stop
seen = []
pendant = []+alltasks
while pendant:
task = pendant.pop(0)
if task in seen:
continue
for x in task.run_after:
if not x in seen:
pendant.append(task)
break
else:
seen.append(task)
self.inputs = [x.outputs[0] for x in seen]
self.order = 1
return Task.Task.runnable_status(self)
class ocalink(Task.Task):
"""bytecode caml link"""
color = 'YELLOW'
run_str = '${OCAMLC} -o ${TGT} ${OCAMLINCLUDES} ${OCALINKFLAGS} ${SRC}'
runnable_status = link_may_start
after = ['ocaml', 'ocamlcc']
class ocalinkx(Task.Task):
"""native caml link"""
color = 'YELLOW'
run_str = '${OCAMLOPT} -o ${TGT} ${OCAMLINCLUDES} ${OCALINKFLAGS_OPT} ${SRC}'
runnable_status = link_may_start
after = ['ocamlx', 'ocamlcc']
def configure(conf):
opt = conf.find_program('ocamlopt', var='OCAMLOPT', mandatory=False)
occ = conf.find_program('ocamlc', var='OCAMLC', mandatory=False)
if (not opt) or (not occ):
conf.fatal('The objective caml compiler was not found:\ninstall it or make it available in your PATH')
v = conf.env
v['OCAMLC'] = occ
v['OCAMLOPT'] = opt
v['OCAMLLEX'] = conf.find_program('ocamllex', var='OCAMLLEX', mandatory=False)
v['OCAMLYACC'] = conf.find_program('ocamlyacc', var='OCAMLYACC', mandatory=False)
v['OCAMLFLAGS'] = ''
where = conf.cmd_and_log(conf.env.OCAMLC + ['-where']).strip()+os.sep
v['OCAMLLIB'] = where
v['LIBPATH_OCAML'] = where
v['INCLUDES_OCAML'] = where
v['LIB_OCAML'] = 'camlrun'
| 9,528 | Python | .py | 293 | 29.808874 | 117 | 0.680392 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,594 | gdbus.py | projecthamster_hamster/waflib/extras/gdbus.py | #!/usr/bin/env python
# encoding: utf-8
# Copyright Garmin International or its subsidiaries, 2018
#
# Heavily based on dbus.py
"""
Compiles dbus files with **gdbus-codegen**
Typical usage::
def options(opt):
opt.load('compiler_c gdbus')
def configure(conf):
conf.load('compiler_c gdbus')
def build(bld):
tg = bld.program(
includes = '.',
source = bld.path.ant_glob('*.c'),
target = 'gnome-hello')
tg.add_gdbus_file('test.xml', 'com.example.example.', 'Example')
"""
from waflib import Task, Errors, Utils
from waflib.TaskGen import taskgen_method, before_method
@taskgen_method
def add_gdbus_file(self, filename, prefix, namespace, export=False):
"""
Adds a dbus file to the list of dbus files to process. Store them in the attribute *dbus_lst*.
:param filename: xml file to compile
:type filename: string
:param prefix: interface prefix (--interface-prefix=prefix)
:type prefix: string
:param mode: C namespace (--c-namespace=namespace)
:type mode: string
:param export: Export Headers?
:type export: boolean
"""
if not hasattr(self, 'gdbus_lst'):
self.gdbus_lst = []
if not 'process_gdbus' in self.meths:
self.meths.append('process_gdbus')
self.gdbus_lst.append([filename, prefix, namespace, export])
@before_method('process_source')
def process_gdbus(self):
"""
Processes the dbus files stored in the attribute *gdbus_lst* to create :py:class:`gdbus_binding_tool` instances.
"""
output_node = self.path.get_bld().make_node(['gdbus', self.get_name()])
sources = []
for filename, prefix, namespace, export in getattr(self, 'gdbus_lst', []):
node = self.path.find_resource(filename)
if not node:
raise Errors.WafError('file not found ' + filename)
c_file = output_node.find_or_declare(node.change_ext('.c').name)
h_file = output_node.find_or_declare(node.change_ext('.h').name)
tsk = self.create_task('gdbus_binding_tool', node, [c_file, h_file])
tsk.cwd = output_node.abspath()
tsk.env.GDBUS_CODEGEN_INTERFACE_PREFIX = prefix
tsk.env.GDBUS_CODEGEN_NAMESPACE = namespace
tsk.env.GDBUS_CODEGEN_OUTPUT = node.change_ext('').name
sources.append(c_file)
if sources:
output_node.mkdir()
self.source = Utils.to_list(self.source) + sources
self.includes = [output_node] + self.to_incnodes(getattr(self, 'includes', []))
if export:
self.export_includes = [output_node] + self.to_incnodes(getattr(self, 'export_includes', []))
class gdbus_binding_tool(Task.Task):
"""
Compiles a dbus file
"""
color = 'BLUE'
ext_out = ['.h', '.c']
run_str = '${GDBUS_CODEGEN} --interface-prefix ${GDBUS_CODEGEN_INTERFACE_PREFIX} --generate-c-code ${GDBUS_CODEGEN_OUTPUT} --c-namespace ${GDBUS_CODEGEN_NAMESPACE} --c-generate-object-manager ${SRC[0].abspath()}'
shell = True
def configure(conf):
"""
Detects the program gdbus-codegen and sets ``conf.env.GDBUS_CODEGEN``
"""
conf.find_program('gdbus-codegen', var='GDBUS_CODEGEN')
| 2,906 | Python | .py | 77 | 35.441558 | 213 | 0.721178 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,595 | batched_cc.py | projecthamster_hamster/waflib/extras/batched_cc.py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2015 (ita)
"""
Instead of compiling object files one by one, c/c++ compilers are often able to compile at once:
cc -c ../file1.c ../file2.c ../file3.c
Files are output on the directory where the compiler is called, and dependencies are more difficult
to track (do not run the command on all source files if only one file changes)
As such, we do as if the files were compiled one by one, but no command is actually run:
replace each cc/cpp Task by a TaskSlave. A new task called TaskMaster collects the
signatures from each slave and finds out the command-line to run.
Just import this module to start using it:
def build(bld):
bld.load('batched_cc')
Note that this is provided as an example, unity builds are recommended
for best performance results (fewer tasks and fewer jobs to execute).
See waflib/extras/unity.py.
"""
from waflib import Task, Utils
from waflib.TaskGen import extension, feature, after_method
from waflib.Tools import c, cxx
MAX_BATCH = 50
c_str = '${CC} ${ARCH_ST:ARCH} ${CFLAGS} ${FRAMEWORKPATH_ST:FRAMEWORKPATH} ${tsk.batch_incpaths()} ${DEFINES_ST:DEFINES} -c ${SRCLST} ${CXX_TGT_F_BATCHED} ${CPPFLAGS}'
c_fun, _ = Task.compile_fun_noshell(c_str)
cxx_str = '${CXX} ${ARCH_ST:ARCH} ${CXXFLAGS} ${FRAMEWORKPATH_ST:FRAMEWORKPATH} ${tsk.batch_incpaths()} ${DEFINES_ST:DEFINES} -c ${SRCLST} ${CXX_TGT_F_BATCHED} ${CPPFLAGS}'
cxx_fun, _ = Task.compile_fun_noshell(cxx_str)
count = 70000
class batch(Task.Task):
color = 'PINK'
after = ['c', 'cxx']
before = ['cprogram', 'cshlib', 'cstlib', 'cxxprogram', 'cxxshlib', 'cxxstlib']
def uid(self):
return Utils.h_list([Task.Task.uid(self), self.generator.idx, self.generator.path.abspath(), self.generator.target])
def __str__(self):
return 'Batch compilation for %d slaves' % len(self.slaves)
def __init__(self, *k, **kw):
Task.Task.__init__(self, *k, **kw)
self.slaves = []
self.inputs = []
self.hasrun = 0
global count
count += 1
self.idx = count
def add_slave(self, slave):
self.slaves.append(slave)
self.set_run_after(slave)
def runnable_status(self):
for t in self.run_after:
if not t.hasrun:
return Task.ASK_LATER
for t in self.slaves:
#if t.executed:
if t.hasrun != Task.SKIPPED:
return Task.RUN_ME
return Task.SKIP_ME
def get_cwd(self):
return self.slaves[0].outputs[0].parent
def batch_incpaths(self):
st = self.env.CPPPATH_ST
return [st % node.abspath() for node in self.generator.includes_nodes]
def run(self):
self.outputs = []
srclst = []
slaves = []
for t in self.slaves:
if t.hasrun != Task.SKIPPED:
slaves.append(t)
srclst.append(t.inputs[0].abspath())
self.env.SRCLST = srclst
if self.slaves[0].__class__.__name__ == 'c':
ret = c_fun(self)
else:
ret = cxx_fun(self)
if ret:
return ret
for t in slaves:
t.old_post_run()
def hook(cls_type):
def n_hook(self, node):
ext = '.obj' if self.env.CC_NAME == 'msvc' else '.o'
name = node.name
k = name.rfind('.')
if k >= 0:
basename = name[:k] + ext
else:
basename = name + ext
outdir = node.parent.get_bld().make_node('%d' % self.idx)
outdir.mkdir()
out = outdir.find_or_declare(basename)
task = self.create_task(cls_type, node, out)
try:
self.compiled_tasks.append(task)
except AttributeError:
self.compiled_tasks = [task]
if not getattr(self, 'masters', None):
self.masters = {}
self.allmasters = []
def fix_path(tsk):
if self.env.CC_NAME == 'msvc':
tsk.env.append_unique('CXX_TGT_F_BATCHED', '/Fo%s\\' % outdir.abspath())
if not node.parent in self.masters:
m = self.masters[node.parent] = self.master = self.create_task('batch')
fix_path(m)
self.allmasters.append(m)
else:
m = self.masters[node.parent]
if len(m.slaves) > MAX_BATCH:
m = self.masters[node.parent] = self.master = self.create_task('batch')
fix_path(m)
self.allmasters.append(m)
m.add_slave(task)
return task
return n_hook
extension('.c')(hook('c'))
extension('.cpp','.cc','.cxx','.C','.c++')(hook('cxx'))
@feature('cprogram', 'cshlib', 'cstaticlib', 'cxxprogram', 'cxxshlib', 'cxxstlib')
@after_method('apply_link')
def link_after_masters(self):
if getattr(self, 'allmasters', None):
for m in self.allmasters:
self.link_task.set_run_after(m)
# Modify the c and cxx task classes - in theory it would be best to
# create subclasses and to re-map the c/c++ extensions
for x in ('c', 'cxx'):
t = Task.classes[x]
def run(self):
pass
def post_run(self):
pass
setattr(t, 'oldrun', getattr(t, 'run', None))
setattr(t, 'run', run)
setattr(t, 'old_post_run', t.post_run)
setattr(t, 'post_run', post_run)
| 4,694 | Python | .py | 133 | 32.421053 | 172 | 0.692104 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,596 | fc_xlf.py | projecthamster_hamster/waflib/extras/fc_xlf.py | #! /usr/bin/env python
# encoding: utf-8
# harald at klimachs.de
import re
from waflib import Utils,Errors
from waflib.Tools import fc,fc_config,fc_scan
from waflib.Configure import conf
from waflib.Tools.compiler_fc import fc_compiler
fc_compiler['aix'].insert(0, 'fc_xlf')
@conf
def find_xlf(conf):
"""Find the xlf program (will look in the environment variable 'FC')"""
fc = conf.find_program(['xlf2003_r', 'xlf2003', 'xlf95_r', 'xlf95', 'xlf90_r', 'xlf90', 'xlf_r', 'xlf'], var='FC')
conf.get_xlf_version(fc)
conf.env.FC_NAME='XLF'
@conf
def xlf_flags(conf):
v = conf.env
v['FCDEFINES_ST'] = '-WF,-D%s'
v['FCFLAGS_fcshlib'] = ['-qpic=small']
v['FCFLAGS_DEBUG'] = ['-qhalt=w']
v['LINKFLAGS_fcshlib'] = ['-Wl,-shared']
@conf
def xlf_modifier_platform(conf):
dest_os = conf.env['DEST_OS'] or Utils.unversioned_sys_platform()
xlf_modifier_func = getattr(conf, 'xlf_modifier_' + dest_os, None)
if xlf_modifier_func:
xlf_modifier_func()
@conf
def get_xlf_version(conf, fc):
"""Get the compiler version"""
cmd = fc + ['-qversion']
try:
out, err = conf.cmd_and_log(cmd, output=0)
except Errors.WafError:
conf.fatal('Could not find xlf %r' % cmd)
for v in (r"IBM XL Fortran.* V(?P<major>\d*)\.(?P<minor>\d*)",):
version_re = re.compile(v, re.I).search
match = version_re(out or err)
if match:
k = match.groupdict()
conf.env['FC_VERSION'] = (k['major'], k['minor'])
break
else:
conf.fatal('Could not determine the XLF version.')
def configure(conf):
conf.find_xlf()
conf.find_ar()
conf.fc_flags()
conf.fc_add_flags()
conf.xlf_flags()
conf.xlf_modifier_platform()
| 1,615 | Python | .py | 52 | 28.942308 | 115 | 0.688789 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,597 | color_rvct.py | projecthamster_hamster/waflib/extras/color_rvct.py | #!/usr/bin/env python
# encoding: utf-8
# Replaces the default formatter by one which understands RVCT output and colorizes it.
__author__ = __maintainer__ = "Jérôme Carretero <cJ-waf@zougloub.eu>"
__copyright__ = "Jérôme Carretero, 2012"
import sys
import atexit
from waflib import Logs
errors = []
def show_errors():
for i, e in enumerate(errors):
if i > 5:
break
print("Error: %s" % e)
atexit.register(show_errors)
class RcvtFormatter(Logs.formatter):
def __init__(self, colors):
Logs.formatter.__init__(self)
self.colors = colors
def format(self, rec):
frame = sys._getframe()
while frame:
func = frame.f_code.co_name
if func == 'exec_command':
cmd = frame.f_locals['cmd']
if isinstance(cmd, list) and ('armcc' in cmd[0] or 'armld' in cmd[0]):
lines = []
for line in rec.msg.splitlines():
if 'Warning: ' in line:
lines.append(self.colors.YELLOW + line)
elif 'Error: ' in line:
lines.append(self.colors.RED + line)
errors.append(line)
elif 'note: ' in line:
lines.append(self.colors.CYAN + line)
else:
lines.append(line)
rec.msg = "\n".join(lines)
frame = frame.f_back
return Logs.formatter.format(self, rec)
def options(opt):
Logs.log.handlers[0].setFormatter(RcvtFormatter(Logs.colors))
| 1,317 | Python | .py | 42 | 27.380952 | 87 | 0.675119 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,598 | fluid.py | projecthamster_hamster/waflib/extras/fluid.py | #!/usr/bin/python
# encoding: utf-8
# Grygoriy Fuchedzhy 2009
"""
Compile fluid files (fltk graphic library). Use the 'fluid' feature in conjunction with the 'cxx' feature.
"""
from waflib import Task
from waflib.TaskGen import extension
class fluid(Task.Task):
color = 'BLUE'
ext_out = ['.h']
run_str = '${FLUID} -c -o ${TGT[0].abspath()} -h ${TGT[1].abspath()} ${SRC}'
@extension('.fl')
def process_fluid(self, node):
"""add the .fl to the source list; the cxx file generated will be compiled when possible"""
cpp = node.change_ext('.cpp')
hpp = node.change_ext('.hpp')
self.create_task('fluid', node, [cpp, hpp])
if 'cxx' in self.features:
self.source.append(cpp)
def configure(conf):
conf.find_program('fluid', var='FLUID')
conf.check_cfg(path='fltk-config', package='', args='--cxxflags --ldflags', uselib_store='FLTK', mandatory=True)
| 862 | Python | .py | 23 | 35.652174 | 113 | 0.701923 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
20,599 | msvs.py | projecthamster_hamster/waflib/extras/msvs.py | #! /usr/bin/env python
# encoding: utf-8
# Avalanche Studios 2009-2011
# Thomas Nagy 2011
"""
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
"""
To add this tool to your project:
def options(conf):
opt.load('msvs')
It can be a good idea to add the sync_exec tool too.
To generate solution files:
$ waf configure msvs
To customize the outputs, provide subclasses in your wscript files::
from waflib.extras import msvs
class vsnode_target(msvs.vsnode_target):
def get_build_command(self, props):
# likely to be required
return "waf.bat build"
def collect_source(self):
# likely to be required
...
class msvs_bar(msvs.msvs_generator):
def init(self):
msvs.msvs_generator.init(self)
self.vsnode_target = vsnode_target
The msvs class re-uses the same build() function for reading the targets (task generators),
you may therefore specify msvs settings on the context object::
def build(bld):
bld.solution_name = 'foo.sln'
bld.waf_command = 'waf.bat'
bld.projects_dir = bld.srcnode.make_node('.depproj')
bld.projects_dir.mkdir()
For visual studio 2008, the command is called 'msvs2008', and the classes
such as vsnode_target are wrapped by a decorator class 'wrap_2008' to
provide special functionality.
To customize platform toolsets, pass additional parameters, for example::
class msvs_2013(msvs.msvs_generator):
cmd = 'msvs2013'
numver = '13.00'
vsver = '2013'
platform_toolset_ver = 'v120'
ASSUMPTIONS:
* a project can be either a directory or a target, vcxproj files are written only for targets that have source files
* each project is a vcxproj file, therefore the project uuid needs only to be a hash of the absolute path
"""
import os, re, sys
import uuid # requires python 2.5
from waflib.Build import BuildContext
from waflib import Utils, TaskGen, Logs, Task, Context, Node, Options
HEADERS_GLOB = '**/(*.h|*.hpp|*.H|*.inl)'
PROJECT_TEMPLATE = r'''<?xml version="1.0" encoding="UTF-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
${for b in project.build_properties}
<ProjectConfiguration Include="${b.configuration}|${b.platform}">
<Configuration>${b.configuration}</Configuration>
<Platform>${b.platform}</Platform>
</ProjectConfiguration>
${endfor}
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{${project.uuid}}</ProjectGuid>
<Keyword>MakeFileProj</Keyword>
<ProjectName>${project.name}</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
${for b in project.build_properties}
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'" Label="Configuration">
<ConfigurationType>Makefile</ConfigurationType>
<OutDir>${b.outdir}</OutDir>
<PlatformToolset>${project.platform_toolset_ver}</PlatformToolset>
</PropertyGroup>
${endfor}
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
${for b in project.build_properties}
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
${endfor}
${for b in project.build_properties}
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
<NMakeBuildCommandLine>${xml:project.get_build_command(b)}</NMakeBuildCommandLine>
<NMakeReBuildCommandLine>${xml:project.get_rebuild_command(b)}</NMakeReBuildCommandLine>
<NMakeCleanCommandLine>${xml:project.get_clean_command(b)}</NMakeCleanCommandLine>
<NMakeIncludeSearchPath>${xml:b.includes_search_path}</NMakeIncludeSearchPath>
<NMakePreprocessorDefinitions>${xml:b.preprocessor_definitions};$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<IncludePath>${xml:b.includes_search_path}</IncludePath>
<ExecutablePath>$(ExecutablePath)</ExecutablePath>
${if getattr(b, 'output_file', None)}
<NMakeOutput>${xml:b.output_file}</NMakeOutput>
${endif}
${if getattr(b, 'deploy_dir', None)}
<RemoteRoot>${xml:b.deploy_dir}</RemoteRoot>
${endif}
</PropertyGroup>
${endfor}
${for b in project.build_properties}
${if getattr(b, 'deploy_dir', None)}
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='${b.configuration}|${b.platform}'">
<Deploy>
<DeploymentType>CopyToHardDrive</DeploymentType>
</Deploy>
</ItemDefinitionGroup>
${endif}
${endfor}
<ItemGroup>
${for x in project.source}
<${project.get_key(x)} Include='${x.win32path()}' />
${endfor}
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
'''
FILTER_TEMPLATE = '''<?xml version="1.0" encoding="UTF-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
${for x in project.source}
<${project.get_key(x)} Include="${x.win32path()}">
<Filter>${project.get_filter_name(x.parent)}</Filter>
</${project.get_key(x)}>
${endfor}
</ItemGroup>
<ItemGroup>
${for x in project.dirs()}
<Filter Include="${project.get_filter_name(x)}">
<UniqueIdentifier>{${project.make_uuid(x.win32path())}}</UniqueIdentifier>
</Filter>
${endfor}
</ItemGroup>
</Project>
'''
PROJECT_2008_TEMPLATE = r'''<?xml version="1.0" encoding="UTF-8"?>
<VisualStudioProject ProjectType="Visual C++" Version="9,00"
Name="${xml: project.name}" ProjectGUID="{${project.uuid}}"
Keyword="MakeFileProj"
TargetFrameworkVersion="196613">
<Platforms>
${if project.build_properties}
${for b in project.build_properties}
<Platform Name="${xml: b.platform}" />
${endfor}
${else}
<Platform Name="Win32" />
${endif}
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
${if project.build_properties}
${for b in project.build_properties}
<Configuration
Name="${xml: b.configuration}|${xml: b.platform}"
IntermediateDirectory="$ConfigurationName"
OutputDirectory="${xml: b.outdir}"
ConfigurationType="0">
<Tool
Name="VCNMakeTool"
BuildCommandLine="${xml: project.get_build_command(b)}"
ReBuildCommandLine="${xml: project.get_rebuild_command(b)}"
CleanCommandLine="${xml: project.get_clean_command(b)}"
${if getattr(b, 'output_file', None)}
Output="${xml: b.output_file}"
${endif}
PreprocessorDefinitions="${xml: b.preprocessor_definitions}"
IncludeSearchPath="${xml: b.includes_search_path}"
ForcedIncludes=""
ForcedUsingAssemblies=""
AssemblySearchPath=""
CompileAsManaged=""
/>
</Configuration>
${endfor}
${else}
<Configuration Name="Release|Win32" >
</Configuration>
${endif}
</Configurations>
<References>
</References>
<Files>
${project.display_filter()}
</Files>
</VisualStudioProject>
'''
SOLUTION_TEMPLATE = '''Microsoft Visual Studio Solution File, Format Version ${project.numver}
# Visual Studio ${project.vsver}
${for p in project.all_projects}
Project("{${p.ptype()}}") = "${p.name}", "${p.title}", "{${p.uuid}}"
EndProject${endfor}
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
${if project.all_projects}
${for (configuration, platform) in project.all_projects[0].ctx.project_configurations()}
${configuration}|${platform} = ${configuration}|${platform}
${endfor}
${endif}
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
${for p in project.all_projects}
${if hasattr(p, 'source')}
${for b in p.build_properties}
{${p.uuid}}.${b.configuration}|${b.platform}.ActiveCfg = ${b.configuration}|${b.platform}
${if getattr(p, 'is_active', None)}
{${p.uuid}}.${b.configuration}|${b.platform}.Build.0 = ${b.configuration}|${b.platform}
${endif}
${if getattr(p, 'is_deploy', None)}
{${p.uuid}}.${b.configuration}|${b.platform}.Deploy.0 = ${b.configuration}|${b.platform}
${endif}
${endfor}
${endif}
${endfor}
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
${for p in project.all_projects}
${if p.parent}
{${p.uuid}} = {${p.parent.uuid}}
${endif}
${endfor}
EndGlobalSection
EndGlobal
'''
COMPILE_TEMPLATE = '''def f(project):
lst = []
def xml_escape(value):
return value.replace("&", "&").replace('"', """).replace("'", "'").replace("<", "<").replace(">", ">")
%s
#f = open('cmd.txt', 'w')
#f.write(str(lst))
#f.close()
return ''.join(lst)
'''
reg_act = re.compile(r"(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<code>[^}]*?)\})", re.M)
def compile_template(line):
"""
Compile a template expression into a python function (like jsps, but way shorter)
"""
extr = []
def repl(match):
g = match.group
if g('dollar'):
return "$"
elif g('backslash'):
return "\\"
elif g('subst'):
extr.append(g('code'))
return "<<|@|>>"
return None
line2 = reg_act.sub(repl, line)
params = line2.split('<<|@|>>')
assert(extr)
indent = 0
buf = []
app = buf.append
def app(txt):
buf.append(indent * '\t' + txt)
for x in range(len(extr)):
if params[x]:
app("lst.append(%r)" % params[x])
f = extr[x]
if f.startswith(('if', 'for')):
app(f + ':')
indent += 1
elif f.startswith('py:'):
app(f[3:])
elif f.startswith(('endif', 'endfor')):
indent -= 1
elif f.startswith(('else', 'elif')):
indent -= 1
app(f + ':')
indent += 1
elif f.startswith('xml:'):
app('lst.append(xml_escape(%s))' % f[4:])
else:
#app('lst.append((%s) or "cannot find %s")' % (f, f))
app('lst.append(%s)' % f)
if extr:
if params[-1]:
app("lst.append(%r)" % params[-1])
fun = COMPILE_TEMPLATE % "\n\t".join(buf)
#print(fun)
return Task.funex(fun)
re_blank = re.compile('(\n|\r|\\s)*\n', re.M)
def rm_blank_lines(txt):
txt = re_blank.sub('\r\n', txt)
return txt
BOM = '\xef\xbb\xbf'
try:
BOM = bytes(BOM, 'latin-1') # python 3
except TypeError:
pass
def stealth_write(self, data, flags='wb'):
try:
unicode
except NameError:
data = data.encode('utf-8') # python 3
else:
data = data.decode(sys.getfilesystemencoding(), 'replace')
data = data.encode('utf-8')
if self.name.endswith(('.vcproj', '.vcxproj')):
data = BOM + data
try:
txt = self.read(flags='rb')
if txt != data:
raise ValueError('must write')
except (IOError, ValueError):
self.write(data, flags=flags)
else:
Logs.debug('msvs: skipping %s', self.win32path())
Node.Node.stealth_write = stealth_write
re_win32 = re.compile(r'^([/\\]cygdrive)?[/\\]([a-z])([^a-z0-9_-].*)', re.I)
def win32path(self):
p = self.abspath()
m = re_win32.match(p)
if m:
return "%s:%s" % (m.group(2).upper(), m.group(3))
return p
Node.Node.win32path = win32path
re_quote = re.compile("[^a-zA-Z0-9-]")
def quote(s):
return re_quote.sub("_", s)
def xml_escape(value):
return value.replace("&", "&").replace('"', """).replace("'", "'").replace("<", "<").replace(">", ">")
def make_uuid(v, prefix = None):
"""
simple utility function
"""
if isinstance(v, dict):
keys = list(v.keys())
keys.sort()
tmp = str([(k, v[k]) for k in keys])
else:
tmp = str(v)
d = Utils.md5(tmp.encode()).hexdigest().upper()
if prefix:
d = '%s%s' % (prefix, d[8:])
gid = uuid.UUID(d, version = 4)
return str(gid).upper()
def diff(node, fromnode):
# difference between two nodes, but with "(..)" instead of ".."
c1 = node
c2 = fromnode
c1h = c1.height()
c2h = c2.height()
lst = []
up = 0
while c1h > c2h:
lst.append(c1.name)
c1 = c1.parent
c1h -= 1
while c2h > c1h:
up += 1
c2 = c2.parent
c2h -= 1
while id(c1) != id(c2):
lst.append(c1.name)
up += 1
c1 = c1.parent
c2 = c2.parent
for i in range(up):
lst.append('(..)')
lst.reverse()
return tuple(lst)
class build_property(object):
pass
class vsnode(object):
"""
Abstract class representing visual studio elements
We assume that all visual studio nodes have a uuid and a parent
"""
def __init__(self, ctx):
self.ctx = ctx # msvs context
self.name = '' # string, mandatory
self.vspath = '' # path in visual studio (name for dirs, absolute path for projects)
self.uuid = '' # string, mandatory
self.parent = None # parent node for visual studio nesting
def get_waf(self):
"""
Override in subclasses...
"""
return 'cd /d "%s" & %s' % (self.ctx.srcnode.win32path(), getattr(self.ctx, 'waf_command', 'waf.bat'))
def ptype(self):
"""
Return a special uuid for projects written in the solution file
"""
pass
def write(self):
"""
Write the project file, by default, do nothing
"""
pass
def make_uuid(self, val):
"""
Alias for creating uuid values easily (the templates cannot access global variables)
"""
return make_uuid(val)
class vsnode_vsdir(vsnode):
"""
Nodes representing visual studio folders (which do not match the filesystem tree!)
"""
VS_GUID_SOLUTIONFOLDER = "2150E333-8FDC-42A3-9474-1A3956D46DE8"
def __init__(self, ctx, uuid, name, vspath=''):
vsnode.__init__(self, ctx)
self.title = self.name = name
self.uuid = uuid
self.vspath = vspath or name
def ptype(self):
return self.VS_GUID_SOLUTIONFOLDER
class vsnode_project(vsnode):
"""
Abstract class representing visual studio project elements
A project is assumed to be writable, and has a node representing the file to write to
"""
VS_GUID_VCPROJ = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942"
def ptype(self):
return self.VS_GUID_VCPROJ
def __init__(self, ctx, node):
vsnode.__init__(self, ctx)
self.path = node
self.uuid = make_uuid(node.win32path())
self.name = node.name
self.platform_toolset_ver = getattr(ctx, 'platform_toolset_ver', None)
self.title = self.path.win32path()
self.source = [] # list of node objects
self.build_properties = [] # list of properties (nmake commands, output dir, etc)
def dirs(self):
"""
Get the list of parent folders of the source files (header files included)
for writing the filters
"""
lst = []
def add(x):
if x.height() > self.tg.path.height() and x not in lst:
lst.append(x)
add(x.parent)
for x in self.source:
add(x.parent)
return lst
def write(self):
Logs.debug('msvs: creating %r', self.path)
# first write the project file
template1 = compile_template(PROJECT_TEMPLATE)
proj_str = template1(self)
proj_str = rm_blank_lines(proj_str)
self.path.stealth_write(proj_str)
# then write the filter
template2 = compile_template(FILTER_TEMPLATE)
filter_str = template2(self)
filter_str = rm_blank_lines(filter_str)
tmp = self.path.parent.make_node(self.path.name + '.filters')
tmp.stealth_write(filter_str)
def get_key(self, node):
"""
required for writing the source files
"""
name = node.name
if name.endswith(('.cpp', '.c')):
return 'ClCompile'
return 'ClInclude'
def collect_properties(self):
"""
Returns a list of triplet (configuration, platform, output_directory)
"""
ret = []
for c in self.ctx.configurations:
for p in self.ctx.platforms:
x = build_property()
x.outdir = ''
x.configuration = c
x.platform = p
x.preprocessor_definitions = ''
x.includes_search_path = ''
# can specify "deploy_dir" too
ret.append(x)
self.build_properties = ret
def get_build_params(self, props):
opt = '--execsolution="%s"' % self.ctx.get_solution_node().win32path()
return (self.get_waf(), opt)
def get_build_command(self, props):
return "%s build %s" % self.get_build_params(props)
def get_clean_command(self, props):
return "%s clean %s" % self.get_build_params(props)
def get_rebuild_command(self, props):
return "%s clean build %s" % self.get_build_params(props)
def get_filter_name(self, node):
lst = diff(node, self.tg.path)
return '\\'.join(lst) or '.'
class vsnode_alias(vsnode_project):
def __init__(self, ctx, node, name):
vsnode_project.__init__(self, ctx, node)
self.name = name
self.output_file = ''
class vsnode_build_all(vsnode_alias):
"""
Fake target used to emulate the behaviour of "make all" (starting one process by target is slow)
This is the only alias enabled by default
"""
def __init__(self, ctx, node, name='build_all_projects'):
vsnode_alias.__init__(self, ctx, node, name)
self.is_active = True
class vsnode_install_all(vsnode_alias):
"""
Fake target used to emulate the behaviour of "make install"
"""
def __init__(self, ctx, node, name='install_all_projects'):
vsnode_alias.__init__(self, ctx, node, name)
def get_build_command(self, props):
return "%s build install %s" % self.get_build_params(props)
def get_clean_command(self, props):
return "%s clean %s" % self.get_build_params(props)
def get_rebuild_command(self, props):
return "%s clean build install %s" % self.get_build_params(props)
class vsnode_project_view(vsnode_alias):
"""
Fake target used to emulate a file system view
"""
def __init__(self, ctx, node, name='project_view'):
vsnode_alias.__init__(self, ctx, node, name)
self.tg = self.ctx() # fake one, cannot remove
self.exclude_files = Node.exclude_regs + '''
waf-2*
waf3-2*/**
.waf-2*
.waf3-2*/**
**/*.sdf
**/*.suo
**/*.ncb
**/%s
''' % Options.lockfile
def collect_source(self):
# this is likely to be slow
self.source = self.ctx.srcnode.ant_glob('**', excl=self.exclude_files)
def get_build_command(self, props):
params = self.get_build_params(props) + (self.ctx.cmd,)
return "%s %s %s" % params
def get_clean_command(self, props):
return ""
def get_rebuild_command(self, props):
return self.get_build_command(props)
class vsnode_target(vsnode_project):
"""
Visual studio project representing a targets (programs, libraries, etc) and bound
to a task generator
"""
def __init__(self, ctx, tg):
"""
A project is more or less equivalent to a file/folder
"""
base = getattr(ctx, 'projects_dir', None) or tg.path
node = base.make_node(quote(tg.name) + ctx.project_extension) # the project file as a Node
vsnode_project.__init__(self, ctx, node)
self.name = quote(tg.name)
self.tg = tg # task generator
def get_build_params(self, props):
"""
Override the default to add the target name
"""
opt = '--execsolution="%s"' % self.ctx.get_solution_node().win32path()
if getattr(self, 'tg', None):
opt += " --targets=%s" % self.tg.name
return (self.get_waf(), opt)
def collect_source(self):
tg = self.tg
source_files = tg.to_nodes(getattr(tg, 'source', []))
include_dirs = Utils.to_list(getattr(tg, 'msvs_includes', []))
include_files = []
for x in include_dirs:
if isinstance(x, str):
x = tg.path.find_node(x)
if x:
lst = [y for y in x.ant_glob(HEADERS_GLOB, flat=False)]
include_files.extend(lst)
# remove duplicates
self.source.extend(list(set(source_files + include_files)))
self.source.sort(key=lambda x: x.win32path())
def collect_properties(self):
"""
Visual studio projects are associated with platforms and configurations (for building especially)
"""
super(vsnode_target, self).collect_properties()
for x in self.build_properties:
x.outdir = self.path.parent.win32path()
x.preprocessor_definitions = ''
x.includes_search_path = ''
try:
tsk = self.tg.link_task
except AttributeError:
pass
else:
x.output_file = tsk.outputs[0].win32path()
x.preprocessor_definitions = ';'.join(tsk.env.DEFINES)
x.includes_search_path = ';'.join(self.tg.env.INCPATHS)
class msvs_generator(BuildContext):
'''generates a visual studio 2010 solution'''
cmd = 'msvs'
fun = 'build'
numver = '11.00' # Visual Studio Version Number
vsver = '2010' # Visual Studio Version Year
platform_toolset_ver = 'v110' # Platform Toolset Version Number
def init(self):
"""
Some data that needs to be present
"""
if not getattr(self, 'configurations', None):
self.configurations = ['Release'] # LocalRelease, RemoteDebug, etc
if not getattr(self, 'platforms', None):
self.platforms = ['Win32']
if not getattr(self, 'all_projects', None):
self.all_projects = []
if not getattr(self, 'project_extension', None):
self.project_extension = '.vcxproj'
if not getattr(self, 'projects_dir', None):
self.projects_dir = self.srcnode.make_node('.depproj')
self.projects_dir.mkdir()
# bind the classes to the object, so that subclass can provide custom generators
if not getattr(self, 'vsnode_vsdir', None):
self.vsnode_vsdir = vsnode_vsdir
if not getattr(self, 'vsnode_target', None):
self.vsnode_target = vsnode_target
if not getattr(self, 'vsnode_build_all', None):
self.vsnode_build_all = vsnode_build_all
if not getattr(self, 'vsnode_install_all', None):
self.vsnode_install_all = vsnode_install_all
if not getattr(self, 'vsnode_project_view', None):
self.vsnode_project_view = vsnode_project_view
self.numver = self.__class__.numver
self.vsver = self.__class__.vsver
self.platform_toolset_ver = self.__class__.platform_toolset_ver
def execute(self):
"""
Entry point
"""
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
# user initialization
self.init()
# two phases for creating the solution
self.collect_projects() # add project objects into "self.all_projects"
self.write_files() # write the corresponding project and solution files
def collect_projects(self):
"""
Fill the list self.all_projects with project objects
Fill the list of build targets
"""
self.collect_targets()
self.add_aliases()
self.collect_dirs()
default_project = getattr(self, 'default_project', None)
def sortfun(x):
# folders should sort to the top
if getattr(x, 'VS_GUID_SOLUTIONFOLDER', None):
return ''
# followed by the default project
elif x.name == default_project:
return ' '
return getattr(x, 'path', None) and x.path.win32path() or x.name
self.all_projects.sort(key=sortfun)
def write_files(self):
"""
Write the project and solution files from the data collected
so far. It is unlikely that you will want to change this
"""
for p in self.all_projects:
p.write()
# and finally write the solution file
node = self.get_solution_node()
node.parent.mkdir()
Logs.warn('Creating %r', node)
template1 = compile_template(SOLUTION_TEMPLATE)
sln_str = template1(self)
sln_str = rm_blank_lines(sln_str)
node.stealth_write(sln_str)
def get_solution_node(self):
"""
The solution filename is required when writing the .vcproj files
return self.solution_node and if it does not exist, make one
"""
try:
return self.solution_node
except AttributeError:
pass
solution_name = getattr(self, 'solution_name', None)
if not solution_name:
solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '.sln'
if os.path.isabs(solution_name):
self.solution_node = self.root.make_node(solution_name)
else:
self.solution_node = self.srcnode.make_node(solution_name)
return self.solution_node
def project_configurations(self):
"""
Helper that returns all the pairs (config,platform)
"""
ret = []
for c in self.configurations:
for p in self.platforms:
ret.append((c, p))
return ret
def collect_targets(self):
"""
Process the list of task generators
"""
for g in self.groups:
for tg in g:
if not isinstance(tg, TaskGen.task_gen):
continue
if not hasattr(tg, 'msvs_includes'):
tg.msvs_includes = tg.to_list(getattr(tg, 'includes', [])) + tg.to_list(getattr(tg, 'export_includes', []))
tg.post()
if not getattr(tg, 'link_task', None):
continue
p = self.vsnode_target(self, tg)
p.collect_source() # delegate this processing
p.collect_properties()
self.all_projects.append(p)
def add_aliases(self):
"""
Add a specific target that emulates the "make all" necessary for Visual studio when pressing F7
We also add an alias for "make install" (disabled by default)
"""
base = getattr(self, 'projects_dir', None) or self.tg.path
node_project = base.make_node('build_all_projects' + self.project_extension) # Node
p_build = self.vsnode_build_all(self, node_project)
p_build.collect_properties()
self.all_projects.append(p_build)
node_project = base.make_node('install_all_projects' + self.project_extension) # Node
p_install = self.vsnode_install_all(self, node_project)
p_install.collect_properties()
self.all_projects.append(p_install)
node_project = base.make_node('project_view' + self.project_extension) # Node
p_view = self.vsnode_project_view(self, node_project)
p_view.collect_source()
p_view.collect_properties()
self.all_projects.append(p_view)
n = self.vsnode_vsdir(self, make_uuid(self.srcnode.win32path() + 'build_aliases'), "build_aliases")
p_build.parent = p_install.parent = p_view.parent = n
self.all_projects.append(n)
def collect_dirs(self):
"""
Create the folder structure in the Visual studio project view
"""
seen = {}
def make_parents(proj):
# look at a project, try to make a parent
if getattr(proj, 'parent', None):
# aliases already have parents
return
x = proj.iter_path
if x in seen:
proj.parent = seen[x]
return
# There is not vsnode_vsdir for x.
# So create a project representing the folder "x"
n = proj.parent = seen[x] = self.vsnode_vsdir(self, make_uuid(x.win32path()), x.name)
n.iter_path = x.parent
self.all_projects.append(n)
# recurse up to the project directory
if x.height() > self.srcnode.height() + 1:
make_parents(n)
for p in self.all_projects[:]: # iterate over a copy of all projects
if not getattr(p, 'tg', None):
# but only projects that have a task generator
continue
# make a folder for each task generator
p.iter_path = p.tg.path
make_parents(p)
def wrap_2008(cls):
class dec(cls):
def __init__(self, *k, **kw):
cls.__init__(self, *k, **kw)
self.project_template = PROJECT_2008_TEMPLATE
def display_filter(self):
root = build_property()
root.subfilters = []
root.sourcefiles = []
root.source = []
root.name = ''
@Utils.run_once
def add_path(lst):
if not lst:
return root
child = build_property()
child.subfilters = []
child.sourcefiles = []
child.source = []
child.name = lst[-1]
par = add_path(lst[:-1])
par.subfilters.append(child)
return child
for x in self.source:
# this crap is for enabling subclasses to override get_filter_name
tmp = self.get_filter_name(x.parent)
tmp = tmp != '.' and tuple(tmp.split('\\')) or ()
par = add_path(tmp)
par.source.append(x)
def display(n):
buf = []
for x in n.source:
buf.append('<File RelativePath="%s" FileType="%s"/>\n' % (xml_escape(x.win32path()), self.get_key(x)))
for x in n.subfilters:
buf.append('<Filter Name="%s">' % xml_escape(x.name))
buf.append(display(x))
buf.append('</Filter>')
return '\n'.join(buf)
return display(root)
def get_key(self, node):
"""
If you do not want to let visual studio use the default file extensions,
override this method to return a value:
0: C/C++ Code, 1: C++ Class, 2: C++ Header File, 3: C++ Form,
4: C++ Control, 5: Text File, 6: DEF File, 7: IDL File,
8: Makefile, 9: RGS File, 10: RC File, 11: RES File, 12: XSD File,
13: XML File, 14: HTML File, 15: CSS File, 16: Bitmap, 17: Icon,
18: Resx File, 19: BSC File, 20: XSX File, 21: C++ Web Service,
22: ASAX File, 23: Asp Page, 24: Document, 25: Discovery File,
26: C# File, 27: eFileTypeClassDiagram, 28: MHTML Document,
29: Property Sheet, 30: Cursor, 31: Manifest, 32: eFileTypeRDLC
"""
return ''
def write(self):
Logs.debug('msvs: creating %r', self.path)
template1 = compile_template(self.project_template)
proj_str = template1(self)
proj_str = rm_blank_lines(proj_str)
self.path.stealth_write(proj_str)
return dec
class msvs_2008_generator(msvs_generator):
'''generates a visual studio 2008 solution'''
cmd = 'msvs2008'
fun = msvs_generator.fun
numver = '10.00'
vsver = '2008'
def init(self):
if not getattr(self, 'project_extension', None):
self.project_extension = '_2008.vcproj'
if not getattr(self, 'solution_name', None):
self.solution_name = getattr(Context.g_module, Context.APPNAME, 'project') + '_2008.sln'
if not getattr(self, 'vsnode_target', None):
self.vsnode_target = wrap_2008(vsnode_target)
if not getattr(self, 'vsnode_build_all', None):
self.vsnode_build_all = wrap_2008(vsnode_build_all)
if not getattr(self, 'vsnode_install_all', None):
self.vsnode_install_all = wrap_2008(vsnode_install_all)
if not getattr(self, 'vsnode_project_view', None):
self.vsnode_project_view = wrap_2008(vsnode_project_view)
msvs_generator.init(self)
def options(ctx):
"""
If the msvs option is used, try to detect if the build is made from visual studio
"""
ctx.add_option('--execsolution', action='store', help='when building with visual studio, use a build state file')
old = BuildContext.execute
def override_build_state(ctx):
def lock(rm, add):
uns = ctx.options.execsolution.replace('.sln', rm)
uns = ctx.root.make_node(uns)
try:
uns.delete()
except OSError:
pass
uns = ctx.options.execsolution.replace('.sln', add)
uns = ctx.root.make_node(uns)
try:
uns.write('')
except EnvironmentError:
pass
if ctx.options.execsolution:
ctx.launch_dir = Context.top_dir # force a build for the whole project (invalid cwd when called by visual studio)
lock('.lastbuildstate', '.unsuccessfulbuild')
old(ctx)
lock('.unsuccessfulbuild', '.lastbuildstate')
else:
old(ctx)
BuildContext.execute = override_build_state
| 31,202 | Python | .py | 905 | 31.418785 | 177 | 0.70063 | projecthamster/hamster | 1,069 | 250 | 128 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |