repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
jazzband/django-push-notifications | push_notifications/fields.py | HexIntegerField.get_prep_value | python | def get_prep_value(self, value):
if value is None or value == "":
return None
if isinstance(value, six.string_types):
value = _hex_string_to_unsigned_integer(value)
if _using_signed_storage():
value = _unsigned_to_signed_integer(value)
return value | Return the integer value to be stored from the hex string | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L91-L99 | [
"def _using_signed_storage():\n\treturn connection.settings_dict[\"ENGINE\"] in signed_integer_engines\n",
"def _unsigned_to_signed_integer(value):\n\treturn struct.unpack(\"q\", struct.pack(\"Q\", value))[0]\n",
"def _hex_string_to_unsigned_integer(value):\n\treturn int(value, 16)\n"
] | class HexIntegerField(models.BigIntegerField):
"""
This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer
on *all* backends including postgres.
Reasoning: Postgres only supports signed bigints. Since we don't care about
signedness, we store it as signed, and cast it to unsigned when we deal with
the actual value (with struct)
On sqlite and mysql, native unsigned bigint types are used. In all cases, the
value we deal with in python is always in hex.
"""
validators = [
MinValueValidator(UNSIGNED_64BIT_INT_MIN_VALUE),
MaxValueValidator(UNSIGNED_64BIT_INT_MAX_VALUE)
]
def db_type(self, connection):
engine = connection.settings_dict["ENGINE"]
if "mysql" in engine:
return "bigint unsigned"
elif "sqlite" in engine:
return "UNSIGNED BIG INT"
else:
return super(HexIntegerField, self).db_type(connection=connection)
def from_db_value(self, value, expression, connection, context):
""" Return an unsigned int representation from all db backends """
if value is None:
return value
if _using_signed_storage():
value = _signed_to_unsigned_integer(value)
return value
def to_python(self, value):
""" Return a str representation of the hexadecimal """
if isinstance(value, six.string_types):
return value
if value is None:
return value
return _unsigned_integer_to_hex_string(value)
def formfield(self, **kwargs):
defaults = {"form_class": HexadecimalField}
defaults.update(kwargs)
# yes, that super call is right
return super(models.IntegerField, self).formfield(**defaults)
def run_validators(self, value):
# make sure validation is performed on integer value not string value
value = _hex_string_to_unsigned_integer(value)
return super(models.BigIntegerField, self).run_validators(value)
|
jazzband/django-push-notifications | push_notifications/fields.py | HexIntegerField.from_db_value | python | def from_db_value(self, value, expression, connection, context):
if value is None:
return value
if _using_signed_storage():
value = _signed_to_unsigned_integer(value)
return value | Return an unsigned int representation from all db backends | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L101-L107 | [
"def _using_signed_storage():\n\treturn connection.settings_dict[\"ENGINE\"] in signed_integer_engines\n",
"def _signed_to_unsigned_integer(value):\n\treturn struct.unpack(\"Q\", struct.pack(\"q\", value))[0]\n"
] | class HexIntegerField(models.BigIntegerField):
"""
This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer
on *all* backends including postgres.
Reasoning: Postgres only supports signed bigints. Since we don't care about
signedness, we store it as signed, and cast it to unsigned when we deal with
the actual value (with struct)
On sqlite and mysql, native unsigned bigint types are used. In all cases, the
value we deal with in python is always in hex.
"""
validators = [
MinValueValidator(UNSIGNED_64BIT_INT_MIN_VALUE),
MaxValueValidator(UNSIGNED_64BIT_INT_MAX_VALUE)
]
def db_type(self, connection):
engine = connection.settings_dict["ENGINE"]
if "mysql" in engine:
return "bigint unsigned"
elif "sqlite" in engine:
return "UNSIGNED BIG INT"
else:
return super(HexIntegerField, self).db_type(connection=connection)
def get_prep_value(self, value):
""" Return the integer value to be stored from the hex string """
if value is None or value == "":
return None
if isinstance(value, six.string_types):
value = _hex_string_to_unsigned_integer(value)
if _using_signed_storage():
value = _unsigned_to_signed_integer(value)
return value
def to_python(self, value):
""" Return a str representation of the hexadecimal """
if isinstance(value, six.string_types):
return value
if value is None:
return value
return _unsigned_integer_to_hex_string(value)
def formfield(self, **kwargs):
defaults = {"form_class": HexadecimalField}
defaults.update(kwargs)
# yes, that super call is right
return super(models.IntegerField, self).formfield(**defaults)
def run_validators(self, value):
# make sure validation is performed on integer value not string value
value = _hex_string_to_unsigned_integer(value)
return super(models.BigIntegerField, self).run_validators(value)
|
jazzband/django-push-notifications | push_notifications/fields.py | HexIntegerField.to_python | python | def to_python(self, value):
if isinstance(value, six.string_types):
return value
if value is None:
return value
return _unsigned_integer_to_hex_string(value) | Return a str representation of the hexadecimal | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L109-L115 | [
"def _unsigned_integer_to_hex_string(value):\n\treturn hex(value).rstrip(\"L\")\n"
] | class HexIntegerField(models.BigIntegerField):
"""
This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer
on *all* backends including postgres.
Reasoning: Postgres only supports signed bigints. Since we don't care about
signedness, we store it as signed, and cast it to unsigned when we deal with
the actual value (with struct)
On sqlite and mysql, native unsigned bigint types are used. In all cases, the
value we deal with in python is always in hex.
"""
validators = [
MinValueValidator(UNSIGNED_64BIT_INT_MIN_VALUE),
MaxValueValidator(UNSIGNED_64BIT_INT_MAX_VALUE)
]
def db_type(self, connection):
engine = connection.settings_dict["ENGINE"]
if "mysql" in engine:
return "bigint unsigned"
elif "sqlite" in engine:
return "UNSIGNED BIG INT"
else:
return super(HexIntegerField, self).db_type(connection=connection)
def get_prep_value(self, value):
""" Return the integer value to be stored from the hex string """
if value is None or value == "":
return None
if isinstance(value, six.string_types):
value = _hex_string_to_unsigned_integer(value)
if _using_signed_storage():
value = _unsigned_to_signed_integer(value)
return value
def from_db_value(self, value, expression, connection, context):
""" Return an unsigned int representation from all db backends """
if value is None:
return value
if _using_signed_storage():
value = _signed_to_unsigned_integer(value)
return value
def formfield(self, **kwargs):
defaults = {"form_class": HexadecimalField}
defaults.update(kwargs)
# yes, that super call is right
return super(models.IntegerField, self).formfield(**defaults)
def run_validators(self, value):
# make sure validation is performed on integer value not string value
value = _hex_string_to_unsigned_integer(value)
return super(models.BigIntegerField, self).run_validators(value)
|
jazzband/django-push-notifications | push_notifications/apns.py | apns_send_message | python | def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
try:
_apns_send(
registration_id, alert, application_id=application_id,
certfile=certfile, **kwargs
)
except apns2_errors.APNsException as apns2_exception:
if isinstance(apns2_exception, apns2_errors.Unregistered):
device = models.APNSDevice.objects.get(registration_id=registration_id)
device.active = False
device.save()
raise APNSServerError(status=apns2_exception.__class__.__name__) | Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need to pass None
to this for silent notifications. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/apns.py#L97-L120 | [
"def _apns_send(\n\tregistration_id, alert, batch=False, application_id=None, certfile=None, **kwargs\n):\n\tclient = _apns_create_socket(certfile=certfile, application_id=application_id)\n\n\tnotification_kwargs = {}\n\n\t# if expiration isn\"t specified use 1 month from now\n\tnotification_kwargs[\"expiration\"] ... | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import errors as apns2_errors
from apns2 import payload as apns2_payload
from . import models
from .conf import get_manager
from .exceptions import NotificationError
class APNSError(NotificationError):
pass
class APNSUnsupportedPriority(APNSError):
pass
class APNSServerError(APNSError):
def __init__(self, status):
super(APNSServerError, self).__init__(status)
self.status = status
def _apns_create_socket(certfile=None, application_id=None):
certfile = certfile or get_manager().get_apns_certificate(application_id)
client = apns2_client.APNsClient(
certfile,
use_sandbox=get_manager().get_apns_use_sandbox(application_id),
use_alternative_port=get_manager().get_apns_use_alternative_port(application_id)
)
client.connect()
return client
def _apns_prepare(
token, alert, application_id=None, badge=None, sound=None, category=None,
content_available=False, action_loc_key=None, loc_key=None, loc_args=[],
extra={}, mutable_content=False, thread_id=None, url_args=None):
if action_loc_key or loc_key or loc_args:
apns2_alert = apns2_payload.PayloadAlert(
body=alert if alert else {}, body_localized_key=loc_key,
body_localized_args=loc_args, action_localized_key=action_loc_key)
else:
apns2_alert = alert
if callable(badge):
badge = badge(token)
return apns2_payload.Payload(
apns2_alert, badge, sound, content_available, mutable_content, category,
url_args, custom=extra, thread_id=thread_id)
def _apns_send(
registration_id, alert, batch=False, application_id=None, certfile=None, **kwargs
):
client = _apns_create_socket(certfile=certfile, application_id=application_id)
notification_kwargs = {}
# if expiration isn"t specified use 1 month from now
notification_kwargs["expiration"] = kwargs.pop("expiration", None)
if not notification_kwargs["expiration"]:
notification_kwargs["expiration"] = int(time.time()) + 2592000
priority = kwargs.pop("priority", None)
if priority:
try:
notification_kwargs["priority"] = apns2_client.NotificationPriority(str(priority))
except ValueError:
raise APNSUnsupportedPriority("Unsupported priority %d" % (priority))
if batch:
data = [apns2_client.Notification(
token=rid, payload=_apns_prepare(rid, alert, **kwargs)) for rid in registration_id]
return client.send_notification_batch(
data, get_manager().get_apns_topic(application_id=application_id),
**notification_kwargs
)
data = _apns_prepare(registration_id, alert, **kwargs)
client.send_notification(
registration_id, data,
get_manager().get_apns_topic(application_id=application_id),
**notification_kwargs
)
def apns_send_bulk_message(
registration_ids, alert, application_id=None, certfile=None, **kwargs
):
"""
Sends an APNS notification to one or more registration_ids.
The registration_ids argument needs to be a list.
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need to pass None
to this for silent notifications.
"""
results = _apns_send(
registration_ids, alert, batch=True, application_id=application_id,
certfile=certfile, **kwargs
)
inactive_tokens = [token for token, result in results.items() if result == "Unregistered"]
models.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False)
return results
|
jazzband/django-push-notifications | push_notifications/apns.py | apns_send_bulk_message | python | def apns_send_bulk_message(
registration_ids, alert, application_id=None, certfile=None, **kwargs
):
results = _apns_send(
registration_ids, alert, batch=True, application_id=application_id,
certfile=certfile, **kwargs
)
inactive_tokens = [token for token, result in results.items() if result == "Unregistered"]
models.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False)
return results | Sends an APNS notification to one or more registration_ids.
The registration_ids argument needs to be a list.
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need to pass None
to this for silent notifications. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/apns.py#L123-L141 | [
"def _apns_send(\n\tregistration_id, alert, batch=False, application_id=None, certfile=None, **kwargs\n):\n\tclient = _apns_create_socket(certfile=certfile, application_id=application_id)\n\n\tnotification_kwargs = {}\n\n\t# if expiration isn\"t specified use 1 month from now\n\tnotification_kwargs[\"expiration\"] ... | """
Apple Push Notification Service
Documentation is available on the iOS Developer Library:
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
"""
import time
from apns2 import client as apns2_client
from apns2 import errors as apns2_errors
from apns2 import payload as apns2_payload
from . import models
from .conf import get_manager
from .exceptions import NotificationError
class APNSError(NotificationError):
pass
class APNSUnsupportedPriority(APNSError):
pass
class APNSServerError(APNSError):
def __init__(self, status):
super(APNSServerError, self).__init__(status)
self.status = status
def _apns_create_socket(certfile=None, application_id=None):
certfile = certfile or get_manager().get_apns_certificate(application_id)
client = apns2_client.APNsClient(
certfile,
use_sandbox=get_manager().get_apns_use_sandbox(application_id),
use_alternative_port=get_manager().get_apns_use_alternative_port(application_id)
)
client.connect()
return client
def _apns_prepare(
token, alert, application_id=None, badge=None, sound=None, category=None,
content_available=False, action_loc_key=None, loc_key=None, loc_args=[],
extra={}, mutable_content=False, thread_id=None, url_args=None):
if action_loc_key or loc_key or loc_args:
apns2_alert = apns2_payload.PayloadAlert(
body=alert if alert else {}, body_localized_key=loc_key,
body_localized_args=loc_args, action_localized_key=action_loc_key)
else:
apns2_alert = alert
if callable(badge):
badge = badge(token)
return apns2_payload.Payload(
apns2_alert, badge, sound, content_available, mutable_content, category,
url_args, custom=extra, thread_id=thread_id)
def _apns_send(
registration_id, alert, batch=False, application_id=None, certfile=None, **kwargs
):
client = _apns_create_socket(certfile=certfile, application_id=application_id)
notification_kwargs = {}
# if expiration isn"t specified use 1 month from now
notification_kwargs["expiration"] = kwargs.pop("expiration", None)
if not notification_kwargs["expiration"]:
notification_kwargs["expiration"] = int(time.time()) + 2592000
priority = kwargs.pop("priority", None)
if priority:
try:
notification_kwargs["priority"] = apns2_client.NotificationPriority(str(priority))
except ValueError:
raise APNSUnsupportedPriority("Unsupported priority %d" % (priority))
if batch:
data = [apns2_client.Notification(
token=rid, payload=_apns_prepare(rid, alert, **kwargs)) for rid in registration_id]
return client.send_notification_batch(
data, get_manager().get_apns_topic(application_id=application_id),
**notification_kwargs
)
data = _apns_prepare(registration_id, alert, **kwargs)
client.send_notification(
registration_id, data,
get_manager().get_apns_topic(application_id=application_id),
**notification_kwargs
)
def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
"""
Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert should always be a string. If it is not set,
it won"t be included in the notification. You will need to pass None
to this for silent notifications.
"""
try:
_apns_send(
registration_id, alert, application_id=application_id,
certfile=certfile, **kwargs
)
except apns2_errors.APNsException as apns2_exception:
if isinstance(apns2_exception, apns2_errors.Unregistered):
device = models.APNSDevice.objects.get(registration_id=registration_id)
device.active = False
device.save()
raise APNSServerError(status=apns2_exception.__class__.__name__)
|
jazzband/django-push-notifications | push_notifications/gcm.py | _cm_send_request | python | def _cm_send_request(
registration_ids, data, cloud_type="GCM", application_id=None,
use_fcm_notifications=True, **kwargs
):
payload = {"registration_ids": registration_ids} if registration_ids else {}
data = data.copy()
# If using FCM, optionnally autodiscovers notification related keys
# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
if cloud_type == "FCM" and use_fcm_notifications:
notification_payload = {}
if "message" in data:
notification_payload["body"] = data.pop("message", None)
for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
value_from_extra = data.pop(key, None)
if value_from_extra:
notification_payload[key] = value_from_extra
value_from_kwargs = kwargs.pop(key, None)
if value_from_kwargs:
notification_payload[key] = value_from_kwargs
if notification_payload:
payload["notification"] = notification_payload
if data:
payload["data"] = data
# Attach any additional non falsy keyword args (targets, options)
# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
payload.update({
k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
})
# Sort the keys for deterministic output (useful for tests)
json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
# Sends requests and handles the response
if cloud_type == "GCM":
response = json.loads(_gcm_send(
json_payload, "application/json", application_id=application_id
))
elif cloud_type == "FCM":
response = json.loads(_fcm_send(
json_payload, "application/json", application_id=application_id
))
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
return _cm_handle_response(registration_ids, response, cloud_type, application_id) | Sends a FCM or GCM notification to one or more registration_ids as json data.
The registration_ids needs to be a list. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/gcm.py#L111-L164 | [
"def _gcm_send(data, content_type, application_id):\n\tkey = get_manager().get_gcm_api_key(application_id)\n\n\theaders = {\n\t\t\"Content-Type\": content_type,\n\t\t\"Authorization\": \"key=%s\" % (key),\n\t\t\"Content-Length\": str(len(data)),\n\t}\n\trequest = Request(get_manager().get_post_url(\"GCM\", applicat... | """
Firebase Cloud Messaging
Previously known as GCM / C2DM
Documentation is available on the Firebase Developer website:
https://firebase.google.com/docs/cloud-messaging/
"""
import json
from django.core.exceptions import ImproperlyConfigured
from .compat import Request, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .models import GCMDevice
# Valid keys for FCM messages. Reference:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref
FCM_TARGETS_KEYS = [
"to", "condition", "notification_key"
]
FCM_OPTIONS_KEYS = [
"collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
"restricted_package_name", "dry_run"
]
FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
"title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
"body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args", "android_channel_id"
]
class GCMError(NotificationError):
pass
def _chunks(l, n):
"""
Yield successive chunks from list \a l with a minimum size \a n
"""
for i in range(0, len(l), n):
yield l[i:i + n]
def _gcm_send(data, content_type, application_id):
key = get_manager().get_gcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("GCM", application_id)
).read().decode("utf-8")
def _fcm_send(data, content_type, application_id):
key = get_manager().get_fcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("FCM", application_id)
).read().decode("utf-8")
def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
response = response_data
if response.get("failure") or response.get("canonical_ids"):
ids_to_remove, old_new_ids = [], []
throw_error = False
for index, result in enumerate(response["results"]):
error = result.get("error")
if error:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
# If error is NotRegistered or InvalidRegistration, then we will deactivate devices
# because this registration ID is no more valid and can't be used to send messages,
# otherwise raise error
if error in ("NotRegistered", "InvalidRegistration"):
ids_to_remove.append(registration_ids[index])
else:
throw_error = True
result["original_registration_id"] = registration_ids[index]
# If registration_id is set, replace the original ID with the new value (canonical ID)
# in your server database. Note that the original ID is not part of the result, you need
# to obtain it from the list of registration_ids in the request (using the same index).
new_id = result.get("registration_id")
if new_id:
old_new_ids.append((registration_ids[index], new_id))
if ids_to_remove:
removed = GCMDevice.objects.filter(
registration_id__in=ids_to_remove, cloud_message_type=cloud_type
)
removed.update(active=False)
for old_id, new_id in old_new_ids:
_cm_handle_canonical_id(new_id, old_id, cloud_type)
if throw_error:
raise GCMError(response)
return response
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
"""
Handle situation when FCM server response contains canonical ID
"""
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_id).update(registration_id=canonical_id)
def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
"""
Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
can be a list or a single string. This will send the notification as json data.
A reference of extra keyword arguments sent to the server is available here:
https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
"""
if cloud_type in ("FCM", "GCM"):
max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
# Checks for valid recipient
if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
return
# Bundles the registration_ids in an list if only one is sent
if not isinstance(registration_ids, list):
registration_ids = [registration_ids] if registration_ids else None
# FCM only allows up to 1000 reg ids per bulk message
# https://firebase.google.com/docs/cloud-messaging/server#http-request
if registration_ids:
ret = []
for chunk in _chunks(registration_ids, max_recipients):
ret.append(_cm_send_request(
chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
))
return ret[0] if len(ret) == 1 else ret
else:
return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs)
send_bulk_message = send_message
|
jazzband/django-push-notifications | push_notifications/gcm.py | _cm_handle_canonical_id | python | def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_id).update(registration_id=canonical_id) | Handle situation when FCM server response contains canonical ID | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/gcm.py#L167-L175 | null | """
Firebase Cloud Messaging
Previously known as GCM / C2DM
Documentation is available on the Firebase Developer website:
https://firebase.google.com/docs/cloud-messaging/
"""
import json
from django.core.exceptions import ImproperlyConfigured
from .compat import Request, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .models import GCMDevice
# Valid keys for FCM messages. Reference:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref
FCM_TARGETS_KEYS = [
"to", "condition", "notification_key"
]
FCM_OPTIONS_KEYS = [
"collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
"restricted_package_name", "dry_run"
]
FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
"title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
"body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args", "android_channel_id"
]
class GCMError(NotificationError):
pass
def _chunks(l, n):
"""
Yield successive chunks from list \a l with a minimum size \a n
"""
for i in range(0, len(l), n):
yield l[i:i + n]
def _gcm_send(data, content_type, application_id):
key = get_manager().get_gcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("GCM", application_id)
).read().decode("utf-8")
def _fcm_send(data, content_type, application_id):
key = get_manager().get_fcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("FCM", application_id)
).read().decode("utf-8")
def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
response = response_data
if response.get("failure") or response.get("canonical_ids"):
ids_to_remove, old_new_ids = [], []
throw_error = False
for index, result in enumerate(response["results"]):
error = result.get("error")
if error:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
# If error is NotRegistered or InvalidRegistration, then we will deactivate devices
# because this registration ID is no more valid and can't be used to send messages,
# otherwise raise error
if error in ("NotRegistered", "InvalidRegistration"):
ids_to_remove.append(registration_ids[index])
else:
throw_error = True
result["original_registration_id"] = registration_ids[index]
# If registration_id is set, replace the original ID with the new value (canonical ID)
# in your server database. Note that the original ID is not part of the result, you need
# to obtain it from the list of registration_ids in the request (using the same index).
new_id = result.get("registration_id")
if new_id:
old_new_ids.append((registration_ids[index], new_id))
if ids_to_remove:
removed = GCMDevice.objects.filter(
registration_id__in=ids_to_remove, cloud_message_type=cloud_type
)
removed.update(active=False)
for old_id, new_id in old_new_ids:
_cm_handle_canonical_id(new_id, old_id, cloud_type)
if throw_error:
raise GCMError(response)
return response
def _cm_send_request(
registration_ids, data, cloud_type="GCM", application_id=None,
use_fcm_notifications=True, **kwargs
):
"""
Sends a FCM or GCM notification to one or more registration_ids as json data.
The registration_ids needs to be a list.
"""
payload = {"registration_ids": registration_ids} if registration_ids else {}
data = data.copy()
# If using FCM, optionnally autodiscovers notification related keys
# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
if cloud_type == "FCM" and use_fcm_notifications:
notification_payload = {}
if "message" in data:
notification_payload["body"] = data.pop("message", None)
for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
value_from_extra = data.pop(key, None)
if value_from_extra:
notification_payload[key] = value_from_extra
value_from_kwargs = kwargs.pop(key, None)
if value_from_kwargs:
notification_payload[key] = value_from_kwargs
if notification_payload:
payload["notification"] = notification_payload
if data:
payload["data"] = data
# Attach any additional non falsy keyword args (targets, options)
# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
payload.update({
k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
})
# Sort the keys for deterministic output (useful for tests)
json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
# Sends requests and handles the response
if cloud_type == "GCM":
response = json.loads(_gcm_send(
json_payload, "application/json", application_id=application_id
))
elif cloud_type == "FCM":
response = json.loads(_fcm_send(
json_payload, "application/json", application_id=application_id
))
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
return _cm_handle_response(registration_ids, response, cloud_type, application_id)
def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
"""
Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
can be a list or a single string. This will send the notification as json data.
A reference of extra keyword arguments sent to the server is available here:
https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
"""
if cloud_type in ("FCM", "GCM"):
max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
# Checks for valid recipient
if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
return
# Bundles the registration_ids in an list if only one is sent
if not isinstance(registration_ids, list):
registration_ids = [registration_ids] if registration_ids else None
# FCM only allows up to 1000 reg ids per bulk message
# https://firebase.google.com/docs/cloud-messaging/server#http-request
if registration_ids:
ret = []
for chunk in _chunks(registration_ids, max_recipients):
ret.append(_cm_send_request(
chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
))
return ret[0] if len(ret) == 1 else ret
else:
return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs)
send_bulk_message = send_message
|
jazzband/django-push-notifications | push_notifications/gcm.py | send_message | python | def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
if cloud_type in ("FCM", "GCM"):
max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
# Checks for valid recipient
if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
return
# Bundles the registration_ids in an list if only one is sent
if not isinstance(registration_ids, list):
registration_ids = [registration_ids] if registration_ids else None
# FCM only allows up to 1000 reg ids per bulk message
# https://firebase.google.com/docs/cloud-messaging/server#http-request
if registration_ids:
ret = []
for chunk in _chunks(registration_ids, max_recipients):
ret.append(_cm_send_request(
chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
))
return ret[0] if len(ret) == 1 else ret
else:
return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs) | Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
can be a list or a single string. This will send the notification as json data.
A reference of extra keyword arguments sent to the server is available here:
https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1 | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/gcm.py#L178-L209 | [
"def get_manager(reload=False):\n\tglobal manager\n\n\tif not manager or reload is True:\n\t\tmanager = import_string(SETTINGS[\"CONFIG\"])()\n\n\treturn manager\n",
"def _chunks(l, n):\n\t\"\"\"\n\tYield successive chunks from list \\a l with a minimum size \\a n\n\t\"\"\"\n\tfor i in range(0, len(l), n):\n\t\ty... | """
Firebase Cloud Messaging
Previously known as GCM / C2DM
Documentation is available on the Firebase Developer website:
https://firebase.google.com/docs/cloud-messaging/
"""
import json
from django.core.exceptions import ImproperlyConfigured
from .compat import Request, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .models import GCMDevice
# Valid keys for FCM messages. Reference:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref
FCM_TARGETS_KEYS = [
"to", "condition", "notification_key"
]
FCM_OPTIONS_KEYS = [
"collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
"restricted_package_name", "dry_run"
]
FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
"title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
"body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args", "android_channel_id"
]
class GCMError(NotificationError):
pass
def _chunks(l, n):
"""
Yield successive chunks from list \a l with a minimum size \a n
"""
for i in range(0, len(l), n):
yield l[i:i + n]
def _gcm_send(data, content_type, application_id):
key = get_manager().get_gcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("GCM", application_id)
).read().decode("utf-8")
def _fcm_send(data, content_type, application_id):
key = get_manager().get_fcm_api_key(application_id)
headers = {
"Content-Type": content_type,
"Authorization": "key=%s" % (key),
"Content-Length": str(len(data)),
}
request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
return urlopen(
request, timeout=get_manager().get_error_timeout("FCM", application_id)
).read().decode("utf-8")
def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
response = response_data
if response.get("failure") or response.get("canonical_ids"):
ids_to_remove, old_new_ids = [], []
throw_error = False
for index, result in enumerate(response["results"]):
error = result.get("error")
if error:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
# If error is NotRegistered or InvalidRegistration, then we will deactivate devices
# because this registration ID is no more valid and can't be used to send messages,
# otherwise raise error
if error in ("NotRegistered", "InvalidRegistration"):
ids_to_remove.append(registration_ids[index])
else:
throw_error = True
result["original_registration_id"] = registration_ids[index]
# If registration_id is set, replace the original ID with the new value (canonical ID)
# in your server database. Note that the original ID is not part of the result, you need
# to obtain it from the list of registration_ids in the request (using the same index).
new_id = result.get("registration_id")
if new_id:
old_new_ids.append((registration_ids[index], new_id))
if ids_to_remove:
removed = GCMDevice.objects.filter(
registration_id__in=ids_to_remove, cloud_message_type=cloud_type
)
removed.update(active=False)
for old_id, new_id in old_new_ids:
_cm_handle_canonical_id(new_id, old_id, cloud_type)
if throw_error:
raise GCMError(response)
return response
def _cm_send_request(
registration_ids, data, cloud_type="GCM", application_id=None,
use_fcm_notifications=True, **kwargs
):
"""
Sends a FCM or GCM notification to one or more registration_ids as json data.
The registration_ids needs to be a list.
"""
payload = {"registration_ids": registration_ids} if registration_ids else {}
data = data.copy()
# If using FCM, optionnally autodiscovers notification related keys
# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
if cloud_type == "FCM" and use_fcm_notifications:
notification_payload = {}
if "message" in data:
notification_payload["body"] = data.pop("message", None)
for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
value_from_extra = data.pop(key, None)
if value_from_extra:
notification_payload[key] = value_from_extra
value_from_kwargs = kwargs.pop(key, None)
if value_from_kwargs:
notification_payload[key] = value_from_kwargs
if notification_payload:
payload["notification"] = notification_payload
if data:
payload["data"] = data
# Attach any additional non falsy keyword args (targets, options)
# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
payload.update({
k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
})
# Sort the keys for deterministic output (useful for tests)
json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
# Sends requests and handles the response
if cloud_type == "GCM":
response = json.loads(_gcm_send(
json_payload, "application/json", application_id=application_id
))
elif cloud_type == "FCM":
response = json.loads(_fcm_send(
json_payload, "application/json", application_id=application_id
))
else:
raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
return _cm_handle_response(registration_ids, response, cloud_type, application_id)
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
"""
Handle situation when FCM server response contains canonical ID
"""
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_id).update(registration_id=canonical_id)
send_bulk_message = send_message
|
jazzband/django-push-notifications | push_notifications/conf/legacy.py | LegacyConfig._get_application_settings | python | def _get_application_settings(self, application_id, settings_key, error_message):
if not application_id:
value = SETTINGS.get(settings_key, empty)
if value is empty:
raise ImproperlyConfigured(error_message)
return value
else:
msg = (
"LegacySettings does not support application_id. To enable "
"multiple application support, use push_notifications.conf.AppSettings."
)
raise ImproperlyConfigured(msg) | Legacy behaviour | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/legacy.py#L18-L31 | null | class LegacyConfig(BaseConfig):
def get_gcm_api_key(self, application_id=None):
msg = (
"Set PUSH_NOTIFICATIONS_SETTINGS[\"GCM_API_KEY\"] to send messages through GCM."
)
return self._get_application_settings(application_id, "GCM_API_KEY", msg)
def get_fcm_api_key(self, application_id=None):
msg = (
"Set PUSH_NOTIFICATIONS_SETTINGS[\"FCM_API_KEY\"] to send messages through FCM."
)
return self._get_application_settings(application_id, "FCM_API_KEY", msg)
def get_post_url(self, cloud_type, application_id=None):
key = "{}_POST_URL".format(cloud_type)
msg = (
"Set PUSH_NOTIFICATIONS_SETTINGS[\"{}\"] to send messages through {}.".format(
key, cloud_type
)
)
return self._get_application_settings(application_id, key, msg)
def get_error_timeout(self, cloud_type, application_id=None):
key = "{}_ERROR_TIMEOUT".format(cloud_type)
msg = (
"Set PUSH_NOTIFICATIONS_SETTINGS[\"{}\"] to send messages through {}.".format(
key, cloud_type
)
)
return self._get_application_settings(application_id, key, msg)
def get_max_recipients(self, cloud_type, application_id=None):
key = "{}_MAX_RECIPIENTS".format(cloud_type)
msg = (
"Set PUSH_NOTIFICATIONS_SETTINGS[\"{}\"] to send messages through {}.".format(
key, cloud_type
)
)
return self._get_application_settings(application_id, key, msg)
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(
application_id, "APNS_CERTIFICATE",
"You need to setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
)
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
msg = (
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
raise ImproperlyConfigured(msg)
return r
def get_apns_use_sandbox(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_USE_SANDBOX", msg)
def get_apns_use_alternative_port(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_USE_ALTERNATIVE_PORT", msg)
def get_apns_topic(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_TOPIC", msg)
def get_apns_host(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_HOST", msg)
def get_apns_port(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_PORT", msg)
def get_apns_feedback_host(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_FEEDBACK_HOST", msg)
def get_apns_feedback_port(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "APNS_FEEDBACK_PORT", msg)
def get_wns_package_security_id(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "WNS_PACKAGE_SECURITY_ID", msg)
def get_wns_secret_key(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "WNS_SECRET_KEY", msg)
def get_wp_post_url(self, application_id, browser):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "WP_POST_URL", msg)[browser]
def get_wp_private_key(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "WP_PRIVATE_KEY", msg)
def get_wp_claims(self, application_id=None):
msg = "Setup PUSH_NOTIFICATIONS_SETTINGS properly to send messages"
return self._get_application_settings(application_id, "WP_CLAIMS", msg)
|
jazzband/django-push-notifications | push_notifications/conf/app.py | AppConfig._validate_applications | python | def _validate_applications(self, apps):
for application_id, application_config in apps.items():
self._validate_config(application_id, application_config)
application_config["APPLICATION_ID"] = application_id | Validate the application collection | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L78-L83 | [
"def _validate_config(self, application_id, application_config):\n\tplatform = application_config.get(\"PLATFORM\", None)\n\n\t# platform is not present\n\tif platform is None:\n\t\traise ImproperlyConfigured(\n\t\t\tBAD_PLATFORM.format(\n\t\t\t\tapplication_id=application_id,\n\t\t\t\tcode=\"required\",\n\t\t\t\tp... | class AppConfig(BaseConfig):
"""
Supports any number of push notification enabled applications.
"""
def __init__(self, settings=None):
# supports overriding the settings to be loaded. Will load from ..settings by default.
self._settings = settings or SETTINGS
# initialize APPLICATIONS to an empty collection
self._settings.setdefault("APPLICATIONS", {})
# validate application configurations
self._validate_applications(self._settings["APPLICATIONS"])
def _validate_config(self, application_id, application_config):
platform = application_config.get("PLATFORM", None)
# platform is not present
if platform is None:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="required",
platforms=", ".join(PLATFORMS)
)
)
# platform is not a valid choice from PLATFORMS
if platform not in PLATFORMS:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="invalid",
platforms=", ".join(PLATFORMS)
)
)
validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
if hasattr(self, validate_fn):
getattr(self, validate_fn)(application_id, application_config)
else:
raise ImproperlyConfigured(
UNKNOWN_PLATFORM.format(
platform=platform,
platforms=", ".join(PLATFORMS)
)
)
def _validate_apns_config(self, application_id, application_config):
allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
APNS_OPTIONAL_SETTINGS
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, APNS_REQUIRED_SETTINGS
)
# determine/set optional values
application_config.setdefault("USE_SANDBOX", False)
application_config.setdefault("USE_ALTERNATIVE_PORT", False)
application_config.setdefault("TOPIC", None)
self._validate_apns_certificate(application_config["CERTIFICATE"])
def _validate_apns_certificate(self, certfile):
"""Validate the APNS certificate at startup."""
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (certfile, e)
)
def _validate_fcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + FCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, FCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_gcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + GCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, GCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_wns_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + WNS_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WNS_REQUIRED_SETTINGS
)
application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
def _validate_wp_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + WP_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WP_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", {
"CHROME": "https://fcm.googleapis.com/fcm/send",
"OPERA": "https://fcm.googleapis.com/fcm/send",
"FIREFOX": "https://updates.push.services.mozilla.com/wpush/v2",
})
def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
"""Confirm only allowed settings are present."""
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the setting: {}.".format(
application_config["PLATFORM"], application_id, setting_key
)
)
def _validate_required_settings(
self, application_id, application_config, required_settings
):
"""All required keys must be present"""
for setting_key in required_settings:
if setting_key not in application_config.keys():
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=setting_key
)
)
def _get_application_settings(self, application_id, platform, settings_key):
"""
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value
or raises ImproperlyConfigured.
"""
if not application_id:
conf_cls = "push_notifications.conf.AppConfig"
raise ImproperlyConfigured(
"{} requires the application_id be specified at all times.".format(conf_cls)
)
# verify that the application config exists
app_config = self._settings.get("APPLICATIONS").get(application_id, None)
if app_config is None:
raise ImproperlyConfigured(
"No application configured with application_id: {}.".format(application_id)
)
# fetch a setting for the incorrect type of platform
if app_config.get("PLATFORM") != platform:
raise ImproperlyConfigured(
SETTING_MISMATCH.format(
application_id=application_id,
platform=app_config.get("PLATFORM"),
setting=settings_key
)
)
# finally, try to fetch the setting
if settings_key not in app_config:
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=settings_key
)
)
return app_config.get(settings_key)
def get_gcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "GCM", "API_KEY")
def get_fcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "FCM", "API_KEY")
def get_post_url(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "POST_URL")
def get_error_timeout(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
def get_max_recipients(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
raise ImproperlyConfigured(
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
return r
def get_apns_use_sandbox(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
def get_apns_use_alternative_port(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
def get_apns_topic(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "TOPIC")
def get_wns_package_security_id(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
def get_wns_secret_key(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
def get_wp_post_url(self, application_id, browser):
return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
def get_wp_private_key(self, application_id=None):
return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
def get_wp_claims(self, application_id=None):
return self._get_application_settings(application_id, "WP", "CLAIMS")
|
jazzband/django-push-notifications | push_notifications/conf/app.py | AppConfig._validate_apns_certificate | python | def _validate_apns_certificate(self, certfile):
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (certfile, e)
) | Validate the APNS certificate at startup. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L136-L146 | null | class AppConfig(BaseConfig):
"""
Supports any number of push notification enabled applications.
"""
def __init__(self, settings=None):
# supports overriding the settings to be loaded. Will load from ..settings by default.
self._settings = settings or SETTINGS
# initialize APPLICATIONS to an empty collection
self._settings.setdefault("APPLICATIONS", {})
# validate application configurations
self._validate_applications(self._settings["APPLICATIONS"])
def _validate_applications(self, apps):
"""Validate the application collection"""
for application_id, application_config in apps.items():
self._validate_config(application_id, application_config)
application_config["APPLICATION_ID"] = application_id
def _validate_config(self, application_id, application_config):
platform = application_config.get("PLATFORM", None)
# platform is not present
if platform is None:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="required",
platforms=", ".join(PLATFORMS)
)
)
# platform is not a valid choice from PLATFORMS
if platform not in PLATFORMS:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="invalid",
platforms=", ".join(PLATFORMS)
)
)
validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
if hasattr(self, validate_fn):
getattr(self, validate_fn)(application_id, application_config)
else:
raise ImproperlyConfigured(
UNKNOWN_PLATFORM.format(
platform=platform,
platforms=", ".join(PLATFORMS)
)
)
def _validate_apns_config(self, application_id, application_config):
allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
APNS_OPTIONAL_SETTINGS
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, APNS_REQUIRED_SETTINGS
)
# determine/set optional values
application_config.setdefault("USE_SANDBOX", False)
application_config.setdefault("USE_ALTERNATIVE_PORT", False)
application_config.setdefault("TOPIC", None)
self._validate_apns_certificate(application_config["CERTIFICATE"])
def _validate_fcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + FCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, FCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_gcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + GCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, GCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_wns_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + WNS_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WNS_REQUIRED_SETTINGS
)
application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
def _validate_wp_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + WP_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WP_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", {
"CHROME": "https://fcm.googleapis.com/fcm/send",
"OPERA": "https://fcm.googleapis.com/fcm/send",
"FIREFOX": "https://updates.push.services.mozilla.com/wpush/v2",
})
def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
"""Confirm only allowed settings are present."""
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the setting: {}.".format(
application_config["PLATFORM"], application_id, setting_key
)
)
def _validate_required_settings(
self, application_id, application_config, required_settings
):
"""All required keys must be present"""
for setting_key in required_settings:
if setting_key not in application_config.keys():
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=setting_key
)
)
def _get_application_settings(self, application_id, platform, settings_key):
"""
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value
or raises ImproperlyConfigured.
"""
if not application_id:
conf_cls = "push_notifications.conf.AppConfig"
raise ImproperlyConfigured(
"{} requires the application_id be specified at all times.".format(conf_cls)
)
# verify that the application config exists
app_config = self._settings.get("APPLICATIONS").get(application_id, None)
if app_config is None:
raise ImproperlyConfigured(
"No application configured with application_id: {}.".format(application_id)
)
# fetch a setting for the incorrect type of platform
if app_config.get("PLATFORM") != platform:
raise ImproperlyConfigured(
SETTING_MISMATCH.format(
application_id=application_id,
platform=app_config.get("PLATFORM"),
setting=settings_key
)
)
# finally, try to fetch the setting
if settings_key not in app_config:
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=settings_key
)
)
return app_config.get(settings_key)
def get_gcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "GCM", "API_KEY")
def get_fcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "FCM", "API_KEY")
def get_post_url(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "POST_URL")
def get_error_timeout(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
def get_max_recipients(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
raise ImproperlyConfigured(
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
return r
def get_apns_use_sandbox(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
def get_apns_use_alternative_port(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
def get_apns_topic(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "TOPIC")
def get_wns_package_security_id(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
def get_wns_secret_key(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
def get_wp_post_url(self, application_id, browser):
return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
def get_wp_private_key(self, application_id=None):
return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
def get_wp_claims(self, application_id=None):
return self._get_application_settings(application_id, "WP", "CLAIMS")
|
jazzband/django-push-notifications | push_notifications/conf/app.py | AppConfig._validate_allowed_settings | python | def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the setting: {}.".format(
application_config["PLATFORM"], application_id, setting_key
)
) | Confirm only allowed settings are present. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L203-L212 | null | class AppConfig(BaseConfig):
"""
Supports any number of push notification enabled applications.
"""
def __init__(self, settings=None):
# supports overriding the settings to be loaded. Will load from ..settings by default.
self._settings = settings or SETTINGS
# initialize APPLICATIONS to an empty collection
self._settings.setdefault("APPLICATIONS", {})
# validate application configurations
self._validate_applications(self._settings["APPLICATIONS"])
def _validate_applications(self, apps):
"""Validate the application collection"""
for application_id, application_config in apps.items():
self._validate_config(application_id, application_config)
application_config["APPLICATION_ID"] = application_id
def _validate_config(self, application_id, application_config):
platform = application_config.get("PLATFORM", None)
# platform is not present
if platform is None:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="required",
platforms=", ".join(PLATFORMS)
)
)
# platform is not a valid choice from PLATFORMS
if platform not in PLATFORMS:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="invalid",
platforms=", ".join(PLATFORMS)
)
)
validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
if hasattr(self, validate_fn):
getattr(self, validate_fn)(application_id, application_config)
else:
raise ImproperlyConfigured(
UNKNOWN_PLATFORM.format(
platform=platform,
platforms=", ".join(PLATFORMS)
)
)
def _validate_apns_config(self, application_id, application_config):
allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
APNS_OPTIONAL_SETTINGS
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, APNS_REQUIRED_SETTINGS
)
# determine/set optional values
application_config.setdefault("USE_SANDBOX", False)
application_config.setdefault("USE_ALTERNATIVE_PORT", False)
application_config.setdefault("TOPIC", None)
self._validate_apns_certificate(application_config["CERTIFICATE"])
def _validate_apns_certificate(self, certfile):
"""Validate the APNS certificate at startup."""
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (certfile, e)
)
def _validate_fcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + FCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, FCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_gcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + GCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, GCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_wns_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + WNS_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WNS_REQUIRED_SETTINGS
)
application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
def _validate_wp_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + WP_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WP_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", {
"CHROME": "https://fcm.googleapis.com/fcm/send",
"OPERA": "https://fcm.googleapis.com/fcm/send",
"FIREFOX": "https://updates.push.services.mozilla.com/wpush/v2",
})
def _validate_required_settings(
self, application_id, application_config, required_settings
):
"""All required keys must be present"""
for setting_key in required_settings:
if setting_key not in application_config.keys():
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=setting_key
)
)
def _get_application_settings(self, application_id, platform, settings_key):
"""
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value
or raises ImproperlyConfigured.
"""
if not application_id:
conf_cls = "push_notifications.conf.AppConfig"
raise ImproperlyConfigured(
"{} requires the application_id be specified at all times.".format(conf_cls)
)
# verify that the application config exists
app_config = self._settings.get("APPLICATIONS").get(application_id, None)
if app_config is None:
raise ImproperlyConfigured(
"No application configured with application_id: {}.".format(application_id)
)
# fetch a setting for the incorrect type of platform
if app_config.get("PLATFORM") != platform:
raise ImproperlyConfigured(
SETTING_MISMATCH.format(
application_id=application_id,
platform=app_config.get("PLATFORM"),
setting=settings_key
)
)
# finally, try to fetch the setting
if settings_key not in app_config:
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=settings_key
)
)
return app_config.get(settings_key)
def get_gcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "GCM", "API_KEY")
def get_fcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "FCM", "API_KEY")
def get_post_url(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "POST_URL")
def get_error_timeout(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
def get_max_recipients(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
raise ImproperlyConfigured(
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
return r
def get_apns_use_sandbox(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
def get_apns_use_alternative_port(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
def get_apns_topic(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "TOPIC")
def get_wns_package_security_id(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
def get_wns_secret_key(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
def get_wp_post_url(self, application_id, browser):
return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
def get_wp_private_key(self, application_id=None):
return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
def get_wp_claims(self, application_id=None):
return self._get_application_settings(application_id, "WP", "CLAIMS")
|
jazzband/django-push-notifications | push_notifications/conf/app.py | AppConfig._validate_required_settings | python | def _validate_required_settings(
self, application_id, application_config, required_settings
):
for setting_key in required_settings:
if setting_key not in application_config.keys():
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=setting_key
)
) | All required keys must be present | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L214-L225 | null | class AppConfig(BaseConfig):
"""
Supports any number of push notification enabled applications.
"""
def __init__(self, settings=None):
# supports overriding the settings to be loaded. Will load from ..settings by default.
self._settings = settings or SETTINGS
# initialize APPLICATIONS to an empty collection
self._settings.setdefault("APPLICATIONS", {})
# validate application configurations
self._validate_applications(self._settings["APPLICATIONS"])
def _validate_applications(self, apps):
"""Validate the application collection"""
for application_id, application_config in apps.items():
self._validate_config(application_id, application_config)
application_config["APPLICATION_ID"] = application_id
def _validate_config(self, application_id, application_config):
platform = application_config.get("PLATFORM", None)
# platform is not present
if platform is None:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="required",
platforms=", ".join(PLATFORMS)
)
)
# platform is not a valid choice from PLATFORMS
if platform not in PLATFORMS:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="invalid",
platforms=", ".join(PLATFORMS)
)
)
validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
if hasattr(self, validate_fn):
getattr(self, validate_fn)(application_id, application_config)
else:
raise ImproperlyConfigured(
UNKNOWN_PLATFORM.format(
platform=platform,
platforms=", ".join(PLATFORMS)
)
)
def _validate_apns_config(self, application_id, application_config):
allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
APNS_OPTIONAL_SETTINGS
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, APNS_REQUIRED_SETTINGS
)
# determine/set optional values
application_config.setdefault("USE_SANDBOX", False)
application_config.setdefault("USE_ALTERNATIVE_PORT", False)
application_config.setdefault("TOPIC", None)
self._validate_apns_certificate(application_config["CERTIFICATE"])
def _validate_apns_certificate(self, certfile):
"""Validate the APNS certificate at startup."""
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (certfile, e)
)
def _validate_fcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + FCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, FCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_gcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + GCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, GCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_wns_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + WNS_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WNS_REQUIRED_SETTINGS
)
application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
def _validate_wp_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + WP_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WP_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", {
"CHROME": "https://fcm.googleapis.com/fcm/send",
"OPERA": "https://fcm.googleapis.com/fcm/send",
"FIREFOX": "https://updates.push.services.mozilla.com/wpush/v2",
})
def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
"""Confirm only allowed settings are present."""
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the setting: {}.".format(
application_config["PLATFORM"], application_id, setting_key
)
)
def _get_application_settings(self, application_id, platform, settings_key):
"""
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value
or raises ImproperlyConfigured.
"""
if not application_id:
conf_cls = "push_notifications.conf.AppConfig"
raise ImproperlyConfigured(
"{} requires the application_id be specified at all times.".format(conf_cls)
)
# verify that the application config exists
app_config = self._settings.get("APPLICATIONS").get(application_id, None)
if app_config is None:
raise ImproperlyConfigured(
"No application configured with application_id: {}.".format(application_id)
)
# fetch a setting for the incorrect type of platform
if app_config.get("PLATFORM") != platform:
raise ImproperlyConfigured(
SETTING_MISMATCH.format(
application_id=application_id,
platform=app_config.get("PLATFORM"),
setting=settings_key
)
)
# finally, try to fetch the setting
if settings_key not in app_config:
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=settings_key
)
)
return app_config.get(settings_key)
def get_gcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "GCM", "API_KEY")
def get_fcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "FCM", "API_KEY")
def get_post_url(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "POST_URL")
def get_error_timeout(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
def get_max_recipients(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
raise ImproperlyConfigured(
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
return r
def get_apns_use_sandbox(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
def get_apns_use_alternative_port(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
def get_apns_topic(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "TOPIC")
def get_wns_package_security_id(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
def get_wns_secret_key(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
def get_wp_post_url(self, application_id, browser):
return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
def get_wp_private_key(self, application_id=None):
return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
def get_wp_claims(self, application_id=None):
return self._get_application_settings(application_id, "WP", "CLAIMS")
|
jazzband/django-push-notifications | push_notifications/conf/app.py | AppConfig._get_application_settings | python | def _get_application_settings(self, application_id, platform, settings_key):
if not application_id:
conf_cls = "push_notifications.conf.AppConfig"
raise ImproperlyConfigured(
"{} requires the application_id be specified at all times.".format(conf_cls)
)
# verify that the application config exists
app_config = self._settings.get("APPLICATIONS").get(application_id, None)
if app_config is None:
raise ImproperlyConfigured(
"No application configured with application_id: {}.".format(application_id)
)
# fetch a setting for the incorrect type of platform
if app_config.get("PLATFORM") != platform:
raise ImproperlyConfigured(
SETTING_MISMATCH.format(
application_id=application_id,
platform=app_config.get("PLATFORM"),
setting=settings_key
)
)
# finally, try to fetch the setting
if settings_key not in app_config:
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=settings_key
)
)
return app_config.get(settings_key) | Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value
or raises ImproperlyConfigured. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L227-L264 | null | class AppConfig(BaseConfig):
"""
Supports any number of push notification enabled applications.
"""
def __init__(self, settings=None):
# supports overriding the settings to be loaded. Will load from ..settings by default.
self._settings = settings or SETTINGS
# initialize APPLICATIONS to an empty collection
self._settings.setdefault("APPLICATIONS", {})
# validate application configurations
self._validate_applications(self._settings["APPLICATIONS"])
def _validate_applications(self, apps):
"""Validate the application collection"""
for application_id, application_config in apps.items():
self._validate_config(application_id, application_config)
application_config["APPLICATION_ID"] = application_id
def _validate_config(self, application_id, application_config):
platform = application_config.get("PLATFORM", None)
# platform is not present
if platform is None:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="required",
platforms=", ".join(PLATFORMS)
)
)
# platform is not a valid choice from PLATFORMS
if platform not in PLATFORMS:
raise ImproperlyConfigured(
BAD_PLATFORM.format(
application_id=application_id,
code="invalid",
platforms=", ".join(PLATFORMS)
)
)
validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
if hasattr(self, validate_fn):
getattr(self, validate_fn)(application_id, application_config)
else:
raise ImproperlyConfigured(
UNKNOWN_PLATFORM.format(
platform=platform,
platforms=", ".join(PLATFORMS)
)
)
def _validate_apns_config(self, application_id, application_config):
allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
APNS_OPTIONAL_SETTINGS
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, APNS_REQUIRED_SETTINGS
)
# determine/set optional values
application_config.setdefault("USE_SANDBOX", False)
application_config.setdefault("USE_ALTERNATIVE_PORT", False)
application_config.setdefault("TOPIC", None)
self._validate_apns_certificate(application_config["CERTIFICATE"])
def _validate_apns_certificate(self, certfile):
"""Validate the APNS certificate at startup."""
try:
with open(certfile, "r") as f:
content = f.read()
check_apns_certificate(content)
except Exception as e:
raise ImproperlyConfigured(
"The APNS certificate file at %r is not readable: %s" % (certfile, e)
)
def _validate_fcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + FCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, FCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_gcm_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + GCM_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, GCM_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
application_config.setdefault("MAX_RECIPIENTS", 1000)
application_config.setdefault("ERROR_TIMEOUT", None)
def _validate_wns_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + WNS_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WNS_REQUIRED_SETTINGS
)
application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
def _validate_wp_config(self, application_id, application_config):
allowed = (
REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + WP_OPTIONAL_SETTINGS
)
self._validate_allowed_settings(application_id, application_config, allowed)
self._validate_required_settings(
application_id, application_config, WP_REQUIRED_SETTINGS
)
application_config.setdefault("POST_URL", {
"CHROME": "https://fcm.googleapis.com/fcm/send",
"OPERA": "https://fcm.googleapis.com/fcm/send",
"FIREFOX": "https://updates.push.services.mozilla.com/wpush/v2",
})
def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
"""Confirm only allowed settings are present."""
for setting_key in application_config.keys():
if setting_key not in allowed_settings:
raise ImproperlyConfigured(
"Platform {}, app {} does not support the setting: {}.".format(
application_config["PLATFORM"], application_id, setting_key
)
)
def _validate_required_settings(
self, application_id, application_config, required_settings
):
"""All required keys must be present"""
for setting_key in required_settings:
if setting_key not in application_config.keys():
raise ImproperlyConfigured(
MISSING_SETTING.format(
application_id=application_id, setting=setting_key
)
)
def get_gcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "GCM", "API_KEY")
def get_fcm_api_key(self, application_id=None):
return self._get_application_settings(application_id, "FCM", "API_KEY")
def get_post_url(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "POST_URL")
def get_error_timeout(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
def get_max_recipients(self, cloud_type, application_id=None):
return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
def get_apns_certificate(self, application_id=None):
r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
if not isinstance(r, string_types):
# probably the (Django) file, and file path should be got
if hasattr(r, "path"):
return r.path
elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
return r["path"]
else:
raise ImproperlyConfigured(
"The APNS certificate settings value should be a string, or "
"should have a 'path' attribute or key"
)
return r
def get_apns_use_sandbox(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
def get_apns_use_alternative_port(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
def get_apns_topic(self, application_id=None):
return self._get_application_settings(application_id, "APNS", "TOPIC")
def get_wns_package_security_id(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
def get_wns_secret_key(self, application_id=None):
return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
def get_wp_post_url(self, application_id, browser):
return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
def get_wp_private_key(self, application_id=None):
return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
def get_wp_claims(self, application_id=None):
return self._get_application_settings(application_id, "WP", "CLAIMS")
|
jazzband/django-push-notifications | push_notifications/admin.py | DeviceAdmin.send_messages | python | def send_messages(self, request, queryset, bulk=False):
ret = []
errors = []
r = ""
for device in queryset:
try:
if bulk:
r = queryset.send_message("Test bulk notification")
else:
r = device.send_message("Test single notification")
if r:
ret.append(r)
except GCMError as e:
errors.append(str(e))
except APNSServerError as e:
errors.append(e.status)
except WebPushError as e:
errors.append(e.message)
if bulk:
break
# Because NotRegistered and InvalidRegistration do not throw GCMError
# catch them here to display error msg.
if not bulk:
for r in ret:
if "error" in r["results"][0]:
errors.append(r["results"][0]["error"])
else:
try:
errors = [r["error"] for r in ret[0][0]["results"] if "error" in r]
except TypeError:
for entry in ret[0][0]:
errors = errors + [r["error"] for r in entry["results"] if "error" in r]
except IndexError:
pass
if errors:
self.message_user(
request, _("Some messages could not be processed: %r" % (", ".join(errors))),
level=messages.ERROR
)
if ret:
if bulk:
# When the queryset exceeds the max_recipients value, the
# send_message method returns a list of dicts, one per chunk
try:
success = ret[0][0]["success"]
except TypeError:
success = 0
for entry in ret[0][0]:
success = success + entry["success"]
if success == 0:
return
elif len(errors) == len(ret):
return
if errors:
msg = _("Some messages were sent: %s" % (ret))
else:
msg = _("All messages were sent: %s" % (ret))
self.message_user(request, msg) | Provides error handling for DeviceAdmin send_message and send_bulk_message methods. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/admin.py#L26-L89 | null | class DeviceAdmin(admin.ModelAdmin):
list_display = ("__str__", "device_id", "user", "active", "date_created")
list_filter = ("active",)
actions = ("send_message", "send_bulk_message", "enable", "disable")
raw_id_fields = ("user",)
if hasattr(User, "USERNAME_FIELD"):
search_fields = ("name", "device_id", "user__%s" % (User.USERNAME_FIELD))
else:
search_fields = ("name", "device_id")
def send_message(self, request, queryset):
self.send_messages(request, queryset)
send_message.short_description = _("Send test message")
def send_bulk_message(self, request, queryset):
self.send_messages(request, queryset, True)
send_bulk_message.short_description = _("Send test message in bulk")
def enable(self, request, queryset):
queryset.update(active=True)
enable.short_description = _("Enable selected devices")
def disable(self, request, queryset):
queryset.update(active=False)
disable.short_description = _("Disable selected devices")
|
jazzband/django-push-notifications | push_notifications/wns.py | _wns_authenticate | python | def _wns_authenticate(scope="notify.windows.com", application_id=None):
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token | Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L31-L82 | null | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | _wns_send | python | def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8") | Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return: | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L85-L139 | [
"def _wns_authenticate(scope=\"notify.windows.com\", application_id=None):\n\t\"\"\"\n\tRequests an Access token for WNS communication.\n\n\t:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}\n\t\"\"\"\n\tclient_id = get_manager().get_wns_package_security_id(application_id)\n\tclien... | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | _wns_prepare_toast | python | def _wns_prepare_toast(data, **kwargs):
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root) | Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L142-L169 | null | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | wns_send_message | python | def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
) | Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L172-L234 | [
"def dict_to_xml_schema(data):\n\t\"\"\"\n\tInput a dictionary to be converted to xml. There should be only one key at\n\tthe top level. The value must be a dict with (required) `children` key and\n\t(optional) `attrs` key. This will be called the `sub-element dictionary`.\n\n\tThe `attrs` value must be a dictionar... | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | wns_send_bulk_message | python | def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res | WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification. | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L237-L256 | [
"def wns_send_message(\n\turi, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs\n):\n\t\"\"\"\n\tSends a notification request to WNS.\n\tThere are four notification types that WNS can send: toast, tile, badge and raw.\n\tToast, tile, and badge can all be customized to use different\n\ttempl... | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | dict_to_xml_schema | python | def dict_to_xml_schema(data):
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root | Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L259-L322 | [
"def _add_element_attrs(elem, attrs):\n\t\"\"\"\n\tAdd attributes to the given element.\n\n\t:param elem: ElementTree.Element: The element the attributes are being added to.\n\t:param attrs: dict: A dictionary of attributes. e.g.:\n\t\t{\"attribute1\": \"value\", \"attribute2\": \"another\"}\n\t:return: ElementTree... | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | _add_sub_elements_from_dict | python | def _add_sub_elements_from_dict(parent, sub_dict):
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children | Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}} | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L325-L357 | [
"def _add_element_attrs(elem, attrs):\n\t\"\"\"\n\tAdd attributes to the given element.\n\n\t:param elem: ElementTree.Element: The element the attributes are being added to.\n\t:param attrs: dict: A dictionary of attributes. e.g.:\n\t\t{\"attribute1\": \"value\", \"attribute2\": \"another\"}\n\t:return: ElementTree... | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_element_attrs(elem, attrs):
"""
Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element
"""
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem
|
jazzband/django-push-notifications | push_notifications/wns.py | _add_element_attrs | python | def _add_element_attrs(elem, attrs):
for attr, value in attrs.items():
elem.attrib[attr] = value
return elem | Add attributes to the given element.
:param elem: ElementTree.Element: The element the attributes are being added to.
:param attrs: dict: A dictionary of attributes. e.g.:
{"attribute1": "value", "attribute2": "another"}
:return: ElementTree.Element | train | https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L360-L371 | null | """
Windows Notification Service
Documentation is available on the Windows Dev Center:
https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
"""
import json
import xml.etree.ElementTree as ET
from django.core.exceptions import ImproperlyConfigured
from .compat import HTTPError, Request, urlencode, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
class WNSError(NotificationError):
pass
class WNSAuthenticationError(WNSError):
pass
class WNSNotificationResponseError(WNSError):
pass
def _wns_authenticate(scope="notify.windows.com", application_id=None):
"""
Requests an Access token for WNS communication.
:return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
"""
client_id = get_manager().get_wns_package_security_id(application_id)
client_secret = get_manager().get_wns_secret_key(application_id)
if not client_id:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
)
if not client_secret:
raise ImproperlyConfigured(
'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
params = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
data = urlencode(params).encode("utf-8")
request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
# One of your settings is probably jacked up.
# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
raise err
oauth_data = response.read().decode("utf-8")
try:
oauth_data = json.loads(oauth_data)
except Exception:
# Upstream WNS issue
raise WNSAuthenticationError("Received invalid JSON data from WNS.")
access_token = oauth_data.get("access_token")
if not access_token:
# Upstream WNS issue
raise WNSAuthenticationError("Access token missing from WNS response.")
return access_token
def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
"""
Sends a notification data and authentication to WNS.
:param uri: str: The device's unique notification URI
:param data: dict: The notification data to be sent.
:return:
"""
access_token = _wns_authenticate(application_id=application_id)
content_type = "text/xml"
if wns_type == "wns/raw":
content_type = "application/octet-stream"
headers = {
# content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
"Content-Type": content_type,
"Authorization": "Bearer %s" % (access_token),
"X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
}
if type(data) is str:
data = data.encode("utf-8")
request = Request(uri, data, headers)
# A lot of things can happen, let them know which one.
try:
response = urlopen(request)
except HTTPError as err:
if err.code == 400:
msg = "One or more headers were specified incorrectly or conflict with another header."
elif err.code == 401:
msg = "The cloud service did not present a valid authentication ticket."
elif err.code == 403:
msg = "The cloud service is not authorized to send a notification to this URI."
elif err.code == 404:
msg = "The channel URI is not valid or is not recognized by WNS."
elif err.code == 405:
msg = "Invalid method. Only POST or DELETE is allowed."
elif err.code == 406:
msg = "The cloud service exceeded its throttle limit"
elif err.code == 410:
msg = "The channel expired."
elif err.code == 413:
msg = "The notification payload exceeds the 500 byte limit."
elif err.code == 500:
msg = "An internal failure caused notification delivery to fail."
elif err.code == 503:
msg = "The server is currently unavailable."
else:
raise err
raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
return response.read().decode("utf-8")
def _wns_prepare_toast(data, **kwargs):
"""
Creates the xml tree for a `toast` notification
:param data: dict: The notification data to be converted to an xml tree.
{
"text": ["Title text", "Message Text", "Another message!"],
"image": ["src1", "src2"],
}
:return: str
"""
root = ET.Element("toast")
visual = ET.SubElement(root, "visual")
binding = ET.SubElement(visual, "binding")
binding.attrib["template"] = kwargs.pop("template", "ToastText01")
if "text" in data:
for count, item in enumerate(data["text"], start=1):
elem = ET.SubElement(binding, "text")
elem.text = item
elem.attrib["id"] = str(count)
if "image" in data:
for count, item in enumerate(data["image"], start=1):
elem = ET.SubElement(binding, "img")
elem.attrib["src"] = item
elem.attrib["id"] = str(count)
return ET.tostring(root)
def wns_send_message(
uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
Sends a notification request to WNS.
There are four notification types that WNS can send: toast, tile, badge and raw.
Toast, tile, and badge can all be customized to use different
templates/icons/sounds/launch params/etc.
See docs for more information:
https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
There are multiple ways to input notification data:
1. The simplest and least custom notification to send is to just pass a string
to `message`. This will create a toast notification with one text element. e.g.:
"This is my notification title"
2. You can also pass a dictionary to `message`: it can only contain one or both
keys: ["text", "image"]. The value of each key must be a list with the text and
src respectively. e.g.:
{
"text": ["text1", "text2"],
"image": ["src1", "src2"],
}
3. Passing a dictionary to `xml_data` will create one of three types of
notifications depending on the dictionary data (toast, tile, badge).
See `dict_to_xml_schema` docs for more information on dictionary formatting.
4. Passing a value to `raw_data` will create a `raw` notification and send the
input data as is.
:param uri: str: The device's unique notification uri.
:param message: str|dict: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
# Create a simple toast notification
if message:
wns_type = "wns/toast"
if isinstance(message, str):
message = {
"text": [message, ],
}
prepared_data = _wns_prepare_toast(data=message, **kwargs)
# Create a toast/tile/badge notification from a dictionary
elif xml_data:
xml = dict_to_xml_schema(xml_data)
wns_type = "wns/%s" % xml.tag
prepared_data = ET.tostring(xml)
# Create a raw notification
elif raw_data:
wns_type = "wns/raw"
prepared_data = raw_data
else:
raise TypeError(
"At least one of the following parameters must be set:"
"`message`, `xml_data`, `raw_data`"
)
return _wns_send(
uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
)
def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
:param xml_data: dict: A dictionary containing data to be converted to an xml tree.
:param raw_data: str: Data to be sent via a `raw` notification.
"""
res = []
if uri_list:
for uri in uri_list:
r = wns_send_message(
uri=uri, message=message, xml_data=xml_data,
raw_data=raw_data, application_id=application_id, **kwargs
)
res.append(r)
return res
def dict_to_xml_schema(data):
"""
Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag as attributes. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
would result in:
<example key1="value1" key2="value2"></example>
If the value is a dict it must contain one or more keys which will be used
as the sub-element names. Each sub-element must have a value of a sub-element
dictionary(see above) or a list of sub-element dictionaries.
If the value is not a dict, it will be the value of the element.
If the value is a list, multiple elements of the same tag will be created
from each sub-element dict in the list.
:param data: dict: Used to create an XML tree. e.g.:
example_data = {
"toast": {
"attrs": {
"launch": "param",
"duration": "short",
},
"children": {
"visual": {
"children": {
"binding": {
"attrs": {"template": "ToastText01"},
"children": {
"text": [
{
"attrs": {"id": "1"},
"children": "text1",
},
{
"attrs": {"id": "2"},
"children": "text2",
},
],
},
},
},
},
},
},
}
:return: ElementTree.Element
"""
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
},
...
}}
"""
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
else:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(sub_element, children)
elif isinstance(children, str):
sub_element.text = children
|
mottosso/Qt.py | examples/loadUi/baseinstance1.py | setup_ui | python | def setup_ui(uifile, base_instance=None):
ui = QtCompat.loadUi(uifile) # Qt.py mapped function
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith('__') and \
member is not 'staticMetaObject':
setattr(base_instance, member, getattr(ui, member))
return ui | Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
QWidget: the base instance | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance1.py#L10-L29 | null | import sys
import os
# Set preferred binding
os.environ['QT_PREFERRED_BINDING'] = os.pathsep.join(['PySide', 'PyQt4'])
from Qt import QtWidgets, QtCompat
class MainWindow(QtWidgets.QWidget):
"""Load .ui file example, using setattr/getattr approach"""
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.base_instance = setup_ui('qwidget.ui', self)
def test():
"""Example: QtCompat.loadUi with setup_ui wrapper"""
working_directory = os.path.dirname(__file__)
os.chdir(working_directory)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window, QtWidgets.QWidget)
assert isinstance(window.parent(), type(None))
assert isinstance(window.base_instance, QtWidgets.QWidget)
assert isinstance(window.lineEdit, QtWidgets.QWidget)
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
|
mottosso/Qt.py | membership.py | write_json | python | def write_json(dictionary, filename):
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename)) | Write dictionary to JSON | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L35-L39 | null | import os
import pkgutil
import json
from optparse import OptionParser
from functools import reduce
from pprint import pprint
# This is where all files are read from and saved to
PREFIX = '/Qt.py'
SKIP_MODULES = [
'PyQt4.uic.pyuic', # Problematic as it is executed on import
'PyQt5.uic.pyuic' # Problematic as it is executed on import
]
SKIP_MEMBERS = [
'qApp' # See main README.md on qApp
]
# Will contain all modules for the current binding
MODULES = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def compare(dicts):
"""Compare by iteration"""
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(
reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))
return common_members
def copy_qtgui_to_modules():
"""Copies the QtGui list of PySide/PyQt4 into QtWidgets"""
pyside_filepath = PREFIX + '/PySide.json'
pyqt4_filepath = PREFIX + '/PyQt4.json'
pyside = read_json(pyside_filepath)
pyqt4 = read_json(pyqt4_filepath)
# When Qt4 was moved to Qt5, they split QtGui into QtGui, QtWidgets, and
# QtPrintSupport.
pyside['QtWidgets'] = pyside['QtGui']
pyqt4['QtWidgets'] = pyqt4['QtGui']
pyside['QtPrintSupport'] = pyside['QtGui']
pyqt4['QtPrintSupport'] = pyqt4['QtGui']
write_json(pyside, pyside_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyside_filepath)))
write_json(pyqt4, pyqt4_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyqt4_filepath)))
def sort_common_members():
"""Sorts the keys and members"""
filename = PREFIX + '/common_members.json'
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
# Only add modules which have common members
sorted_json_data[key] = sorted(json_data[key])
print('--> Sorted/cleaned ' + os.path.basename(filename))
write_json(sorted_json_data, filename)
def generate_common_members():
"""Generate JSON with commonly shared members"""
pyside = read_json(PREFIX + '/PySide.json')
pyside2 = read_json(PREFIX + '/PySide2.json')
pyqt4 = read_json(PREFIX + '/PyQt4.json')
pyqt5 = read_json(PREFIX + '/PyQt5.json')
dicts = [pyside, pyside2, pyqt4, pyqt5]
common_members = compare(dicts)
write_json(common_members, PREFIX + '/common_members.json')
if __name__ == '__main__':
# Parse commandline arguments
parser = OptionParser()
parser.add_option('--binding', dest='binding', metavar='BINDING')
parser.add_option(
'--copy-qtgui',
action='store_true',
dest='copy',
default=False)
parser.add_option(
'--generate-common-members',
action='store_true',
dest='generate',
default=False)
parser.add_option(
'--sort-common-members',
action='store_true',
dest='sort',
default=False)
(options, args) = parser.parse_args()
if options.copy:
copy_qtgui_to_modules()
elif options.generate:
generate_common_members()
elif options.sort:
sort_common_members()
else:
# Import <binding>
binding = __import__(options.binding)
for importer, modname, ispkg in pkgutil.walk_packages(
path=binding.__path__,
prefix=binding.__name__ + '.',
onerror=lambda x: None):
if modname not in SKIP_MODULES:
MODULES.append(modname)
basemodule = modname[:modname.rfind('.')]
submodule = modname[modname.rfind('.')+1:]
try:
import_statement = (
'from ' + basemodule + ' import ' + submodule)
exec(import_statement)
# print(import_statement)
except (ImportError, AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import', modname, error)
try:
raw_members = [] # avoid Hound errors
exec('raw_members = dir(' + submodule + ')')
members = []
for member in raw_members:
if member not in SKIP_MEMBERS and \
not member.startswith('_'):
try:
import_statement = (
'from ' + basemodule + '.' + submodule +
' import ' + member)
exec(import_statement)
# print(import_statement)
MODULES.append(modname + '.' + member)
except (AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import',
modname, error)
except (NameError) as error:
print('WARNING: Skipped dir() command', modname, error)
# Remove duplicates and sort
MODULES = sorted(list(set(MODULES)))
if QT_VERBOSE:
# Print all modules (for debugging)
for module in MODULES:
print(module)
# Create dictionary
members = {}
for module in MODULES:
key = module.split('.')[1]
if key not in members:
members[key] = []
try:
value = module.split('.')[2]
members[key].append(value)
except IndexError:
pass
# Sort and remove duplicates
sorted_members = {}
for key, value in members.copy().items():
sorted_members[key] = sorted(list(set(value)))
if QT_VERBOSE:
# Debug
pprint(sorted_members)
# Write to disk
filepath = PREFIX + '/' + binding.__name__ + '.json'
write_json(sorted_members, filepath)
|
mottosso/Qt.py | membership.py | compare | python | def compare(dicts):
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(
reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))
return common_members | Compare by iteration | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L42-L51 | null | import os
import pkgutil
import json
from optparse import OptionParser
from functools import reduce
from pprint import pprint
# This is where all files are read from and saved to
PREFIX = '/Qt.py'
SKIP_MODULES = [
'PyQt4.uic.pyuic', # Problematic as it is executed on import
'PyQt5.uic.pyuic' # Problematic as it is executed on import
]
SKIP_MEMBERS = [
'qApp' # See main README.md on qApp
]
# Will contain all modules for the current binding
MODULES = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename))
def copy_qtgui_to_modules():
"""Copies the QtGui list of PySide/PyQt4 into QtWidgets"""
pyside_filepath = PREFIX + '/PySide.json'
pyqt4_filepath = PREFIX + '/PyQt4.json'
pyside = read_json(pyside_filepath)
pyqt4 = read_json(pyqt4_filepath)
# When Qt4 was moved to Qt5, they split QtGui into QtGui, QtWidgets, and
# QtPrintSupport.
pyside['QtWidgets'] = pyside['QtGui']
pyqt4['QtWidgets'] = pyqt4['QtGui']
pyside['QtPrintSupport'] = pyside['QtGui']
pyqt4['QtPrintSupport'] = pyqt4['QtGui']
write_json(pyside, pyside_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyside_filepath)))
write_json(pyqt4, pyqt4_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyqt4_filepath)))
def sort_common_members():
"""Sorts the keys and members"""
filename = PREFIX + '/common_members.json'
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
# Only add modules which have common members
sorted_json_data[key] = sorted(json_data[key])
print('--> Sorted/cleaned ' + os.path.basename(filename))
write_json(sorted_json_data, filename)
def generate_common_members():
"""Generate JSON with commonly shared members"""
pyside = read_json(PREFIX + '/PySide.json')
pyside2 = read_json(PREFIX + '/PySide2.json')
pyqt4 = read_json(PREFIX + '/PyQt4.json')
pyqt5 = read_json(PREFIX + '/PyQt5.json')
dicts = [pyside, pyside2, pyqt4, pyqt5]
common_members = compare(dicts)
write_json(common_members, PREFIX + '/common_members.json')
if __name__ == '__main__':
# Parse commandline arguments
parser = OptionParser()
parser.add_option('--binding', dest='binding', metavar='BINDING')
parser.add_option(
'--copy-qtgui',
action='store_true',
dest='copy',
default=False)
parser.add_option(
'--generate-common-members',
action='store_true',
dest='generate',
default=False)
parser.add_option(
'--sort-common-members',
action='store_true',
dest='sort',
default=False)
(options, args) = parser.parse_args()
if options.copy:
copy_qtgui_to_modules()
elif options.generate:
generate_common_members()
elif options.sort:
sort_common_members()
else:
# Import <binding>
binding = __import__(options.binding)
for importer, modname, ispkg in pkgutil.walk_packages(
path=binding.__path__,
prefix=binding.__name__ + '.',
onerror=lambda x: None):
if modname not in SKIP_MODULES:
MODULES.append(modname)
basemodule = modname[:modname.rfind('.')]
submodule = modname[modname.rfind('.')+1:]
try:
import_statement = (
'from ' + basemodule + ' import ' + submodule)
exec(import_statement)
# print(import_statement)
except (ImportError, AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import', modname, error)
try:
raw_members = [] # avoid Hound errors
exec('raw_members = dir(' + submodule + ')')
members = []
for member in raw_members:
if member not in SKIP_MEMBERS and \
not member.startswith('_'):
try:
import_statement = (
'from ' + basemodule + '.' + submodule +
' import ' + member)
exec(import_statement)
# print(import_statement)
MODULES.append(modname + '.' + member)
except (AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import',
modname, error)
except (NameError) as error:
print('WARNING: Skipped dir() command', modname, error)
# Remove duplicates and sort
MODULES = sorted(list(set(MODULES)))
if QT_VERBOSE:
# Print all modules (for debugging)
for module in MODULES:
print(module)
# Create dictionary
members = {}
for module in MODULES:
key = module.split('.')[1]
if key not in members:
members[key] = []
try:
value = module.split('.')[2]
members[key].append(value)
except IndexError:
pass
# Sort and remove duplicates
sorted_members = {}
for key, value in members.copy().items():
sorted_members[key] = sorted(list(set(value)))
if QT_VERBOSE:
# Debug
pprint(sorted_members)
# Write to disk
filepath = PREFIX + '/' + binding.__name__ + '.json'
write_json(sorted_members, filepath)
|
mottosso/Qt.py | membership.py | copy_qtgui_to_modules | python | def copy_qtgui_to_modules():
pyside_filepath = PREFIX + '/PySide.json'
pyqt4_filepath = PREFIX + '/PyQt4.json'
pyside = read_json(pyside_filepath)
pyqt4 = read_json(pyqt4_filepath)
# When Qt4 was moved to Qt5, they split QtGui into QtGui, QtWidgets, and
# QtPrintSupport.
pyside['QtWidgets'] = pyside['QtGui']
pyqt4['QtWidgets'] = pyqt4['QtGui']
pyside['QtPrintSupport'] = pyside['QtGui']
pyqt4['QtPrintSupport'] = pyqt4['QtGui']
write_json(pyside, pyside_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyside_filepath)))
write_json(pyqt4, pyqt4_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyqt4_filepath))) | Copies the QtGui list of PySide/PyQt4 into QtWidgets | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L54-L74 | [
"def read_json(filename):\n \"\"\"Read JSON, return dict\"\"\"\n\n with open(filename, 'r') as data_file:\n return json.load(data_file)\n",
"def write_json(dictionary, filename):\n \"\"\"Write dictionary to JSON\"\"\"\n with open(filename, 'w') as data_file:\n json.dump(dictionary, data_... | import os
import pkgutil
import json
from optparse import OptionParser
from functools import reduce
from pprint import pprint
# This is where all files are read from and saved to
PREFIX = '/Qt.py'
SKIP_MODULES = [
'PyQt4.uic.pyuic', # Problematic as it is executed on import
'PyQt5.uic.pyuic' # Problematic as it is executed on import
]
SKIP_MEMBERS = [
'qApp' # See main README.md on qApp
]
# Will contain all modules for the current binding
MODULES = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename))
def compare(dicts):
"""Compare by iteration"""
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(
reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))
return common_members
def sort_common_members():
"""Sorts the keys and members"""
filename = PREFIX + '/common_members.json'
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
# Only add modules which have common members
sorted_json_data[key] = sorted(json_data[key])
print('--> Sorted/cleaned ' + os.path.basename(filename))
write_json(sorted_json_data, filename)
def generate_common_members():
"""Generate JSON with commonly shared members"""
pyside = read_json(PREFIX + '/PySide.json')
pyside2 = read_json(PREFIX + '/PySide2.json')
pyqt4 = read_json(PREFIX + '/PyQt4.json')
pyqt5 = read_json(PREFIX + '/PyQt5.json')
dicts = [pyside, pyside2, pyqt4, pyqt5]
common_members = compare(dicts)
write_json(common_members, PREFIX + '/common_members.json')
if __name__ == '__main__':
# Parse commandline arguments
parser = OptionParser()
parser.add_option('--binding', dest='binding', metavar='BINDING')
parser.add_option(
'--copy-qtgui',
action='store_true',
dest='copy',
default=False)
parser.add_option(
'--generate-common-members',
action='store_true',
dest='generate',
default=False)
parser.add_option(
'--sort-common-members',
action='store_true',
dest='sort',
default=False)
(options, args) = parser.parse_args()
if options.copy:
copy_qtgui_to_modules()
elif options.generate:
generate_common_members()
elif options.sort:
sort_common_members()
else:
# Import <binding>
binding = __import__(options.binding)
for importer, modname, ispkg in pkgutil.walk_packages(
path=binding.__path__,
prefix=binding.__name__ + '.',
onerror=lambda x: None):
if modname not in SKIP_MODULES:
MODULES.append(modname)
basemodule = modname[:modname.rfind('.')]
submodule = modname[modname.rfind('.')+1:]
try:
import_statement = (
'from ' + basemodule + ' import ' + submodule)
exec(import_statement)
# print(import_statement)
except (ImportError, AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import', modname, error)
try:
raw_members = [] # avoid Hound errors
exec('raw_members = dir(' + submodule + ')')
members = []
for member in raw_members:
if member not in SKIP_MEMBERS and \
not member.startswith('_'):
try:
import_statement = (
'from ' + basemodule + '.' + submodule +
' import ' + member)
exec(import_statement)
# print(import_statement)
MODULES.append(modname + '.' + member)
except (AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import',
modname, error)
except (NameError) as error:
print('WARNING: Skipped dir() command', modname, error)
# Remove duplicates and sort
MODULES = sorted(list(set(MODULES)))
if QT_VERBOSE:
# Print all modules (for debugging)
for module in MODULES:
print(module)
# Create dictionary
members = {}
for module in MODULES:
key = module.split('.')[1]
if key not in members:
members[key] = []
try:
value = module.split('.')[2]
members[key].append(value)
except IndexError:
pass
# Sort and remove duplicates
sorted_members = {}
for key, value in members.copy().items():
sorted_members[key] = sorted(list(set(value)))
if QT_VERBOSE:
# Debug
pprint(sorted_members)
# Write to disk
filepath = PREFIX + '/' + binding.__name__ + '.json'
write_json(sorted_members, filepath)
|
mottosso/Qt.py | membership.py | sort_common_members | python | def sort_common_members():
filename = PREFIX + '/common_members.json'
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
# Only add modules which have common members
sorted_json_data[key] = sorted(json_data[key])
print('--> Sorted/cleaned ' + os.path.basename(filename))
write_json(sorted_json_data, filename) | Sorts the keys and members | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L77-L96 | [
"def read_json(filename):\n \"\"\"Read JSON, return dict\"\"\"\n\n with open(filename, 'r') as data_file:\n return json.load(data_file)\n",
"def write_json(dictionary, filename):\n \"\"\"Write dictionary to JSON\"\"\"\n with open(filename, 'w') as data_file:\n json.dump(dictionary, data_... | import os
import pkgutil
import json
from optparse import OptionParser
from functools import reduce
from pprint import pprint
# This is where all files are read from and saved to
PREFIX = '/Qt.py'
SKIP_MODULES = [
'PyQt4.uic.pyuic', # Problematic as it is executed on import
'PyQt5.uic.pyuic' # Problematic as it is executed on import
]
SKIP_MEMBERS = [
'qApp' # See main README.md on qApp
]
# Will contain all modules for the current binding
MODULES = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename))
def compare(dicts):
"""Compare by iteration"""
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(
reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))
return common_members
def copy_qtgui_to_modules():
"""Copies the QtGui list of PySide/PyQt4 into QtWidgets"""
pyside_filepath = PREFIX + '/PySide.json'
pyqt4_filepath = PREFIX + '/PyQt4.json'
pyside = read_json(pyside_filepath)
pyqt4 = read_json(pyqt4_filepath)
# When Qt4 was moved to Qt5, they split QtGui into QtGui, QtWidgets, and
# QtPrintSupport.
pyside['QtWidgets'] = pyside['QtGui']
pyqt4['QtWidgets'] = pyqt4['QtGui']
pyside['QtPrintSupport'] = pyside['QtGui']
pyqt4['QtPrintSupport'] = pyqt4['QtGui']
write_json(pyside, pyside_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyside_filepath)))
write_json(pyqt4, pyqt4_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyqt4_filepath)))
def generate_common_members():
"""Generate JSON with commonly shared members"""
pyside = read_json(PREFIX + '/PySide.json')
pyside2 = read_json(PREFIX + '/PySide2.json')
pyqt4 = read_json(PREFIX + '/PyQt4.json')
pyqt5 = read_json(PREFIX + '/PyQt5.json')
dicts = [pyside, pyside2, pyqt4, pyqt5]
common_members = compare(dicts)
write_json(common_members, PREFIX + '/common_members.json')
if __name__ == '__main__':
# Parse commandline arguments
parser = OptionParser()
parser.add_option('--binding', dest='binding', metavar='BINDING')
parser.add_option(
'--copy-qtgui',
action='store_true',
dest='copy',
default=False)
parser.add_option(
'--generate-common-members',
action='store_true',
dest='generate',
default=False)
parser.add_option(
'--sort-common-members',
action='store_true',
dest='sort',
default=False)
(options, args) = parser.parse_args()
if options.copy:
copy_qtgui_to_modules()
elif options.generate:
generate_common_members()
elif options.sort:
sort_common_members()
else:
# Import <binding>
binding = __import__(options.binding)
for importer, modname, ispkg in pkgutil.walk_packages(
path=binding.__path__,
prefix=binding.__name__ + '.',
onerror=lambda x: None):
if modname not in SKIP_MODULES:
MODULES.append(modname)
basemodule = modname[:modname.rfind('.')]
submodule = modname[modname.rfind('.')+1:]
try:
import_statement = (
'from ' + basemodule + ' import ' + submodule)
exec(import_statement)
# print(import_statement)
except (ImportError, AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import', modname, error)
try:
raw_members = [] # avoid Hound errors
exec('raw_members = dir(' + submodule + ')')
members = []
for member in raw_members:
if member not in SKIP_MEMBERS and \
not member.startswith('_'):
try:
import_statement = (
'from ' + basemodule + '.' + submodule +
' import ' + member)
exec(import_statement)
# print(import_statement)
MODULES.append(modname + '.' + member)
except (AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import',
modname, error)
except (NameError) as error:
print('WARNING: Skipped dir() command', modname, error)
# Remove duplicates and sort
MODULES = sorted(list(set(MODULES)))
if QT_VERBOSE:
# Print all modules (for debugging)
for module in MODULES:
print(module)
# Create dictionary
members = {}
for module in MODULES:
key = module.split('.')[1]
if key not in members:
members[key] = []
try:
value = module.split('.')[2]
members[key].append(value)
except IndexError:
pass
# Sort and remove duplicates
sorted_members = {}
for key, value in members.copy().items():
sorted_members[key] = sorted(list(set(value)))
if QT_VERBOSE:
# Debug
pprint(sorted_members)
# Write to disk
filepath = PREFIX + '/' + binding.__name__ + '.json'
write_json(sorted_members, filepath)
|
mottosso/Qt.py | membership.py | generate_common_members | python | def generate_common_members():
pyside = read_json(PREFIX + '/PySide.json')
pyside2 = read_json(PREFIX + '/PySide2.json')
pyqt4 = read_json(PREFIX + '/PyQt4.json')
pyqt5 = read_json(PREFIX + '/PyQt5.json')
dicts = [pyside, pyside2, pyqt4, pyqt5]
common_members = compare(dicts)
write_json(common_members, PREFIX + '/common_members.json') | Generate JSON with commonly shared members | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L99-L109 | [
"def compare(dicts):\n \"\"\"Compare by iteration\"\"\"\n\n common_members = {}\n common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))\n for k in common_keys:\n common_members[k] = list(\n reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))\n\n return common_members\n... | import os
import pkgutil
import json
from optparse import OptionParser
from functools import reduce
from pprint import pprint
# This is where all files are read from and saved to
PREFIX = '/Qt.py'
SKIP_MODULES = [
'PyQt4.uic.pyuic', # Problematic as it is executed on import
'PyQt5.uic.pyuic' # Problematic as it is executed on import
]
SKIP_MEMBERS = [
'qApp' # See main README.md on qApp
]
# Will contain all modules for the current binding
MODULES = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
def read_json(filename):
"""Read JSON, return dict"""
with open(filename, 'r') as data_file:
return json.load(data_file)
def write_json(dictionary, filename):
"""Write dictionary to JSON"""
with open(filename, 'w') as data_file:
json.dump(dictionary, data_file, indent=4, sort_keys=True)
print('--> Wrote ' + os.path.basename(filename))
def compare(dicts):
"""Compare by iteration"""
common_members = {}
common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))
for k in common_keys:
common_members[k] = list(
reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))
return common_members
def copy_qtgui_to_modules():
"""Copies the QtGui list of PySide/PyQt4 into QtWidgets"""
pyside_filepath = PREFIX + '/PySide.json'
pyqt4_filepath = PREFIX + '/PyQt4.json'
pyside = read_json(pyside_filepath)
pyqt4 = read_json(pyqt4_filepath)
# When Qt4 was moved to Qt5, they split QtGui into QtGui, QtWidgets, and
# QtPrintSupport.
pyside['QtWidgets'] = pyside['QtGui']
pyqt4['QtWidgets'] = pyqt4['QtGui']
pyside['QtPrintSupport'] = pyside['QtGui']
pyqt4['QtPrintSupport'] = pyqt4['QtGui']
write_json(pyside, pyside_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyside_filepath)))
write_json(pyqt4, pyqt4_filepath)
print('--> Copied QtGui to QtWidgets and QtPrintSupport for {0}'.format(
os.path.basename(pyqt4_filepath)))
def sort_common_members():
"""Sorts the keys and members"""
filename = PREFIX + '/common_members.json'
sorted_json_data = {}
json_data = read_json(filename)
all_keys = []
for key, value in json_data.items():
all_keys.append(key)
sorted_keys = sorted(all_keys)
for key in sorted_keys:
if len(json_data[key]) > 0:
# Only add modules which have common members
sorted_json_data[key] = sorted(json_data[key])
print('--> Sorted/cleaned ' + os.path.basename(filename))
write_json(sorted_json_data, filename)
if __name__ == '__main__':
# Parse commandline arguments
parser = OptionParser()
parser.add_option('--binding', dest='binding', metavar='BINDING')
parser.add_option(
'--copy-qtgui',
action='store_true',
dest='copy',
default=False)
parser.add_option(
'--generate-common-members',
action='store_true',
dest='generate',
default=False)
parser.add_option(
'--sort-common-members',
action='store_true',
dest='sort',
default=False)
(options, args) = parser.parse_args()
if options.copy:
copy_qtgui_to_modules()
elif options.generate:
generate_common_members()
elif options.sort:
sort_common_members()
else:
# Import <binding>
binding = __import__(options.binding)
for importer, modname, ispkg in pkgutil.walk_packages(
path=binding.__path__,
prefix=binding.__name__ + '.',
onerror=lambda x: None):
if modname not in SKIP_MODULES:
MODULES.append(modname)
basemodule = modname[:modname.rfind('.')]
submodule = modname[modname.rfind('.')+1:]
try:
import_statement = (
'from ' + basemodule + ' import ' + submodule)
exec(import_statement)
# print(import_statement)
except (ImportError, AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import', modname, error)
try:
raw_members = [] # avoid Hound errors
exec('raw_members = dir(' + submodule + ')')
members = []
for member in raw_members:
if member not in SKIP_MEMBERS and \
not member.startswith('_'):
try:
import_statement = (
'from ' + basemodule + '.' + submodule +
' import ' + member)
exec(import_statement)
# print(import_statement)
MODULES.append(modname + '.' + member)
except (AttributeError, SyntaxError) as error:
# SyntaxError catched here because e.g. _port3
# running on Python 2...
print('WARNING: Skipped import',
modname, error)
except (NameError) as error:
print('WARNING: Skipped dir() command', modname, error)
# Remove duplicates and sort
MODULES = sorted(list(set(MODULES)))
if QT_VERBOSE:
# Print all modules (for debugging)
for module in MODULES:
print(module)
# Create dictionary
members = {}
for module in MODULES:
key = module.split('.')[1]
if key not in members:
members[key] = []
try:
value = module.split('.')[2]
members[key].append(value)
except IndexError:
pass
# Sort and remove duplicates
sorted_members = {}
for key, value in members.copy().items():
sorted_members[key] = sorted(list(set(value)))
if QT_VERBOSE:
# Debug
pprint(sorted_members)
# Write to disk
filepath = PREFIX + '/' + binding.__name__ + '.json'
write_json(sorted_members, filepath)
|
mottosso/Qt.py | caveats.py | parse | python | def parse(fname):
blocks = list()
with io.open(fname, "r", encoding="utf-8") as f:
in_block = False
current_block = None
current_header = ""
for line in f:
# Doctests are within a quadruple hashtag header.
if line.startswith("#### "):
current_header = line.rstrip()
# The actuat test is within a fenced block.
if line.startswith("```"):
in_block = False
if in_block:
current_block.append(line)
if line.startswith("```python"):
in_block = True
current_block = list()
current_block.append(current_header)
blocks.append(current_block)
tests = list()
for block in blocks:
header = (
block[0].strip("# ") # Remove Markdown
.rstrip() # Remove newline
.lower() # PEP08
)
# Remove unsupported characters
header = re.sub(r"\W", "_", header)
# Adding "untested" anywhere in the first line of
# the doctest excludes it from the test.
if "untested" in block[1].lower():
continue
data = re.sub(" ", "", block[1]) # Remove spaces
data = (
data.strip("#")
.rstrip() # Remove newline
.split(",")
)
binding, doctest_version = (data + [None])[:2]
# Run tests on both Python 2 and 3, unless explicitly stated
if doctest_version is not None:
if doctest_version not in ("Python2", "Python3"):
raise SyntaxError(
"Invalid Python version:\n%s\n"
"Python version must follow binding, e.g.\n"
"# PyQt5, Python3" % doctest_version)
active_version = "Python%i" % sys.version_info[0]
if doctest_version != active_version:
continue
tests.append({
"header": header,
"binding": binding,
"body": block[2:]
})
return tests | Return blocks of code as list of dicts
Arguments:
fname (str): Relative name of caveats file | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/caveats.py#L6-L82 | null | import io
import re
import sys
def format_(blocks):
"""Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()`
"""
tests = list()
function_count = 0 # For each test to have a unique name
for block in blocks:
# Validate docstring format of body
if not any(line[:3] == ">>>" for line in block["body"]):
# A doctest requires at least one `>>>` directive.
block["body"].insert(0, ">>> assert False, "
"'Body must be in docstring format'\n")
# Validate binding on first line
if not block["binding"] in ("PySide", "PySide2", "PyQt5", "PyQt4"):
block["body"].insert(0, ">>> assert False, "
"'Invalid binding'\n")
if sys.version_info > (3, 4) and block["binding"] in ("PySide"):
# Skip caveat test if it requires PySide on Python > 3.4
continue
else:
function_count += 1
block["header"] = block["header"]
block["count"] = str(function_count)
block["body"] = " ".join(block["body"])
tests.append("""\
def test_{count}_{header}():
'''Test {header}
>>> import os, sys
>>> PYTHON = sys.version_info[0]
>>> long = int if PYTHON == 3 else long
>>> _ = os.environ.pop("QT_VERBOSE", None) # Disable debug output
>>> os.environ["QT_PREFERRED_BINDING"] = "{binding}"
{body}
'''
""".format(**block))
return tests
|
mottosso/Qt.py | caveats.py | format_ | python | def format_(blocks):
tests = list()
function_count = 0 # For each test to have a unique name
for block in blocks:
# Validate docstring format of body
if not any(line[:3] == ">>>" for line in block["body"]):
# A doctest requires at least one `>>>` directive.
block["body"].insert(0, ">>> assert False, "
"'Body must be in docstring format'\n")
# Validate binding on first line
if not block["binding"] in ("PySide", "PySide2", "PyQt5", "PyQt4"):
block["body"].insert(0, ">>> assert False, "
"'Invalid binding'\n")
if sys.version_info > (3, 4) and block["binding"] in ("PySide"):
# Skip caveat test if it requires PySide on Python > 3.4
continue
else:
function_count += 1
block["header"] = block["header"]
block["count"] = str(function_count)
block["body"] = " ".join(block["body"])
tests.append("""\
def test_{count}_{header}():
'''Test {header}
>>> import os, sys
>>> PYTHON = sys.version_info[0]
>>> long = int if PYTHON == 3 else long
>>> _ = os.environ.pop("QT_VERBOSE", None) # Disable debug output
>>> os.environ["QT_PREFERRED_BINDING"] = "{binding}"
{body}
'''
""".format(**block))
return tests | Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()` | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/caveats.py#L85-L132 | null | import io
import re
import sys
def parse(fname):
"""Return blocks of code as list of dicts
Arguments:
fname (str): Relative name of caveats file
"""
blocks = list()
with io.open(fname, "r", encoding="utf-8") as f:
in_block = False
current_block = None
current_header = ""
for line in f:
# Doctests are within a quadruple hashtag header.
if line.startswith("#### "):
current_header = line.rstrip()
# The actuat test is within a fenced block.
if line.startswith("```"):
in_block = False
if in_block:
current_block.append(line)
if line.startswith("```python"):
in_block = True
current_block = list()
current_block.append(current_header)
blocks.append(current_block)
tests = list()
for block in blocks:
header = (
block[0].strip("# ") # Remove Markdown
.rstrip() # Remove newline
.lower() # PEP08
)
# Remove unsupported characters
header = re.sub(r"\W", "_", header)
# Adding "untested" anywhere in the first line of
# the doctest excludes it from the test.
if "untested" in block[1].lower():
continue
data = re.sub(" ", "", block[1]) # Remove spaces
data = (
data.strip("#")
.rstrip() # Remove newline
.split(",")
)
binding, doctest_version = (data + [None])[:2]
# Run tests on both Python 2 and 3, unless explicitly stated
if doctest_version is not None:
if doctest_version not in ("Python2", "Python3"):
raise SyntaxError(
"Invalid Python version:\n%s\n"
"Python version must follow binding, e.g.\n"
"# PyQt5, Python3" % doctest_version)
active_version = "Python%i" % sys.version_info[0]
if doctest_version != active_version:
continue
tests.append({
"header": header,
"binding": binding,
"body": block[2:]
})
return tests
|
mottosso/Qt.py | Qt.py | _qInstallMessageHandler | python | def _qInstallMessageHandler(handler):
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject) | Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L683-L716 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _wrapinstance | python | def _wrapinstance(ptr, base=None):
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base) | Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything. | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L729-L778 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _loadUi | python | def _loadUi(uifile, baseinstance=None):
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi") | Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface. | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L817-L948 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _import_sub_module | python | def _import_sub_module(module, name):
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module | import_sub_module will mimic the function of importlib.import_module | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1191-L1196 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _setup | python | def _setup(module, extras):
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name)) | Install common submodules | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1199-L1222 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _reassign_misplaced_members | python | def _reassign_misplaced_members(binding):
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
) | Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1225-L1294 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _build_compatibility_members | python | def _build_compatibility_members(binding, decorators=None):
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class) | Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions. | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1297-L1355 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _pyside2 | python | def _pyside2():
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2") | Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1358-L1400 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _pyqt4 | python | def _pyqt4():
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators) | Initialise PyQt4 | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1478-L1571 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _none | python | def _none():
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock()) | Internal option (used in installer) | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1574-L1587 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | Qt.py | _convert | python | def _convert(lines):
def parse(line):
line = line.replace("from PySide2 import", "from Qt import QtCompat,")
line = line.replace("QtWidgets.QApplication.translate",
"QtCompat.translate")
if "QtCore.SIGNAL" in line:
raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 "
"and so Qt.py does not support it: you "
"should avoid defining signals inside "
"your ui files.")
return line
parsed = list()
for line in lines:
line = parse(line)
parsed.append(line)
return parsed | Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines()) | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1595-L1623 | null | """Minimal Python 2 & 3 shim around all Qt bindings
DOCUMENTATION
Qt.py was born in the film and visual effects industry to address
the growing need for the development of software capable of running
with more than one flavour of the Qt bindings for Python - PySide,
PySide2, PyQt4 and PyQt5.
1. Build for one, run with all
2. Explicit is better than implicit
3. Support co-existence
Default resolution order:
- PySide2
- PyQt5
- PySide
- PyQt4
Usage:
>> import sys
>> from Qt import QtWidgets
>> app = QtWidgets.QApplication(sys.argv)
>> button = QtWidgets.QPushButton("Hello World")
>> button.show()
>> app.exec_()
All members of PySide2 are mapped from other bindings, should they exist.
If no equivalent member exist, it is excluded from Qt.py and inaccessible.
The idea is to highlight members that exist across all supported binding,
and guarantee that code that runs on one binding runs on all others.
For more details, visit https://github.com/mottosso/Qt.py
LICENSE
See end of file for license (MIT, BSD) information.
"""
import os
import sys
import types
import shutil
import importlib
__version__ = "1.2.0.b3"
# Enable support for `from Qt import *`
__all__ = []
# Flags from environment variables
QT_VERBOSE = bool(os.getenv("QT_VERBOSE"))
QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "")
QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT")
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = types.ModuleType("QtCompat")
try:
long
except NameError:
# Python 3 compatibility
long = int
"""Common members of all bindings
This is where each member of Qt.py is explicitly defined.
It is based on a "lowest common denominator" of all bindings;
including members found in each of the 4 bindings.
The "_common_members" dictionary is generated using the
build_membership.sh script.
"""
_common_members = {
"QtCore": [
"QAbstractAnimation",
"QAbstractEventDispatcher",
"QAbstractItemModel",
"QAbstractListModel",
"QAbstractState",
"QAbstractTableModel",
"QAbstractTransition",
"QAnimationGroup",
"QBasicTimer",
"QBitArray",
"QBuffer",
"QByteArray",
"QByteArrayMatcher",
"QChildEvent",
"QCoreApplication",
"QCryptographicHash",
"QDataStream",
"QDate",
"QDateTime",
"QDir",
"QDirIterator",
"QDynamicPropertyChangeEvent",
"QEasingCurve",
"QElapsedTimer",
"QEvent",
"QEventLoop",
"QEventTransition",
"QFile",
"QFileInfo",
"QFileSystemWatcher",
"QFinalState",
"QGenericArgument",
"QGenericReturnArgument",
"QHistoryState",
"QItemSelectionRange",
"QIODevice",
"QLibraryInfo",
"QLine",
"QLineF",
"QLocale",
"QMargins",
"QMetaClassInfo",
"QMetaEnum",
"QMetaMethod",
"QMetaObject",
"QMetaProperty",
"QMimeData",
"QModelIndex",
"QMutex",
"QMutexLocker",
"QObject",
"QParallelAnimationGroup",
"QPauseAnimation",
"QPersistentModelIndex",
"QPluginLoader",
"QPoint",
"QPointF",
"QProcess",
"QProcessEnvironment",
"QPropertyAnimation",
"QReadLocker",
"QReadWriteLock",
"QRect",
"QRectF",
"QRegExp",
"QResource",
"QRunnable",
"QSemaphore",
"QSequentialAnimationGroup",
"QSettings",
"QSignalMapper",
"QSignalTransition",
"QSize",
"QSizeF",
"QSocketNotifier",
"QState",
"QStateMachine",
"QSysInfo",
"QSystemSemaphore",
"QT_TRANSLATE_NOOP",
"QT_TR_NOOP",
"QT_TR_NOOP_UTF8",
"QTemporaryFile",
"QTextBoundaryFinder",
"QTextCodec",
"QTextDecoder",
"QTextEncoder",
"QTextStream",
"QTextStreamManipulator",
"QThread",
"QThreadPool",
"QTime",
"QTimeLine",
"QTimer",
"QTimerEvent",
"QTranslator",
"QUrl",
"QVariantAnimation",
"QWaitCondition",
"QWriteLocker",
"QXmlStreamAttribute",
"QXmlStreamAttributes",
"QXmlStreamEntityDeclaration",
"QXmlStreamEntityResolver",
"QXmlStreamNamespaceDeclaration",
"QXmlStreamNotationDeclaration",
"QXmlStreamReader",
"QXmlStreamWriter",
"Qt",
"QtCriticalMsg",
"QtDebugMsg",
"QtFatalMsg",
"QtMsgType",
"QtSystemMsg",
"QtWarningMsg",
"qAbs",
"qAddPostRoutine",
"qChecksum",
"qCritical",
"qDebug",
"qFatal",
"qFuzzyCompare",
"qIsFinite",
"qIsInf",
"qIsNaN",
"qIsNull",
"qRegisterResourceData",
"qUnregisterResourceData",
"qVersion",
"qWarning",
"qrand",
"qsrand"
],
"QtGui": [
"QAbstractTextDocumentLayout",
"QActionEvent",
"QBitmap",
"QBrush",
"QClipboard",
"QCloseEvent",
"QColor",
"QConicalGradient",
"QContextMenuEvent",
"QCursor",
"QDesktopServices",
"QDoubleValidator",
"QDrag",
"QDragEnterEvent",
"QDragLeaveEvent",
"QDragMoveEvent",
"QDropEvent",
"QFileOpenEvent",
"QFocusEvent",
"QFont",
"QFontDatabase",
"QFontInfo",
"QFontMetrics",
"QFontMetricsF",
"QGradient",
"QHelpEvent",
"QHideEvent",
"QHoverEvent",
"QIcon",
"QIconDragEvent",
"QIconEngine",
"QImage",
"QImageIOHandler",
"QImageReader",
"QImageWriter",
"QInputEvent",
"QInputMethodEvent",
"QIntValidator",
"QKeyEvent",
"QKeySequence",
"QLinearGradient",
"QMatrix2x2",
"QMatrix2x3",
"QMatrix2x4",
"QMatrix3x2",
"QMatrix3x3",
"QMatrix3x4",
"QMatrix4x2",
"QMatrix4x3",
"QMatrix4x4",
"QMouseEvent",
"QMoveEvent",
"QMovie",
"QPaintDevice",
"QPaintEngine",
"QPaintEngineState",
"QPaintEvent",
"QPainter",
"QPainterPath",
"QPainterPathStroker",
"QPalette",
"QPen",
"QPicture",
"QPictureIO",
"QPixmap",
"QPixmapCache",
"QPolygon",
"QPolygonF",
"QQuaternion",
"QRadialGradient",
"QRegExpValidator",
"QRegion",
"QResizeEvent",
"QSessionManager",
"QShortcutEvent",
"QShowEvent",
"QStandardItem",
"QStandardItemModel",
"QStatusTipEvent",
"QSyntaxHighlighter",
"QTabletEvent",
"QTextBlock",
"QTextBlockFormat",
"QTextBlockGroup",
"QTextBlockUserData",
"QTextCharFormat",
"QTextCursor",
"QTextDocument",
"QTextDocumentFragment",
"QTextFormat",
"QTextFragment",
"QTextFrame",
"QTextFrameFormat",
"QTextImageFormat",
"QTextInlineObject",
"QTextItem",
"QTextLayout",
"QTextLength",
"QTextLine",
"QTextList",
"QTextListFormat",
"QTextObject",
"QTextObjectInterface",
"QTextOption",
"QTextTable",
"QTextTableCell",
"QTextTableCellFormat",
"QTextTableFormat",
"QTouchEvent",
"QTransform",
"QValidator",
"QVector2D",
"QVector3D",
"QVector4D",
"QWhatsThisClickedEvent",
"QWheelEvent",
"QWindowStateChangeEvent",
"qAlpha",
"qBlue",
"qGray",
"qGreen",
"qIsGray",
"qRed",
"qRgb",
"qRgba"
],
"QtHelp": [
"QHelpContentItem",
"QHelpContentModel",
"QHelpContentWidget",
"QHelpEngine",
"QHelpEngineCore",
"QHelpIndexModel",
"QHelpIndexWidget",
"QHelpSearchEngine",
"QHelpSearchQuery",
"QHelpSearchQueryWidget",
"QHelpSearchResultWidget"
],
"QtMultimedia": [
"QAbstractVideoBuffer",
"QAbstractVideoSurface",
"QAudio",
"QAudioDeviceInfo",
"QAudioFormat",
"QAudioInput",
"QAudioOutput",
"QVideoFrame",
"QVideoSurfaceFormat"
],
"QtNetwork": [
"QAbstractNetworkCache",
"QAbstractSocket",
"QAuthenticator",
"QHostAddress",
"QHostInfo",
"QLocalServer",
"QLocalSocket",
"QNetworkAccessManager",
"QNetworkAddressEntry",
"QNetworkCacheMetaData",
"QNetworkConfiguration",
"QNetworkConfigurationManager",
"QNetworkCookie",
"QNetworkCookieJar",
"QNetworkDiskCache",
"QNetworkInterface",
"QNetworkProxy",
"QNetworkProxyFactory",
"QNetworkProxyQuery",
"QNetworkReply",
"QNetworkRequest",
"QNetworkSession",
"QSsl",
"QTcpServer",
"QTcpSocket",
"QUdpSocket"
],
"QtOpenGL": [
"QGL",
"QGLContext",
"QGLFormat",
"QGLWidget"
],
"QtPrintSupport": [
"QAbstractPrintDialog",
"QPageSetupDialog",
"QPrintDialog",
"QPrintEngine",
"QPrintPreviewDialog",
"QPrintPreviewWidget",
"QPrinter",
"QPrinterInfo"
],
"QtSql": [
"QSql",
"QSqlDatabase",
"QSqlDriver",
"QSqlDriverCreatorBase",
"QSqlError",
"QSqlField",
"QSqlIndex",
"QSqlQuery",
"QSqlQueryModel",
"QSqlRecord",
"QSqlRelation",
"QSqlRelationalDelegate",
"QSqlRelationalTableModel",
"QSqlResult",
"QSqlTableModel"
],
"QtSvg": [
"QGraphicsSvgItem",
"QSvgGenerator",
"QSvgRenderer",
"QSvgWidget"
],
"QtTest": [
"QTest"
],
"QtWidgets": [
"QAbstractButton",
"QAbstractGraphicsShapeItem",
"QAbstractItemDelegate",
"QAbstractItemView",
"QAbstractScrollArea",
"QAbstractSlider",
"QAbstractSpinBox",
"QAction",
"QActionGroup",
"QApplication",
"QBoxLayout",
"QButtonGroup",
"QCalendarWidget",
"QCheckBox",
"QColorDialog",
"QColumnView",
"QComboBox",
"QCommandLinkButton",
"QCommonStyle",
"QCompleter",
"QDataWidgetMapper",
"QDateEdit",
"QDateTimeEdit",
"QDesktopWidget",
"QDial",
"QDialog",
"QDialogButtonBox",
"QDirModel",
"QDockWidget",
"QDoubleSpinBox",
"QErrorMessage",
"QFileDialog",
"QFileIconProvider",
"QFileSystemModel",
"QFocusFrame",
"QFontComboBox",
"QFontDialog",
"QFormLayout",
"QFrame",
"QGesture",
"QGestureEvent",
"QGestureRecognizer",
"QGraphicsAnchor",
"QGraphicsAnchorLayout",
"QGraphicsBlurEffect",
"QGraphicsColorizeEffect",
"QGraphicsDropShadowEffect",
"QGraphicsEffect",
"QGraphicsEllipseItem",
"QGraphicsGridLayout",
"QGraphicsItem",
"QGraphicsItemGroup",
"QGraphicsLayout",
"QGraphicsLayoutItem",
"QGraphicsLineItem",
"QGraphicsLinearLayout",
"QGraphicsObject",
"QGraphicsOpacityEffect",
"QGraphicsPathItem",
"QGraphicsPixmapItem",
"QGraphicsPolygonItem",
"QGraphicsProxyWidget",
"QGraphicsRectItem",
"QGraphicsRotation",
"QGraphicsScale",
"QGraphicsScene",
"QGraphicsSceneContextMenuEvent",
"QGraphicsSceneDragDropEvent",
"QGraphicsSceneEvent",
"QGraphicsSceneHelpEvent",
"QGraphicsSceneHoverEvent",
"QGraphicsSceneMouseEvent",
"QGraphicsSceneMoveEvent",
"QGraphicsSceneResizeEvent",
"QGraphicsSceneWheelEvent",
"QGraphicsSimpleTextItem",
"QGraphicsTextItem",
"QGraphicsTransform",
"QGraphicsView",
"QGraphicsWidget",
"QGridLayout",
"QGroupBox",
"QHBoxLayout",
"QHeaderView",
"QInputDialog",
"QItemDelegate",
"QItemEditorCreatorBase",
"QItemEditorFactory",
"QKeyEventTransition",
"QLCDNumber",
"QLabel",
"QLayout",
"QLayoutItem",
"QLineEdit",
"QListView",
"QListWidget",
"QListWidgetItem",
"QMainWindow",
"QMdiArea",
"QMdiSubWindow",
"QMenu",
"QMenuBar",
"QMessageBox",
"QMouseEventTransition",
"QPanGesture",
"QPinchGesture",
"QPlainTextDocumentLayout",
"QPlainTextEdit",
"QProgressBar",
"QProgressDialog",
"QPushButton",
"QRadioButton",
"QRubberBand",
"QScrollArea",
"QScrollBar",
"QShortcut",
"QSizeGrip",
"QSizePolicy",
"QSlider",
"QSpacerItem",
"QSpinBox",
"QSplashScreen",
"QSplitter",
"QSplitterHandle",
"QStackedLayout",
"QStackedWidget",
"QStatusBar",
"QStyle",
"QStyleFactory",
"QStyleHintReturn",
"QStyleHintReturnMask",
"QStyleHintReturnVariant",
"QStyleOption",
"QStyleOptionButton",
"QStyleOptionComboBox",
"QStyleOptionComplex",
"QStyleOptionDockWidget",
"QStyleOptionFocusRect",
"QStyleOptionFrame",
"QStyleOptionGraphicsItem",
"QStyleOptionGroupBox",
"QStyleOptionHeader",
"QStyleOptionMenuItem",
"QStyleOptionProgressBar",
"QStyleOptionRubberBand",
"QStyleOptionSizeGrip",
"QStyleOptionSlider",
"QStyleOptionSpinBox",
"QStyleOptionTab",
"QStyleOptionTabBarBase",
"QStyleOptionTabWidgetFrame",
"QStyleOptionTitleBar",
"QStyleOptionToolBar",
"QStyleOptionToolBox",
"QStyleOptionToolButton",
"QStyleOptionViewItem",
"QStylePainter",
"QStyledItemDelegate",
"QSwipeGesture",
"QSystemTrayIcon",
"QTabBar",
"QTabWidget",
"QTableView",
"QTableWidget",
"QTableWidgetItem",
"QTableWidgetSelectionRange",
"QTapAndHoldGesture",
"QTapGesture",
"QTextBrowser",
"QTextEdit",
"QTimeEdit",
"QToolBar",
"QToolBox",
"QToolButton",
"QToolTip",
"QTreeView",
"QTreeWidget",
"QTreeWidgetItem",
"QTreeWidgetItemIterator",
"QUndoCommand",
"QUndoGroup",
"QUndoStack",
"QUndoView",
"QVBoxLayout",
"QWhatsThis",
"QWidget",
"QWidgetAction",
"QWidgetItem",
"QWizard",
"QWizardPage"
],
"QtX11Extras": [
"QX11Info"
],
"QtXml": [
"QDomAttr",
"QDomCDATASection",
"QDomCharacterData",
"QDomComment",
"QDomDocument",
"QDomDocumentFragment",
"QDomDocumentType",
"QDomElement",
"QDomEntity",
"QDomEntityReference",
"QDomImplementation",
"QDomNamedNodeMap",
"QDomNode",
"QDomNodeList",
"QDomNotation",
"QDomProcessingInstruction",
"QDomText",
"QXmlAttributes",
"QXmlContentHandler",
"QXmlDTDHandler",
"QXmlDeclHandler",
"QXmlDefaultHandler",
"QXmlEntityResolver",
"QXmlErrorHandler",
"QXmlInputSource",
"QXmlLexicalHandler",
"QXmlLocator",
"QXmlNamespaceSupport",
"QXmlParseException",
"QXmlReader",
"QXmlSimpleReader"
],
"QtXmlPatterns": [
"QAbstractMessageHandler",
"QAbstractUriResolver",
"QAbstractXmlNodeModel",
"QAbstractXmlReceiver",
"QSourceLocation",
"QXmlFormatter",
"QXmlItem",
"QXmlName",
"QXmlNamePool",
"QXmlNodeModelIndex",
"QXmlQuery",
"QXmlResultItems",
"QXmlSchema",
"QXmlSchemaValidator",
"QXmlSerializer"
]
}
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message handlers are passed 3 arguments
# The first argument is a QtMsgType
# The last argument is the message to be printed
# The Middle argument (if passed) is a QMessageLogContext
if len(args) == 3:
msgType, logContext, msg = args
elif len(args) == 2:
msgType, msg = args
logContext = None
else:
raise TypeError(
"handler expected 2 or 3 arguments, got {0}".format(len(args)))
if isinstance(msg, bytes):
# In python 3, some bindings pass a bytestring, which cannot be
# used elsewhere. Decoding a python 2 or 3 bytestring object will
# consistently return a unicode object.
msg = msg.decode()
handler(msgType, logContext, msg)
passObject = messageOutputHandler if handler else handler
if Qt.IsPySide or Qt.IsPyQt4:
return Qt._QtCore.qInstallMsgHandler(passObject)
elif Qt.IsPySide2 or Qt.IsPyQt5:
return Qt._QtCore.qInstallMessageHandler(passObject)
def _getcpppointer(object):
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").getCppPointer(object)[0]
elif hasattr(Qt, "_shiboken"):
return getattr(Qt, "_shiboken").getCppPointer(object)[0]
elif hasattr(Qt, "_sip"):
return getattr(Qt, "_sip").unwrapinstance(object)
raise AttributeError("'module' has no attribute 'getCppPointer'")
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not provided.
See :func:`QtCompat.wrapInstance()`
Arguments:
ptr (long): Pointer to QObject in memory
base (QObject, optional): Base class to wrap with. Defaults to QObject,
which should handle anything.
"""
assert isinstance(ptr, long), "Argument 'ptr' must be of type <long>"
assert (base is None) or issubclass(base, Qt.QtCore.QObject), (
"Argument 'base' must be of type <QObject>")
if Qt.IsPyQt4 or Qt.IsPyQt5:
func = getattr(Qt, "_sip").wrapinstance
elif Qt.IsPySide2:
func = getattr(Qt, "_shiboken2").wrapInstance
elif Qt.IsPySide:
func = getattr(Qt, "_shiboken").wrapInstance
else:
raise AttributeError("'module' has no attribute 'wrapInstance'")
if base is None:
q_object = func(long(ptr), Qt.QtCore.QObject)
meta_object = q_object.metaObject()
class_name = meta_object.className()
super_class_name = meta_object.superClass().className()
if hasattr(Qt.QtWidgets, class_name):
base = getattr(Qt.QtWidgets, class_name)
elif hasattr(Qt.QtWidgets, super_class_name):
base = getattr(Qt.QtWidgets, super_class_name)
else:
base = Qt.QtCore.QObject
return func(long(ptr), base)
def _translate(context, sourceText, *args):
# In Qt4 bindings, translate can be passed 2 or 3 arguments
# In Qt5 bindings, translate can be passed 2 arguments
# The first argument is disambiguation[str]
# The last argument is n[int]
# The middle argument can be encoding[QtCore.QCoreApplication.Encoding]
if len(args) == 3:
disambiguation, encoding, n = args
elif len(args) == 2:
disambiguation, n = args
encoding = None
else:
raise TypeError(
"Expected 4 or 5 arguments, got {0}.".format(len(args) + 2))
if hasattr(Qt.QtCore, "QCoreApplication"):
app = getattr(Qt.QtCore, "QCoreApplication")
else:
raise NotImplementedError(
"Missing QCoreApplication implementation for {binding}".format(
binding=Qt.__binding__,
)
)
if Qt.__binding__ in ("PySide2", "PyQt5"):
sanitized_args = [context, sourceText, disambiguation, n]
else:
sanitized_args = [
context,
sourceText,
disambiguation,
encoding or app.CodecForTr,
n
]
return app.translate(*sanitized_args)
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute path to Qt Designer file.
baseinstance (QWidget): Instantiated QWidget or subclass thereof
Return:
baseinstance if `baseinstance` is not `None`. Otherwise
return the newly created instance of the user interface.
"""
if hasattr(Qt, "_uic"):
return Qt._uic.loadUi(uifile, baseinstance)
elif hasattr(Qt, "_QtUiTools"):
# Implement `PyQt5.uic.loadUi` for PySide(2)
class _UiLoader(Qt._QtUiTools.QUiLoader):
"""Create the user interface in a base instance.
Unlike `Qt._QtUiTools.QUiLoader` itself this class does not
create a new instance of the top-level widget, but creates the user
interface in an existing instance of the top-level class if needed.
This mimics the behaviour of `PyQt5.uic.loadUi`.
"""
def __init__(self, baseinstance):
super(_UiLoader, self).__init__(baseinstance)
self.baseinstance = baseinstance
self.custom_widgets = {}
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them in createWidget method.
"""
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os separator by python module separator
return module.replace("/", ".").replace("\\", ".")
custom_widgets = etree.find("customwidgets")
if custom_widgets is None:
return
for custom_widget in custom_widgets:
class_name = custom_widget.find("class").text
header = custom_widget.find("header").text
module = importlib.import_module(headerToModule(header))
self.custom_widgets[class_name] = getattr(module,
class_name)
def load(self, uifile, *args, **kwargs):
from xml.etree.ElementTree import ElementTree
# For whatever reason, if this doesn't happen then
# reading an invalid or non-existing .ui file throws
# a RuntimeError.
etree = ElementTree()
etree.parse(uifile)
self._loadCustomWidgets(etree)
widget = Qt._QtUiTools.QUiLoader.load(
self, uifile, *args, **kwargs)
# Workaround for PySide 1.0.9, see issue #208
widget.parentWidget()
return widget
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-level widget,
# return the base instance instead
return self.baseinstance
# For some reason, Line is not in the list of available
# widgets, but works fine, so we have to special case it here.
if class_name in self.availableWidgets() + ["Line"]:
# Create a new widget for child widgets
widget = Qt._QtUiTools.QUiLoader.createWidget(self,
class_name,
parent,
name)
elif class_name in self.custom_widgets:
widget = self.custom_widgets[class_name](parent)
else:
raise Exception("Custom widget '%s' not supported"
% class_name)
if self.baseinstance:
# Set an attribute for the new child widget on the base
# instance, just like PyQt5.uic.loadUi does.
setattr(self.baseinstance, name, widget)
return widget
widget = _UiLoader(baseinstance).load(uifile)
Qt.QtCore.QMetaObject.connectSlotsByName(widget)
return widget
else:
raise NotImplementedError("No implementation available for loadUi")
"""Misplaced members
These members from the original submodule are misplaced relative PySide2
"""
_misplaced_members = {
"PySide2": {
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken2.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken2.getCppPointer": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt5": {
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtCore.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtCore.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtCore.QStringListModel": "QtCore.QStringListModel",
"QtCore.QItemSelection": "QtCore.QItemSelection",
"QtCore.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.QItemSelectionRange": "QtCore.QItemSelectionRange",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtWidgets.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtWidgets.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMessageHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PySide": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.Property": "QtCore.Property",
"QtCore.Signal": "QtCore.Signal",
"QtCore.Slot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
"QtUiTools.QUiLoader": ["QtCompat.loadUi", _loadUi],
"shiboken.wrapInstance": ["QtCompat.wrapInstance", _wrapinstance],
"shiboken.unwrapInstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
},
"PyQt4": {
"QtGui.QAbstractProxyModel": "QtCore.QAbstractProxyModel",
"QtGui.QSortFilterProxyModel": "QtCore.QSortFilterProxyModel",
"QtGui.QItemSelection": "QtCore.QItemSelection",
"QtGui.QStringListModel": "QtCore.QStringListModel",
"QtGui.QItemSelectionModel": "QtCore.QItemSelectionModel",
"QtCore.pyqtProperty": "QtCore.Property",
"QtCore.pyqtSignal": "QtCore.Signal",
"QtCore.pyqtSlot": "QtCore.Slot",
"QtGui.QItemSelectionRange": "QtCore.QItemSelectionRange",
"QtGui.QAbstractPrintDialog": "QtPrintSupport.QAbstractPrintDialog",
"QtGui.QPageSetupDialog": "QtPrintSupport.QPageSetupDialog",
"QtGui.QPrintDialog": "QtPrintSupport.QPrintDialog",
"QtGui.QPrintEngine": "QtPrintSupport.QPrintEngine",
"QtGui.QPrintPreviewDialog": "QtPrintSupport.QPrintPreviewDialog",
"QtGui.QPrintPreviewWidget": "QtPrintSupport.QPrintPreviewWidget",
"QtGui.QPrinter": "QtPrintSupport.QPrinter",
"QtGui.QPrinterInfo": "QtPrintSupport.QPrinterInfo",
# "QtCore.pyqtSignature": "QtCore.Slot",
"uic.loadUi": ["QtCompat.loadUi", _loadUi],
"sip.wrapinstance": ["QtCompat.wrapInstance", _wrapinstance],
"sip.unwrapinstance": ["QtCompat.getCppPointer", _getcpppointer],
"QtCore.QString": "str",
"QtGui.qApp": "QtWidgets.QApplication.instance()",
"QtCore.QCoreApplication.translate": [
"QtCompat.translate", _translate
],
"QtGui.QApplication.translate": [
"QtCompat.translate", _translate
],
"QtCore.qInstallMsgHandler": [
"QtCompat.qInstallMessageHandler", _qInstallMessageHandler
],
}
}
""" Compatibility Members
This dictionary is used to build Qt.QtCompat objects that provide a consistent
interface for obsolete members, and differences in binding return values.
{
"binding": {
"classname": {
"targetname": "binding_namespace",
}
}
}
"""
_compatibility_members = {
"PySide2": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt5": {
"QWidget": {
"grab": "QtWidgets.QWidget.grab",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.sectionsClickable",
"setSectionsClickable":
"QtWidgets.QHeaderView.setSectionsClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.sectionResizeMode",
"setSectionResizeMode":
"QtWidgets.QHeaderView.setSectionResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.sectionsMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setSectionsMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PySide": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
"PyQt4": {
"QWidget": {
"grab": "QtWidgets.QPixmap.grabWidget",
},
"QHeaderView": {
"sectionsClickable": "QtWidgets.QHeaderView.isClickable",
"setSectionsClickable": "QtWidgets.QHeaderView.setClickable",
"sectionResizeMode": "QtWidgets.QHeaderView.resizeMode",
"setSectionResizeMode": "QtWidgets.QHeaderView.setResizeMode",
"sectionsMovable": "QtWidgets.QHeaderView.isMovable",
"setSectionsMovable": "QtWidgets.QHeaderView.setMovable",
},
"QFileDialog": {
"getOpenFileName": "QtWidgets.QFileDialog.getOpenFileName",
"getOpenFileNames": "QtWidgets.QFileDialog.getOpenFileNames",
"getSaveFileName": "QtWidgets.QFileDialog.getSaveFileName",
},
},
}
def _apply_site_config():
try:
import QtSiteConfig
except ImportError:
# If no QtSiteConfig module found, no modifications
# to _common_members are needed.
pass
else:
# Provide the ability to modify the dicts used to build Qt.py
if hasattr(QtSiteConfig, 'update_members'):
QtSiteConfig.update_members(_common_members)
if hasattr(QtSiteConfig, 'update_misplaced_members'):
QtSiteConfig.update_misplaced_members(members=_misplaced_members)
if hasattr(QtSiteConfig, 'update_compatibility_members'):
QtSiteConfig.update_compatibility_members(
members=_compatibility_members)
def _new_module(name):
return types.ModuleType(__name__ + "." + name)
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(
module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, "_" + name, submodule)
if name not in extras:
# Store reference to original binding,
# but don't store speciality modules
# such as uic or QtUiTools
setattr(Qt, name, _new_module(name))
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
src_member = None
if len(src_parts) > 1:
src_member = src_parts[1:]
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
dst_parts = dst.split(".")
dst_module = dst_parts[0]
dst_member = None
if len(dst_parts) > 1:
dst_member = dst_parts[1]
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, "_" + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log("Misplaced member has no source: {0}".format(src))
continue
try:
src_object = getattr(Qt, dst_module)
except AttributeError:
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = 'Not creating missing member module "{m}" for "{c}"'
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + "." + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, "_" + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type("QtCompat", (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, "_" + namespaces[0])
except AttributeError as e:
_log("QtCompat: AttributeError: %s" % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken2
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide2 import shiboken2
extras.append("shiboken2")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken2"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PySide2")
_build_compatibility_members("PySide2")
def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide")
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
if hasattr(Qt, "_QtWidgets"):
Qt.QtCompat.setSectionResizeMode = \
Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members("PyQt5")
_build_compatibility_members('PyQt5')
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError:
raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2")
for api in ("QString",
"QVariant",
"QDate",
"QDateTime",
"QTextStream",
"QTime",
"QUrl"):
try:
sip.setapi(api, hint or 2)
except AttributeError:
raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py")
except ValueError:
actual = sip.getapi(api)
if not hint:
raise ImportError("API version already set to %d" % actual)
else:
# Having provided a hint indicates a soft constraint, one
# that doesn't throw an exception.
sys.stderr.write(
"Warning: API '%s' has already been set to %d.\n"
% (api, actual)
)
import PyQt4 as module
extras = ["uic"]
try:
import sip
extras.append(sip.__name__)
except ImportError:
sip = None
_setup(module, extras)
if hasattr(Qt, "_sip"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = sip.delete
if hasattr(Qt, "_uic"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = \
Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
_reassign_misplaced_members("PyQt4")
# QFileDialog QtCompat decorator
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selected filename, and a empty string
# for the selected filter
return ret, ''
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators = {
"QFileDialog": {
"getOpenFileName": _standardizeQFileDialog,
"getOpenFileNames": _standardizeQFileDialog,
"getSaveFileName": _standardizeQFileDialog,
}
}
_build_compatibility_members('PyQt4', decorators)
def _none():
"""Internal option (used in installer)"""
Mock = type("Mock", (), {"__getattr__": lambda Qt, attr: None})
Qt.__binding__ = "None"
Qt.__qt_version__ = "0.0.0"
Qt.__binding_version__ = "0.0.0"
Qt.QtCompat.loadUi = lambda uifile, baseinstance=None: None
Qt.QtCompat.setSectionResizeMode = lambda *args, **kwargs: None
for submodule in _common_members.keys():
setattr(Qt, submodule, Mock())
setattr(Qt, "_" + submodule, Mock())
def _log(text):
if QT_VERBOSE:
sys.stdout.write(text + "\n")
def _cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
"# for details.\n"
"#\n")
#
# ------> Read
#
with open(args.convert) as f:
lines = _convert(f.readlines())
backup = "%s_backup%s" % os.path.splitext(args.convert)
sys.stdout.write("Creating \"%s\"..\n" % backup)
shutil.copy(args.convert, backup)
#
# <------ Write
#
with open(args.convert, "w") as f:
f.write("".join(lines))
sys.stdout.write("Successfully converted \"%s\"\n" % args.convert)
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
default_order = ("PySide2", "PyQt5", "PySide", "PyQt4")
preferred_order = list(
b for b in QT_PREFERRED_BINDING.split(os.pathsep) if b
)
order = preferred_order or default_order
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4,
"None": _none
}
_log("Order: '%s'" % "', '".join(order))
# Allow site-level customization of the available modules.
_apply_site_config()
found_binding = False
for name in order:
_log("Trying %s" % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log("ImportError: %s" % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, "_%s" % name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + "." + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
# Backwards compatibility
if hasattr(Qt.QtCompat, 'loadUi'):
Qt.QtCompat.load_ui = Qt.QtCompat.loadUi
_install()
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = Qt.__binding__ == 'PyQt5'
Qt.IsPySide = Qt.__binding__ == 'PySide'
Qt.IsPyQt4 = Qt.__binding__ == 'PyQt4'
"""Augment QtCompat
QtCompat contains wrappers and added functionality
to the original bindings, such as the CLI interface
and otherwise incompatible members between bindings,
such as `QHeaderView.setSectionResizeMode`.
"""
Qt.QtCompat._cli = _cli
Qt.QtCompat._convert = _convert
# Enable command-line interface
if __name__ == "__main__":
_cli(sys.argv[1:])
# The MIT License (MIT)
#
# Copyright (c) 2016-2017 Marcus Ottosson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# In PySide(2), loadUi does not exist, so we implement it
#
# `_UiLoader` is adapted from the qtpy project, which was further influenced
# by qt-helpers which was released under a 3-clause BSD license which in turn
# is based on a solution at:
#
# - https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# The License for this code is as follows:
#
# qt-helpers - a common front-end to various Qt modules
#
# Copyright (c) 2015, Chris Beaumont and Thomas Robitaille
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the Glue project nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR
# CONTRIBUTORS 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.
#
# Which itself was based on the solution at
#
# https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8
#
# which was released under the MIT license:
#
# Copyright (c) 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# Modifications by Charl Botha <cpbotha@vxlabs.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files
# (the "Software"),to deal in the Software without restriction,
# including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
mottosso/Qt.py | examples/QtSiteConfig/QtSiteConfig.py | update_compatibility_decorators | python | def update_compatibility_decorators(binding, decorators):
def _widgetDecorator(some_function):
def wrapper(*args, **kwargs):
ret = some_function(*args, **kwargs)
# Modifies the returned value so we can test that the
# decorator works.
return "Test: {}".format(ret)
# preserve docstring and name of original function
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
# Assign a different decorator for the same method name on each class
def _mainWindowDecorator(some_function):
def wrapper(*args, **kwargs):
ret = some_function(*args, **kwargs)
# Modifies the returned value so we can test that the
# decorator works.
return "QMainWindow Test: {}".format(ret)
# preserve docstring and name of original function
wrapper.__doc__ = some_function.__doc__
wrapper.__name__ = some_function.__name__
return wrapper
decorators.setdefault("QWidget", {})["windowTitleDecorator"] = (
_widgetDecorator
)
decorators.setdefault("QMainWindow", {})["windowTitleDecorator"] = (
_mainWindowDecorator
) | This optional function is called by Qt.py to modify the decorators
applied to QtCompat namespace objects.
Arguments:
binding (str): The Qt binding being wrapped by Qt.py
decorators (dict): Maps specific decorator functions to
QtCompat namespace methods. See Qt._build_compatibility_members
for more info. | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/QtSiteConfig/QtSiteConfig.py#L53-L91 | null | # Contrived example used for unit testing. For a more realistic example
# see the README
def update_members(members):
"""This optional function is called by Qt.py to modify the modules exposed.
Arguments:
members (dict): The members considered by Qt.py
"""
# Contrived example used for unit testing. This makes the QtCore module
# not accessible. I chose this so it can be tested everywhere, for a
# more realistic example see the README
members.pop("QtCore")
def update_misplaced_members(members):
"""This optional function is called by Qt.py to standardize the location
and naming of exposed classes.
Arguments:
members (dict): The members considered by Qt.py
"""
# Create Qt.QtGui.QColorTest that points to Qtgui.QColor for unit testing.
members["PySide2"]["QtGui.QColor"] = "QtGui.QColorTest"
members["PyQt5"]["QtGui.QColor"] = "QtGui.QColorTest"
members["PySide"]["QtGui.QColor"] = "QtGui.QColorTest"
members["PyQt4"]["QtGui.QColor"] = "QtGui.QColorTest"
def update_compatibility_members(members):
"""This optional function is called by Qt.py to modify the structure of
QtCompat namespace classes.
Arguments:
members (dict): The members considered by Qt.py
"""
# Create a QtCompat.QWidget compatibility class. This example is
# is used to provide a testable unittest
for binding in ("PySide2", "PyQt5", "PySide", "PyQt4"):
members[binding]["QWidget"] = {
# Simple remapping of QWidget.windowTitle
"windowTitleTest": "QtWidgets.QWidget.windowTitle",
# Remap QWidget.windowTitle with a decorator that modifies
# the returned value.
"windowTitleDecorator": "QtWidgets.QWidget.windowTitle",
}
members[binding]["QMainWindow"] = {
"windowTitleDecorator": "QtWidgets.QMainWindow.windowTitle"
}
|
mottosso/Qt.py | examples/loadUi/baseinstance2.py | load_ui_type | python | def load_ui_type(uifile):
import pysideuic
import xml.etree.ElementTree as ElementTree
from cStringIO import StringIO
parsed = ElementTree.parse(uifile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uifile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec(pyc) in frame
# Fetch the base_class and form class based on their type in
# the xml from designer
form_class = frame['Ui_%s' % form_class]
base_class = eval('QtWidgets.%s' % widget_class)
return form_class, base_class | Pyside equivalent for the loadUiType function in PyQt.
From the PyQt4 documentation:
Load a Qt Designer .ui file and return a tuple of the generated form
class and the Qt base class. These can then be used to create any
number of instances of the user interface without having to parse the
.ui file more than once.
Note:
Pyside lacks the "loadUiType" command, so we have to convert the ui
file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
Args:
uifile (str): Absolute path to .ui file
Returns:
tuple: the generated form class, the Qt base class | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L10-L51 | null | import sys
import os
# Set preferred binding, or Qt.py tests will fail which doesn't have pysideuic
os.environ['QT_PREFERRED_BINDING'] = 'PyQt4'
from Qt import QtWidgets, __binding__
def pyside_load_ui(uifile, base_instance=None):
"""Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
This seems to work correctly in Maya as well as outside of it as
opposed to other implementations which involve overriding QUiLoader.
Returns:
QWidget: the base instance
"""
form_class, base_class = load_ui_type(uifile)
if not base_instance:
typeName = form_class.__name__
finalType = type(typeName,
(form_class, base_class),
{})
base_instance = finalType()
else:
if not isinstance(base_instance, base_class):
raise RuntimeError(
'The base_instance passed to loadUi does not inherit from'
' needed base type (%s)' % type(base_class))
typeName = type(base_instance).__name__
base_instance.__class__ = type(typeName,
(form_class, type(base_instance)),
{})
base_instance.setupUi(base_instance)
return base_instance
def load_ui_wrapper(uifile, base_instance=None):
"""Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
function: pyside_load_ui or uic.loadUi
"""
if 'PySide' in __binding__:
return pyside_load_ui(uifile, base_instance)
elif 'PyQt' in __binding__:
uic = __import__(__binding__ + ".uic").uic
return uic.loadUi(uifile, base_instance)
class MainWindow(QtWidgets.QWidget):
"""Load .ui file example, utilizing pysideuic and/or PyQt4.uic.loadUi"""
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.base_instance = load_ui_wrapper('qwidget.ui', self)
def test():
"""Example: load_ui with custom uic.loadUi-like wrapper"""
working_directory = os.path.dirname(__file__)
os.chdir(working_directory)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window, QtWidgets.QWidget)
assert isinstance(window.parent(), type(None))
assert isinstance(window.base_instance, QtWidgets.QWidget)
assert isinstance(window.lineEdit, QtWidgets.QWidget)
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
|
mottosso/Qt.py | examples/loadUi/baseinstance2.py | pyside_load_ui | python | def pyside_load_ui(uifile, base_instance=None):
form_class, base_class = load_ui_type(uifile)
if not base_instance:
typeName = form_class.__name__
finalType = type(typeName,
(form_class, base_class),
{})
base_instance = finalType()
else:
if not isinstance(base_instance, base_class):
raise RuntimeError(
'The base_instance passed to loadUi does not inherit from'
' needed base type (%s)' % type(base_class))
typeName = type(base_instance).__name__
base_instance.__class__ = type(typeName,
(form_class, type(base_instance)),
{})
base_instance.setupUi(base_instance)
return base_instance | Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
This seems to work correctly in Maya as well as outside of it as
opposed to other implementations which involve overriding QUiLoader.
Returns:
QWidget: the base instance | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L54-L89 | [
"def load_ui_type(uifile):\n \"\"\"Pyside equivalent for the loadUiType function in PyQt.\n\n From the PyQt4 documentation:\n Load a Qt Designer .ui file and return a tuple of the generated form\n class and the Qt base class. These can then be used to create any\n number of instances of t... | import sys
import os
# Set preferred binding, or Qt.py tests will fail which doesn't have pysideuic
os.environ['QT_PREFERRED_BINDING'] = 'PyQt4'
from Qt import QtWidgets, __binding__
def load_ui_type(uifile):
"""Pyside equivalent for the loadUiType function in PyQt.
From the PyQt4 documentation:
Load a Qt Designer .ui file and return a tuple of the generated form
class and the Qt base class. These can then be used to create any
number of instances of the user interface without having to parse the
.ui file more than once.
Note:
Pyside lacks the "loadUiType" command, so we have to convert the ui
file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
Args:
uifile (str): Absolute path to .ui file
Returns:
tuple: the generated form class, the Qt base class
"""
import pysideuic
import xml.etree.ElementTree as ElementTree
from cStringIO import StringIO
parsed = ElementTree.parse(uifile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uifile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec(pyc) in frame
# Fetch the base_class and form class based on their type in
# the xml from designer
form_class = frame['Ui_%s' % form_class]
base_class = eval('QtWidgets.%s' % widget_class)
return form_class, base_class
def load_ui_wrapper(uifile, base_instance=None):
"""Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
function: pyside_load_ui or uic.loadUi
"""
if 'PySide' in __binding__:
return pyside_load_ui(uifile, base_instance)
elif 'PyQt' in __binding__:
uic = __import__(__binding__ + ".uic").uic
return uic.loadUi(uifile, base_instance)
class MainWindow(QtWidgets.QWidget):
"""Load .ui file example, utilizing pysideuic and/or PyQt4.uic.loadUi"""
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.base_instance = load_ui_wrapper('qwidget.ui', self)
def test():
"""Example: load_ui with custom uic.loadUi-like wrapper"""
working_directory = os.path.dirname(__file__)
os.chdir(working_directory)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window, QtWidgets.QWidget)
assert isinstance(window.parent(), type(None))
assert isinstance(window.base_instance, QtWidgets.QWidget)
assert isinstance(window.lineEdit, QtWidgets.QWidget)
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
|
mottosso/Qt.py | examples/loadUi/baseinstance2.py | load_ui_wrapper | python | def load_ui_wrapper(uifile, base_instance=None):
if 'PySide' in __binding__:
return pyside_load_ui(uifile, base_instance)
elif 'PyQt' in __binding__:
uic = __import__(__binding__ + ".uic").uic
return uic.loadUi(uifile, base_instance) | Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
function: pyside_load_ui or uic.loadUi | train | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L92-L107 | [
"def pyside_load_ui(uifile, base_instance=None):\n \"\"\"Provide PyQt4.uic.loadUi functionality to PySide\n\n Args:\n uifile (str): Absolute path to .ui file\n base_instance (QWidget): The widget into which UI widgets are loaded\n\n\n Note:\n pysideuic is required for this to work with... | import sys
import os
# Set preferred binding, or Qt.py tests will fail which doesn't have pysideuic
os.environ['QT_PREFERRED_BINDING'] = 'PyQt4'
from Qt import QtWidgets, __binding__
def load_ui_type(uifile):
"""Pyside equivalent for the loadUiType function in PyQt.
From the PyQt4 documentation:
Load a Qt Designer .ui file and return a tuple of the generated form
class and the Qt base class. These can then be used to create any
number of instances of the user interface without having to parse the
.ui file more than once.
Note:
Pyside lacks the "loadUiType" command, so we have to convert the ui
file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
Args:
uifile (str): Absolute path to .ui file
Returns:
tuple: the generated form class, the Qt base class
"""
import pysideuic
import xml.etree.ElementTree as ElementTree
from cStringIO import StringIO
parsed = ElementTree.parse(uifile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uifile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec(pyc) in frame
# Fetch the base_class and form class based on their type in
# the xml from designer
form_class = frame['Ui_%s' % form_class]
base_class = eval('QtWidgets.%s' % widget_class)
return form_class, base_class
def pyside_load_ui(uifile, base_instance=None):
"""Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
This seems to work correctly in Maya as well as outside of it as
opposed to other implementations which involve overriding QUiLoader.
Returns:
QWidget: the base instance
"""
form_class, base_class = load_ui_type(uifile)
if not base_instance:
typeName = form_class.__name__
finalType = type(typeName,
(form_class, base_class),
{})
base_instance = finalType()
else:
if not isinstance(base_instance, base_class):
raise RuntimeError(
'The base_instance passed to loadUi does not inherit from'
' needed base type (%s)' % type(base_class))
typeName = type(base_instance).__name__
base_instance.__class__ = type(typeName,
(form_class, type(base_instance)),
{})
base_instance.setupUi(base_instance)
return base_instance
class MainWindow(QtWidgets.QWidget):
"""Load .ui file example, utilizing pysideuic and/or PyQt4.uic.loadUi"""
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.base_instance = load_ui_wrapper('qwidget.ui', self)
def test():
"""Example: load_ui with custom uic.loadUi-like wrapper"""
working_directory = os.path.dirname(__file__)
os.chdir(working_directory)
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window, QtWidgets.QWidget)
assert isinstance(window.parent(), type(None))
assert isinstance(window.base_instance, QtWidgets.QWidget)
assert isinstance(window.lineEdit, QtWidgets.QWidget)
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
|
ihabunek/toot | toot/wcstring.py | _wc_hard_wrap | python | def _wc_hard_wrap(line, length):
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars) | Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L10-L30 | null | """
Utilities for dealing with string containing wide characters.
"""
import re
from wcwidth import wcwidth, wcswidth
def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…'
def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text
def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text
|
ihabunek/toot | toot/wcstring.py | wc_wrap | python | def wc_wrap(text, length):
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length) | Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L33-L66 | [
"def _wc_hard_wrap(line, length):\n \"\"\"\n Wrap text to length characters, breaking when target length is reached,\n taking into account character width.\n\n Used to wrap lines which cannot be wrapped on whitespace.\n \"\"\"\n chars = []\n chars_len = 0\n for char in line:\n char_le... | """
Utilities for dealing with string containing wide characters.
"""
import re
from wcwidth import wcwidth, wcswidth
def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars)
def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…'
def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text
def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text
|
ihabunek/toot | toot/wcstring.py | trunc | python | def trunc(text, length):
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…' | Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L69-L98 | null | """
Utilities for dealing with string containing wide characters.
"""
import re
from wcwidth import wcwidth, wcswidth
def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars)
def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text
def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text
|
ihabunek/toot | toot/wcstring.py | pad | python | def pad(text, length):
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text | Pads text to given length, taking into account wide characters. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L101-L108 | null | """
Utilities for dealing with string containing wide characters.
"""
import re
from wcwidth import wcwidth, wcswidth
def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars)
def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…'
def fit_text(text, length):
"""Makes text fit the given length by padding or truncating it."""
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text
|
ihabunek/toot | toot/wcstring.py | fit_text | python | def fit_text(text, length):
text_length = wcswidth(text)
if text_length > length:
return trunc(text, length)
if text_length < length:
return pad(text, length)
return text | Makes text fit the given length by padding or truncating it. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L111-L121 | [
"def pad(text, length):\n \"\"\"Pads text to given length, taking into account wide characters.\"\"\"\n text_length = wcswidth(text)\n\n if text_length < length:\n return text + ' ' * (length - text_length)\n\n return text\n",
"def trunc(text, length):\n \"\"\"\n Truncates text to given l... | """
Utilities for dealing with string containing wide characters.
"""
import re
from wcwidth import wcwidth, wcswidth
def _wc_hard_wrap(line, length):
"""
Wrap text to length characters, breaking when target length is reached,
taking into account character width.
Used to wrap lines which cannot be wrapped on whitespace.
"""
chars = []
chars_len = 0
for char in line:
char_len = wcwidth(char)
if chars_len + char_len > length:
yield "".join(chars)
chars = []
chars_len = 0
chars.append(char)
chars_len += char_len
if chars:
yield "".join(chars)
def wc_wrap(text, length):
"""
Wrap text to given length, breaking on whitespace and taking into account
character width.
Meant for use on a single line or paragraph. Will destroy spacing between
words and paragraphs and any indentation.
"""
line_words = []
line_len = 0
words = re.split(r"\s+", text.strip())
for word in words:
word_len = wcswidth(word)
if line_words and line_len + word_len > length:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
line_words = []
line_len = 0
line_words.append(word)
line_len += word_len + 1 # add 1 to account for space between words
if line_words:
line = " ".join(line_words)
if line_len <= length:
yield line
else:
yield from _wc_hard_wrap(line, length)
def trunc(text, length):
"""
Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis.
"""
if length < 1:
raise ValueError("length should be 1 or larger")
# Remove whitespace first so no unneccesary truncation is done.
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
# We cannot just remove n characters from the end since we don't know how
# wide these characters are and how it will affect text length.
# Use wcwidth to determine how many characters need to be truncated.
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
trunc_length += wcwidth(char)
if text_length - trunc_length <= length:
break
# Additional char to make room for elipsis
n = chars_to_truncate + 1
return text[:-n].strip() + '…'
def pad(text, length):
"""Pads text to given length, taking into account wide characters."""
text_length = wcswidth(text)
if text_length < length:
return text + ' ' * (length - text_length)
return text
|
ihabunek/toot | toot/http.py | _get_error_message | python | def _get_error_message(response):
try:
data = response.json()
if "error_description" in data:
return data['error_description']
if "error" in data:
return data['error']
except Exception:
pass
return "Unknown error" | Attempt to extract an error message from response body | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/http.py#L19-L30 | null | from requests import Request, Session
from toot.exceptions import NotFoundError, ApiError
from toot.logging import log_request, log_response
def send_request(request, allow_redirects=True):
log_request(request)
with Session() as session:
prepared = session.prepare_request(request)
settings = session.merge_environment_settings(prepared.url, {}, None, None, None)
response = session.send(prepared, allow_redirects=allow_redirects, **settings)
log_response(response)
return response
def process_response(response):
if not response.ok:
error = _get_error_message(response)
if response.status_code == 404:
raise NotFoundError(error)
raise ApiError(error)
return response
def get(app, user, url, params=None):
url = app.base_url + url
headers = {"Authorization": "Bearer " + user.access_token}
request = Request('GET', url, headers, params=params)
response = send_request(request)
return process_response(response)
def anon_get(url, params=None):
request = Request('GET', url, None, params=params)
response = send_request(request)
return process_response(response)
def post(app, user, url, data=None, files=None, allow_redirects=True, headers={}):
url = app.base_url + url
headers["Authorization"] = "Bearer " + user.access_token
request = Request('POST', url, headers, files, data)
response = send_request(request, allow_redirects)
return process_response(response)
def delete(app, user, url, data=None):
url = app.base_url + url
headers = {"Authorization": "Bearer " + user.access_token}
request = Request('DELETE', url, headers=headers, data=data)
response = send_request(request)
return process_response(response)
def anon_post(url, data=None, files=None, allow_redirects=True):
request = Request('POST', url, {}, files, data)
response = send_request(request, allow_redirects)
return process_response(response)
|
ihabunek/toot | toot/config.py | make_config | python | def make_config(path):
apps, user = load_legacy_config()
apps = {a.instance: a._asdict() for a in apps}
users = {user_id(user): user._asdict()} if user else {}
active_user = user_id(user) if user else None
config = {
"apps": apps,
"users": users,
"active_user": active_user,
}
print_out("Creating config file at <blue>{}</blue>".format(path))
# Ensure dir exists
os.makedirs(dirname(path), exist_ok=True)
with open(path, 'w') as f:
json.dump(config, f, indent=True) | Creates a config file.
Attempts to load data from legacy config files if they exist. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/config.py#L33-L56 | [
"def print_out(*args, **kwargs):\n if not QUIET:\n args = [colorize(a) if USE_ANSI_COLOR else strip_tags(a) for a in args]\n print(*args, **kwargs)\n",
"def user_id(user):\n return \"{}@{}\".format(user.username, user.instance)\n",
"def load_legacy_config():\n apps = list(load_apps(INSTAN... | # -*- coding: utf-8 -*-
import os
import json
from functools import wraps
from os.path import dirname
from toot import User, App
from toot.config_legacy import load_legacy_config
from toot.exceptions import ConsoleError
from toot.output import print_out
def get_config_file_path():
"""Returns the path to toot config file
Attempts to locate config home dir from XDG_CONFIG_HOME env variable.
See: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html#variables
If not found, defaults to `~/.config`.
"""
config_dir = os.getenv('XDG_CONFIG_HOME', '~/.config')
return os.path.expanduser(config_dir + '/toot/config.json')
CONFIG_FILE = get_config_file_path()
def user_id(user):
return "{}@{}".format(user.username, user.instance)
def load_config():
if not os.path.exists(CONFIG_FILE):
make_config(CONFIG_FILE)
with open(CONFIG_FILE) as f:
return json.load(f)
def save_config(config):
with open(CONFIG_FILE, 'w') as f:
return json.dump(config, f, indent=True)
def extract_user_app(config, user_id):
if user_id not in config['users']:
return None, None
user_data = config['users'][user_id]
instance = user_data['instance']
if instance not in config['apps']:
return None, None
app_data = config['apps'][instance]
return User(**user_data), App(**app_data)
def get_active_user_app():
"""Returns (User, App) of active user or (None, None) if no user is active."""
config = load_config()
if config['active_user']:
return extract_user_app(config, config['active_user'])
return None, None
def get_user_app(user_id):
"""Returns (User, App) for given user ID or (None, None) if user is not logged in."""
return extract_user_app(load_config(), user_id)
def load_app(instance):
config = load_config()
if instance in config['apps']:
return App(**config['apps'][instance])
def load_user(user_id, throw=False):
config = load_config()
if user_id in config['users']:
return User(**config['users'][user_id])
if throw:
raise ConsoleError("User '{}' not found".format(user_id))
def modify_config(f):
@wraps(f)
def wrapper(*args, **kwargs):
config = load_config()
config = f(config, *args, **kwargs)
save_config(config)
return config
return wrapper
@modify_config
def save_app(config, app):
assert isinstance(app, App)
config['apps'][app.instance] = app._asdict()
return config
@modify_config
def delete_app(config, app):
assert isinstance(app, App)
config['apps'].pop(app.instance, None)
return config
@modify_config
def save_user(config, user, activate=True):
assert isinstance(user, User)
config['users'][user_id(user)] = user._asdict()
if activate:
config['active_user'] = user_id(user)
return config
@modify_config
def delete_user(config, user):
assert isinstance(user, User)
config['users'].pop(user_id(user), None)
if config['active_user'] == user_id(user):
config['active_user'] = None
return config
@modify_config
def activate_user(config, user):
assert isinstance(user, User)
config['active_user'] = user_id(user)
return config
|
ihabunek/toot | toot/api.py | post_status | python | def post_status(
app,
user,
status,
visibility='public',
media_ids=None,
sensitive=False,
spoiler_text=None,
in_reply_to_id=None
):
# Idempotency key assures the same status is not posted multiple times
# if the request is retried.
headers = {"Idempotency-Key": uuid.uuid4().hex}
return http.post(app, user, '/api/v1/statuses', {
'status': status,
'media_ids[]': media_ids,
'visibility': visibility,
'sensitive': str_bool(sensitive),
'spoiler_text': spoiler_text,
'in_reply_to_id': in_reply_to_id,
}, headers=headers).json() | Posts a new status.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/api.py#L87-L113 | [
"def str_bool(b):\n \"\"\"Convert boolean to string, in the way expected by the API.\"\"\"\n return \"true\" if b else \"false\"\n",
"def post(app, user, url, data=None, files=None, allow_redirects=True, headers={}):\n url = app.base_url + url\n\n headers[\"Authorization\"] = \"Bearer \" + user.access... | # -*- coding: utf-8 -*-
import re
import uuid
from urllib.parse import urlparse, urlencode, quote
from toot import http, CLIENT_NAME, CLIENT_WEBSITE
from toot.exceptions import AuthenticationError
from toot.utils import str_bool
SCOPES = 'read write follow'
def _account_action(app, user, account, action):
url = '/api/v1/accounts/{}/{}'.format(account, action)
return http.post(app, user, url).json()
def _status_action(app, user, status_id, action):
url = '/api/v1/statuses/{}/{}'.format(status_id, action)
return http.post(app, user, url).json()
def create_app(domain, scheme='https'):
url = '{}://{}/api/v1/apps'.format(scheme, domain)
data = {
'client_name': CLIENT_NAME,
'redirect_uris': 'urn:ietf:wg:oauth:2.0:oob',
'scopes': SCOPES,
'website': CLIENT_WEBSITE,
}
return http.anon_post(url, data).json()
def login(app, username, password):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'password',
'client_id': app.client_id,
'client_secret': app.client_secret,
'username': username,
'password': password,
'scope': SCOPES,
}
response = http.anon_post(url, data, allow_redirects=False)
# If auth fails, it redirects to the login page
if response.is_redirect:
raise AuthenticationError()
return http.process_response(response).json()
def get_browser_login_url(app):
"""Returns the URL for manual log in via browser"""
return "{}/oauth/authorize/?{}".format(app.base_url, urlencode({
"response_type": "code",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"scope": SCOPES,
"client_id": app.client_id,
}))
def request_access_token(app, authorization_code):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'authorization_code',
'client_id': app.client_id,
'client_secret': app.client_secret,
'code': authorization_code,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
}
response = http.anon_post(url, data, allow_redirects=False)
return http.process_response(response).json()
def delete_status(app, user, status_id):
"""
Deletes a status with given ID.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#deleting-a-status
"""
return http.delete(app, user, '/api/v1/statuses/{}'.format(status_id))
def favourite(app, user, status_id):
return _status_action(app, user, status_id, 'favourite')
def unfavourite(app, user, status_id):
return _status_action(app, user, status_id, 'unfavourite')
def reblog(app, user, status_id):
return _status_action(app, user, status_id, 'reblog')
def unreblog(app, user, status_id):
return _status_action(app, user, status_id, 'unreblog')
def pin(app, user, status_id):
return _status_action(app, user, status_id, 'pin')
def unpin(app, user, status_id):
return _status_action(app, user, status_id, 'unpin')
def context(app, user, status_id):
url = '/api/v1/statuses/{}/context'.format(status_id)
return http.get(app, user, url).json()
def reblogged_by(app, user, status_id):
url = '/api/v1/statuses/{}/reblogged_by'.format(status_id)
return http.get(app, user, url).json()
def _get_next_path(headers):
"""Given timeline response headers, returns the path to the next batch"""
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query])
def _timeline_generator(app, user, path, params=None):
while path:
response = http.get(app, user, path, params)
yield response.json()
path = _get_next_path(response.headers)
def _anon_timeline_generator(instance, path, params=None):
while path:
url = "https://{}{}".format(instance, path)
response = http.anon_get(url, params)
yield response.json()
path = _get_next_path(response.headers)
def home_timeline_generator(app, user, limit=20):
path = '/api/v1/timelines/home?limit={}'.format(limit)
return _timeline_generator(app, user, path)
def public_timeline_generator(instance, local=False, limit=20):
path = '/api/v1/timelines/public'
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def tag_timeline_generator(instance, hashtag, local=False, limit=20):
path = '/api/v1/timelines/tag/{}'.format(hashtag)
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def timeline_list_generator(app, user, list_id, limit=20):
path = '/api/v1/timelines/list/{}'.format(list_id)
return _timeline_generator(app, user, path, {'limit': limit})
def upload_media(app, user, file):
return http.post(app, user, '/api/v1/media', files={
'file': file
}).json()
def search(app, user, query, resolve):
return http.get(app, user, '/api/v1/search', {
'q': query,
'resolve': resolve,
}).json()
def search_accounts(app, user, query):
return http.get(app, user, '/api/v1/accounts/search', {
'q': query,
}).json()
def follow(app, user, account):
return _account_action(app, user, account, 'follow')
def unfollow(app, user, account):
return _account_action(app, user, account, 'unfollow')
def mute(app, user, account):
return _account_action(app, user, account, 'mute')
def unmute(app, user, account):
return _account_action(app, user, account, 'unmute')
def block(app, user, account):
return _account_action(app, user, account, 'block')
def unblock(app, user, account):
return _account_action(app, user, account, 'unblock')
def verify_credentials(app, user):
return http.get(app, user, '/api/v1/accounts/verify_credentials').json()
def single_status(app, user, status_id):
url = '/api/v1/statuses/{}'.format(status_id)
return http.get(app, user, url).json()
def get_notifications(app, user):
return http.get(app, user, '/api/v1/notifications').json()
def clear_notifications(app, user):
http.post(app, user, '/api/v1/notifications/clear')
def get_instance(domain, scheme="https"):
url = "{}://{}/api/v1/instance".format(scheme, domain)
return http.anon_get(url).json()
|
ihabunek/toot | toot/api.py | delete_status | python | def delete_status(app, user, status_id):
return http.delete(app, user, '/api/v1/statuses/{}'.format(status_id)) | Deletes a status with given ID.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#deleting-a-status | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/api.py#L116-L121 | [
"def delete(app, user, url, data=None):\n url = app.base_url + url\n headers = {\"Authorization\": \"Bearer \" + user.access_token}\n\n request = Request('DELETE', url, headers=headers, data=data)\n response = send_request(request)\n\n return process_response(response)\n"
] | # -*- coding: utf-8 -*-
import re
import uuid
from urllib.parse import urlparse, urlencode, quote
from toot import http, CLIENT_NAME, CLIENT_WEBSITE
from toot.exceptions import AuthenticationError
from toot.utils import str_bool
SCOPES = 'read write follow'
def _account_action(app, user, account, action):
url = '/api/v1/accounts/{}/{}'.format(account, action)
return http.post(app, user, url).json()
def _status_action(app, user, status_id, action):
url = '/api/v1/statuses/{}/{}'.format(status_id, action)
return http.post(app, user, url).json()
def create_app(domain, scheme='https'):
url = '{}://{}/api/v1/apps'.format(scheme, domain)
data = {
'client_name': CLIENT_NAME,
'redirect_uris': 'urn:ietf:wg:oauth:2.0:oob',
'scopes': SCOPES,
'website': CLIENT_WEBSITE,
}
return http.anon_post(url, data).json()
def login(app, username, password):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'password',
'client_id': app.client_id,
'client_secret': app.client_secret,
'username': username,
'password': password,
'scope': SCOPES,
}
response = http.anon_post(url, data, allow_redirects=False)
# If auth fails, it redirects to the login page
if response.is_redirect:
raise AuthenticationError()
return http.process_response(response).json()
def get_browser_login_url(app):
"""Returns the URL for manual log in via browser"""
return "{}/oauth/authorize/?{}".format(app.base_url, urlencode({
"response_type": "code",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"scope": SCOPES,
"client_id": app.client_id,
}))
def request_access_token(app, authorization_code):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'authorization_code',
'client_id': app.client_id,
'client_secret': app.client_secret,
'code': authorization_code,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
}
response = http.anon_post(url, data, allow_redirects=False)
return http.process_response(response).json()
def post_status(
app,
user,
status,
visibility='public',
media_ids=None,
sensitive=False,
spoiler_text=None,
in_reply_to_id=None
):
"""
Posts a new status.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status
"""
# Idempotency key assures the same status is not posted multiple times
# if the request is retried.
headers = {"Idempotency-Key": uuid.uuid4().hex}
return http.post(app, user, '/api/v1/statuses', {
'status': status,
'media_ids[]': media_ids,
'visibility': visibility,
'sensitive': str_bool(sensitive),
'spoiler_text': spoiler_text,
'in_reply_to_id': in_reply_to_id,
}, headers=headers).json()
def favourite(app, user, status_id):
return _status_action(app, user, status_id, 'favourite')
def unfavourite(app, user, status_id):
return _status_action(app, user, status_id, 'unfavourite')
def reblog(app, user, status_id):
return _status_action(app, user, status_id, 'reblog')
def unreblog(app, user, status_id):
return _status_action(app, user, status_id, 'unreblog')
def pin(app, user, status_id):
return _status_action(app, user, status_id, 'pin')
def unpin(app, user, status_id):
return _status_action(app, user, status_id, 'unpin')
def context(app, user, status_id):
url = '/api/v1/statuses/{}/context'.format(status_id)
return http.get(app, user, url).json()
def reblogged_by(app, user, status_id):
url = '/api/v1/statuses/{}/reblogged_by'.format(status_id)
return http.get(app, user, url).json()
def _get_next_path(headers):
"""Given timeline response headers, returns the path to the next batch"""
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query])
def _timeline_generator(app, user, path, params=None):
while path:
response = http.get(app, user, path, params)
yield response.json()
path = _get_next_path(response.headers)
def _anon_timeline_generator(instance, path, params=None):
while path:
url = "https://{}{}".format(instance, path)
response = http.anon_get(url, params)
yield response.json()
path = _get_next_path(response.headers)
def home_timeline_generator(app, user, limit=20):
path = '/api/v1/timelines/home?limit={}'.format(limit)
return _timeline_generator(app, user, path)
def public_timeline_generator(instance, local=False, limit=20):
path = '/api/v1/timelines/public'
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def tag_timeline_generator(instance, hashtag, local=False, limit=20):
path = '/api/v1/timelines/tag/{}'.format(hashtag)
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def timeline_list_generator(app, user, list_id, limit=20):
path = '/api/v1/timelines/list/{}'.format(list_id)
return _timeline_generator(app, user, path, {'limit': limit})
def upload_media(app, user, file):
return http.post(app, user, '/api/v1/media', files={
'file': file
}).json()
def search(app, user, query, resolve):
return http.get(app, user, '/api/v1/search', {
'q': query,
'resolve': resolve,
}).json()
def search_accounts(app, user, query):
return http.get(app, user, '/api/v1/accounts/search', {
'q': query,
}).json()
def follow(app, user, account):
return _account_action(app, user, account, 'follow')
def unfollow(app, user, account):
return _account_action(app, user, account, 'unfollow')
def mute(app, user, account):
return _account_action(app, user, account, 'mute')
def unmute(app, user, account):
return _account_action(app, user, account, 'unmute')
def block(app, user, account):
return _account_action(app, user, account, 'block')
def unblock(app, user, account):
return _account_action(app, user, account, 'unblock')
def verify_credentials(app, user):
return http.get(app, user, '/api/v1/accounts/verify_credentials').json()
def single_status(app, user, status_id):
url = '/api/v1/statuses/{}'.format(status_id)
return http.get(app, user, url).json()
def get_notifications(app, user):
return http.get(app, user, '/api/v1/notifications').json()
def clear_notifications(app, user):
http.post(app, user, '/api/v1/notifications/clear')
def get_instance(domain, scheme="https"):
url = "{}://{}/api/v1/instance".format(scheme, domain)
return http.anon_get(url).json()
|
ihabunek/toot | toot/api.py | _get_next_path | python | def _get_next_path(headers):
links = headers.get('Link', '')
matches = re.match('<([^>]+)>; rel="next"', links)
if matches:
parsed = urlparse(matches.group(1))
return "?".join([parsed.path, parsed.query]) | Given timeline response headers, returns the path to the next batch | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/api.py#L160-L166 | null | # -*- coding: utf-8 -*-
import re
import uuid
from urllib.parse import urlparse, urlencode, quote
from toot import http, CLIENT_NAME, CLIENT_WEBSITE
from toot.exceptions import AuthenticationError
from toot.utils import str_bool
SCOPES = 'read write follow'
def _account_action(app, user, account, action):
url = '/api/v1/accounts/{}/{}'.format(account, action)
return http.post(app, user, url).json()
def _status_action(app, user, status_id, action):
url = '/api/v1/statuses/{}/{}'.format(status_id, action)
return http.post(app, user, url).json()
def create_app(domain, scheme='https'):
url = '{}://{}/api/v1/apps'.format(scheme, domain)
data = {
'client_name': CLIENT_NAME,
'redirect_uris': 'urn:ietf:wg:oauth:2.0:oob',
'scopes': SCOPES,
'website': CLIENT_WEBSITE,
}
return http.anon_post(url, data).json()
def login(app, username, password):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'password',
'client_id': app.client_id,
'client_secret': app.client_secret,
'username': username,
'password': password,
'scope': SCOPES,
}
response = http.anon_post(url, data, allow_redirects=False)
# If auth fails, it redirects to the login page
if response.is_redirect:
raise AuthenticationError()
return http.process_response(response).json()
def get_browser_login_url(app):
"""Returns the URL for manual log in via browser"""
return "{}/oauth/authorize/?{}".format(app.base_url, urlencode({
"response_type": "code",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"scope": SCOPES,
"client_id": app.client_id,
}))
def request_access_token(app, authorization_code):
url = app.base_url + '/oauth/token'
data = {
'grant_type': 'authorization_code',
'client_id': app.client_id,
'client_secret': app.client_secret,
'code': authorization_code,
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
}
response = http.anon_post(url, data, allow_redirects=False)
return http.process_response(response).json()
def post_status(
app,
user,
status,
visibility='public',
media_ids=None,
sensitive=False,
spoiler_text=None,
in_reply_to_id=None
):
"""
Posts a new status.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status
"""
# Idempotency key assures the same status is not posted multiple times
# if the request is retried.
headers = {"Idempotency-Key": uuid.uuid4().hex}
return http.post(app, user, '/api/v1/statuses', {
'status': status,
'media_ids[]': media_ids,
'visibility': visibility,
'sensitive': str_bool(sensitive),
'spoiler_text': spoiler_text,
'in_reply_to_id': in_reply_to_id,
}, headers=headers).json()
def delete_status(app, user, status_id):
"""
Deletes a status with given ID.
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#deleting-a-status
"""
return http.delete(app, user, '/api/v1/statuses/{}'.format(status_id))
def favourite(app, user, status_id):
return _status_action(app, user, status_id, 'favourite')
def unfavourite(app, user, status_id):
return _status_action(app, user, status_id, 'unfavourite')
def reblog(app, user, status_id):
return _status_action(app, user, status_id, 'reblog')
def unreblog(app, user, status_id):
return _status_action(app, user, status_id, 'unreblog')
def pin(app, user, status_id):
return _status_action(app, user, status_id, 'pin')
def unpin(app, user, status_id):
return _status_action(app, user, status_id, 'unpin')
def context(app, user, status_id):
url = '/api/v1/statuses/{}/context'.format(status_id)
return http.get(app, user, url).json()
def reblogged_by(app, user, status_id):
url = '/api/v1/statuses/{}/reblogged_by'.format(status_id)
return http.get(app, user, url).json()
def _timeline_generator(app, user, path, params=None):
while path:
response = http.get(app, user, path, params)
yield response.json()
path = _get_next_path(response.headers)
def _anon_timeline_generator(instance, path, params=None):
while path:
url = "https://{}{}".format(instance, path)
response = http.anon_get(url, params)
yield response.json()
path = _get_next_path(response.headers)
def home_timeline_generator(app, user, limit=20):
path = '/api/v1/timelines/home?limit={}'.format(limit)
return _timeline_generator(app, user, path)
def public_timeline_generator(instance, local=False, limit=20):
path = '/api/v1/timelines/public'
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def tag_timeline_generator(instance, hashtag, local=False, limit=20):
path = '/api/v1/timelines/tag/{}'.format(hashtag)
params = {'local': str_bool(local), 'limit': limit}
return _anon_timeline_generator(instance, path, params)
def timeline_list_generator(app, user, list_id, limit=20):
path = '/api/v1/timelines/list/{}'.format(list_id)
return _timeline_generator(app, user, path, {'limit': limit})
def upload_media(app, user, file):
return http.post(app, user, '/api/v1/media', files={
'file': file
}).json()
def search(app, user, query, resolve):
return http.get(app, user, '/api/v1/search', {
'q': query,
'resolve': resolve,
}).json()
def search_accounts(app, user, query):
return http.get(app, user, '/api/v1/accounts/search', {
'q': query,
}).json()
def follow(app, user, account):
return _account_action(app, user, account, 'follow')
def unfollow(app, user, account):
return _account_action(app, user, account, 'unfollow')
def mute(app, user, account):
return _account_action(app, user, account, 'mute')
def unmute(app, user, account):
return _account_action(app, user, account, 'unmute')
def block(app, user, account):
return _account_action(app, user, account, 'block')
def unblock(app, user, account):
return _account_action(app, user, account, 'unblock')
def verify_credentials(app, user):
return http.get(app, user, '/api/v1/accounts/verify_credentials').json()
def single_status(app, user, status_id):
url = '/api/v1/statuses/{}'.format(status_id)
return http.get(app, user, url).json()
def get_notifications(app, user):
return http.get(app, user, '/api/v1/notifications').json()
def clear_notifications(app, user):
http.post(app, user, '/api/v1/notifications/clear')
def get_instance(domain, scheme="https"):
url = "{}://{}/api/v1/instance".format(scheme, domain)
return http.anon_get(url).json()
|
ihabunek/toot | toot/ui/app.py | TimelineApp.reply | python | def reply(self):
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN) | Reply to the selected status | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L624-L647 | [
"def post_status(\n app,\n user,\n status,\n visibility='public',\n media_ids=None,\n sensitive=False,\n spoiler_text=None,\n in_reply_to_id=None\n):\n \"\"\"\n Posts a new status.\n https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status\n ... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def toggle_reblog(self):
"""Reblog or unreblog selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status)
def toggle_favourite(self):
"""Favourite or unfavourite selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status)
def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/app.py | TimelineApp.toggle_reblog | python | def toggle_reblog(self):
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status) | Reblog or unreblog selected status. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L649-L669 | [
"def reblog(app, user, status_id):\n return _status_action(app, user, status_id, 'reblog')\n",
"def unreblog(app, user, status_id):\n return _status_action(app, user, status_id, 'unreblog')\n",
"def get_selected_status(self):\n if len(self.statuses) > self.selected:\n return self.statuses[self.s... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN)
def toggle_favourite(self):
"""Favourite or unfavourite selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status)
def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/app.py | TimelineApp.toggle_favourite | python | def toggle_favourite(self):
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status) | Favourite or unfavourite selected status. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L671-L690 | [
"def favourite(app, user, status_id):\n return _status_action(app, user, status_id, 'favourite')\n",
"def unfavourite(app, user, status_id):\n return _status_action(app, user, status_id, 'unfavourite')\n",
"def get_selected_status(self):\n if len(self.statuses) > self.selected:\n return self.sta... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN)
def toggle_reblog(self):
"""Reblog or unreblog selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status)
def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/app.py | TimelineApp.select_previous | python | def select_previous(self):
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | Move to the previous status in the timeline. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L692-L704 | [
"def redraw_after_selection_change(self, old_index, new_index):\n old_status = self.statuses[old_index]\n new_status = self.statuses[new_index]\n\n # Perform a partial redraw\n self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)\n self.left.draw_status_row(new_status... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN)
def toggle_reblog(self):
"""Reblog or unreblog selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status)
def toggle_favourite(self):
"""Favourite or unfavourite selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status)
def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/app.py | TimelineApp.select_next | python | def select_next(self):
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index) | Move to the next status in the timeline. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L706-L720 | [
"def fetch_next(self):\n try:\n self.footer.draw_message(\"Loading toots...\", Color.BLUE)\n statuses = next(self.status_generator)\n except StopIteration:\n return None\n\n for status in statuses:\n self.statuses.append(parse_status(status))\n\n self.footer.draw_message(\"Lo... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN)
def toggle_reblog(self):
"""Reblog or unreblog selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status)
def toggle_favourite(self):
"""Favourite or unfavourite selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status)
def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def full_redraw(self):
"""Perform a full redraw of the UI."""
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/app.py | TimelineApp.full_redraw | python | def full_redraw(self):
self.left.draw_statuses(self.statuses, self.selected)
self.right.draw(self.get_selected_status())
self.header.draw(self.user)
self.draw_footer_status() | Perform a full redraw of the UI. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/app.py#L740-L746 | [
"def draw_statuses(self, statuses, selected, starting=0):\n # Resize window to accomodate statuses if required\n height, width = self.pad.getmaxyx()\n\n new_height = len(statuses) * 3 + 1\n if new_height > height:\n self.pad.resize(new_height, width)\n self.pad.box()\n\n last_idx = len(... | class TimelineApp:
def __init__(self, app, user, status_generator):
self.app = app
self.user = user
self.status_generator = status_generator
self.statuses = []
self.stdscr = None
def run(self):
os.environ.setdefault('ESCDELAY', '25')
curses.wrapper(self._wrapped_run)
def _wrapped_run(self, stdscr):
self.stdscr = stdscr
Color.setup_palette()
self.setup_windows()
# Load some data and redraw
self.fetch_next()
self.selected = 0
self.full_redraw()
self.loop()
def setup_windows(self):
screen_height, screen_width = self.stdscr.getmaxyx()
if screen_width < 60:
raise ConsoleError("Terminal screen is too narrow, toot curses requires at least 60 columns to display properly.")
header_height = 1
footer_height = 2
footer_top = screen_height - footer_height
left_width = max(min(screen_width // 3, 60), 30)
main_height = screen_height - header_height - footer_height
main_width = screen_width - left_width
self.header = HeaderWindow(self.stdscr, header_height, screen_width, 0, 0)
self.footer = FooterWindow(self.stdscr, footer_height, screen_width, footer_top, 0)
self.left = StatusListWindow(self.stdscr, main_height, left_width, header_height, 0)
self.right = StatusDetailWindow(self.stdscr, main_height, main_width, header_height, left_width)
self.help_modal = HelpModal(self.stdscr, resize_callback=self.on_resize)
def loop(self):
while True:
ch = self.left.pad.getch()
key = chr(ch).lower() if curses.ascii.isprint(ch) else None
if key == 'q':
return
elif key == 'h':
self.help_modal.loop()
self.full_redraw()
elif key == 'v':
status = self.get_selected_status()
if status:
webbrowser.open(status['url'])
elif key == 'j' or ch == curses.KEY_DOWN:
self.select_next()
elif key == 'k' or ch == curses.KEY_UP:
self.select_previous()
elif key == 's':
self.show_sensitive()
elif key == 'b':
self.toggle_reblog()
elif key == 'f':
self.toggle_favourite()
elif key == 'c':
self.compose()
elif key == 'r':
self.reply()
elif ch == curses.KEY_RESIZE:
self.on_resize()
def show_sensitive(self):
status = self.get_selected_status()
if status['sensitive'] and not status['show_sensitive']:
status['show_sensitive'] = True
self.right.draw(status)
def compose(self):
"""Compose and submit a new status"""
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to post", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting status...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None)
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Status posted", Color.GREEN)
def reply(self):
"""Reply to the selected status"""
status = self.get_selected_status()
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reply", Color.RED)
return
compose_modal = ComposeModal(self.stdscr, default_cw='\n'.join(status['spoiler_text']) or None, resize_callback=self.on_resize)
content, cw = compose_modal.loop()
self.full_redraw()
if content is None:
return
elif len(content) == 0:
self.footer.draw_message("Status must contain content", Color.RED)
return
self.footer.draw_message("Submitting reply...", Color.YELLOW)
response = api.post_status(app, user, content, spoiler_text=cw, sensitive=cw is not None, in_reply_to_id=status['id'])
status = parse_status(response)
self.statuses.insert(0, status)
self.selected += 1
self.left.draw_statuses(self.statuses, self.selected)
self.footer.draw_message("✓ Reply posted", Color.GREEN)
def toggle_reblog(self):
"""Reblog or unreblog selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to reblog", Color.RED)
return
status_id = status['id']
if status['reblogged']:
status['reblogged'] = False
self.footer.draw_message("Unboosting status...", Color.YELLOW)
api.unreblog(app, user, status_id)
self.footer.draw_message("✓ Status unboosted", Color.GREEN)
else:
status['reblogged'] = True
self.footer.draw_message("Boosting status...", Color.YELLOW)
api.reblog(app, user, status_id)
self.footer.draw_message("✓ Status boosted", Color.GREEN)
self.right.draw(status)
def toggle_favourite(self):
"""Favourite or unfavourite selected status."""
status = self.get_selected_status()
assert status
app, user = self.app, self.user
if not app or not user:
self.footer.draw_message("You must be logged in to favourite", Color.RED)
return
status_id = status['id']
if status['favourited']:
self.footer.draw_message("Undoing favourite status...", Color.YELLOW)
api.unfavourite(app, user, status_id)
self.footer.draw_message("✓ Status unfavourited", Color.GREEN)
else:
self.footer.draw_message("Favourite status...", Color.YELLOW)
api.favourite(app, user, status_id)
self.footer.draw_message("✓ Status favourited", Color.GREEN)
status['favourited'] = not status['favourited']
self.right.draw(status)
def select_previous(self):
"""Move to the previous status in the timeline."""
self.footer.clear_message()
if self.selected == 0:
self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN)
return
old_index = self.selected
new_index = self.selected - 1
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def select_next(self):
"""Move to the next status in the timeline."""
self.footer.clear_message()
old_index = self.selected
new_index = self.selected + 1
# Load more statuses if no more are available
if self.selected + 1 >= len(self.statuses):
self.fetch_next()
self.left.draw_statuses(self.statuses, self.selected, new_index - 1)
self.draw_footer_status()
self.selected = new_index
self.redraw_after_selection_change(old_index, new_index)
def fetch_next(self):
try:
self.footer.draw_message("Loading toots...", Color.BLUE)
statuses = next(self.status_generator)
except StopIteration:
return None
for status in statuses:
self.statuses.append(parse_status(status))
self.footer.draw_message("Loaded {} toots".format(len(statuses)), Color.GREEN)
return len(statuses)
def on_resize(self):
self.setup_windows()
self.full_redraw()
def redraw_after_selection_change(self, old_index, new_index):
old_status = self.statuses[old_index]
new_status = self.statuses[new_index]
# Perform a partial redraw
self.left.draw_status_row(old_status, old_index, highlight=False, draw_divider=False)
self.left.draw_status_row(new_status, new_index, highlight=True, draw_divider=False)
self.left.scroll_if_required(new_index)
self.right.draw(new_status)
self.draw_footer_status()
def get_selected_status(self):
if len(self.statuses) > self.selected:
return self.statuses[self.selected]
def draw_footer_status(self):
self.footer.draw_status(self.selected, len(self.statuses))
|
ihabunek/toot | toot/ui/utils.py | size_as_drawn | python | def size_as_drawn(lines, screen_width):
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_line)
y += 1
else:
x = 0
y += 1
return y - 1, x - 1 if x != 0 else 0 | Get the bottom-right corner of some text as would be drawn by draw_lines | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/ui/utils.py#L49-L62 | [
"def wc_wrap(text, length):\n \"\"\"\n Wrap text to given length, breaking on whitespace and taking into account\n character width.\n\n Meant for use on a single line or paragraph. Will destroy spacing between\n words and paragraphs and any indentation.\n \"\"\"\n line_words = []\n line_len ... | import re
from toot.wcstring import fit_text, wc_wrap
def draw_horizontal_divider(window, y):
height, width = window.getmaxyx()
# Don't draw out of bounds
if y < height - 1:
line = '├' + '─' * (width - 2) + '┤'
window.addstr(y, 0, line)
def enumerate_lines(lines, text_width, default_color):
def parse_line(line):
if isinstance(line, tuple) and len(line) == 2:
return line[0], line[1]
elif isinstance(line, str):
return line, default_color
elif line is None:
return "", default_color
raise ValueError("Wrong yield in generator")
def wrap_lines(lines):
for line in lines:
line, color = parse_line(line)
if line:
for wrapped in wc_wrap(line, text_width):
yield wrapped, color
else:
yield "", color
return enumerate(wrap_lines(lines))
HASHTAG_PATTERN = re.compile(r'(?<!\w)(#\w+)\b')
def highlight_hashtags(window, y, padding, line):
from toot.ui.app import Color
for match in re.finditer(HASHTAG_PATTERN, line):
start, end = match.span()
window.chgat(y, start + padding, end - start, Color.HASHTAG)
def draw_lines(window, lines, start_y, padding, default_color):
height, width = window.getmaxyx()
text_width = width - 2 * padding
for dy, (line, color) in enumerate_lines(lines, text_width, default_color):
y = start_y + dy
if y < height - 1:
window.addstr(y, padding, fit_text(line, text_width), color)
highlight_hashtags(window, y, padding, line)
return y + 1
|
ihabunek/toot | toot/commands.py | _find_account | python | def _find_account(app, user, account_name):
if not account_name:
raise ConsoleError("Empty account name given")
accounts = api.search_accounts(app, user, account_name)
if account_name[0] == "@":
account_name = account_name[1:]
for account in accounts:
if account['acct'] == account_name:
return account
raise ConsoleError("Account not found") | For a given account name, returns the Account object.
Raises an exception if not found. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/commands.py#L216-L233 | [
"def search_accounts(app, user, query):\n return http.get(app, user, '/api/v1/accounts/search', {\n 'q': query,\n }).json()\n"
] | # -*- coding: utf-8 -*-
from toot import api, config
from toot.auth import login_interactive, login_browser_interactive, create_app_interactive
from toot.exceptions import ConsoleError, NotFoundError
from toot.output import (print_out, print_instance, print_account,
print_search_results, print_timeline, print_notifications)
from toot.utils import assert_domain_exists, multiline_input, EOF_KEY
def get_timeline_generator(app, user, args):
# Make sure tag, list and public are not used simultaneously
if len([arg for arg in [args.tag, args.list, args.public] if arg]) > 1:
raise ConsoleError("Only one of --public, --tag, or --list can be used at one time.")
if args.local and not (args.public or args.tag):
raise ConsoleError("The --local option is only valid alongside --public or --tag.")
if args.instance and not (args.public or args.tag):
raise ConsoleError("The --instance option is only valid alongside --public or --tag.")
if args.public:
instance = args.instance or app.instance
return api.public_timeline_generator(instance, local=args.local, limit=args.count)
elif args.tag:
instance = args.instance or app.instance
return api.tag_timeline_generator(instance, args.tag, local=args.local, limit=args.count)
elif args.list:
return api.timeline_list_generator(app, user, args.list, limit=args.count)
else:
return api.home_timeline_generator(app, user, limit=args.count)
def timeline(app, user, args):
generator = get_timeline_generator(app, user, args)
while(True):
try:
items = next(generator)
except StopIteration:
print_out("That's all folks.")
return
if args.reverse:
items = reversed(items)
print_timeline(items)
if args.once:
break
char = input("\nContinue? [Y/n] ")
if char.lower() == "n":
break
def thread(app, user, args):
toot = api.single_status(app, user, args.status_id)
context = api.context(app, user, args.status_id)
thread = []
for item in context['ancestors']:
thread.append(item)
thread.append(toot)
for item in context['descendants']:
thread.append(item)
print_timeline(thread)
def curses(app, user, args):
generator = get_timeline_generator(app, user, args)
from toot.ui.app import TimelineApp
TimelineApp(app, user, generator).run()
def post(app, user, args):
if args.media:
media = _do_upload(app, user, args.media)
media_ids = [media['id']]
else:
media = None
media_ids = None
if media and not args.text:
args.text = media['text_url']
if not args.text:
print_out("Write or paste your toot. Press <yellow>{}</yellow> to post it.".format(EOF_KEY))
args.text = multiline_input()
if not args.text:
raise ConsoleError("You must specify either text or media to post.")
response = api.post_status(
app, user, args.text,
visibility=args.visibility,
media_ids=media_ids,
sensitive=args.sensitive,
spoiler_text=args.spoiler_text,
in_reply_to_id=args.reply_to,
)
print_out("Toot posted: <green>{}</green>".format(response.get('url')))
def delete(app, user, args):
api.delete_status(app, user, args.status_id)
print_out("<green>✓ Status deleted</green>")
def favourite(app, user, args):
api.favourite(app, user, args.status_id)
print_out("<green>✓ Status favourited</green>")
def unfavourite(app, user, args):
api.unfavourite(app, user, args.status_id)
print_out("<green>✓ Status unfavourited</green>")
def reblog(app, user, args):
api.reblog(app, user, args.status_id)
print_out("<green>✓ Status reblogged</green>")
def unreblog(app, user, args):
api.unreblog(app, user, args.status_id)
print_out("<green>✓ Status unreblogged</green>")
def pin(app, user, args):
api.pin(app, user, args.status_id)
print_out("<green>✓ Status pinned</green>")
def unpin(app, user, args):
api.unpin(app, user, args.status_id)
print_out("<green>✓ Status unpinned</green>")
def reblogged_by(app, user, args):
for account in api.reblogged_by(app, user, args.status_id):
print_out("{}\n @{}".format(account['display_name'], account['acct']))
def auth(app, user, args):
config_data = config.load_config()
if not config_data["users"]:
print_out("You are not logged in to any accounts")
return
active_user = config_data["active_user"]
print_out("Authenticated accounts:")
for uid, u in config_data["users"].items():
active_label = "ACTIVE" if active_user == uid else ""
print_out("* <green>{}</green> <yellow>{}</yellow>".format(uid, active_label))
path = config.get_config_file_path()
print_out("\nAuth tokens are stored in: <blue>{}</blue>".format(path))
def login_cli(app, user, args):
app = create_app_interactive(instance=args.instance, scheme=args.scheme)
login_interactive(app, args.email)
print_out()
print_out("<green>✓ Successfully logged in.</green>")
def login(app, user, args):
app = create_app_interactive(instance=args.instance, scheme=args.scheme)
login_browser_interactive(app)
print_out()
print_out("<green>✓ Successfully logged in.</green>")
def logout(app, user, args):
user = config.load_user(args.account, throw=True)
config.delete_user(user)
print_out("<green>✓ User {} logged out</green>".format(config.user_id(user)))
def activate(app, user, args):
user = config.load_user(args.account, throw=True)
config.activate_user(user)
print_out("<green>✓ User {} active</green>".format(config.user_id(user)))
def upload(app, user, args):
response = _do_upload(app, user, args.file)
msg = "Successfully uploaded media ID <yellow>{}</yellow>, type '<yellow>{}</yellow>'"
print_out()
print_out(msg.format(response['id'], response['type']))
print_out("Original URL: <green>{}</green>".format(response['url']))
print_out("Preview URL: <green>{}</green>".format(response['preview_url']))
print_out("Text URL: <green>{}</green>".format(response['text_url']))
def search(app, user, args):
response = api.search(app, user, args.query, args.resolve)
print_search_results(response)
def _do_upload(app, user, file):
print_out("Uploading media: <green>{}</green>".format(file.name))
return api.upload_media(app, user, file)
def follow(app, user, args):
account = _find_account(app, user, args.account)
api.follow(app, user, account['id'])
print_out("<green>✓ You are now following {}</green>".format(args.account))
def unfollow(app, user, args):
account = _find_account(app, user, args.account)
api.unfollow(app, user, account['id'])
print_out("<green>✓ You are no longer following {}</green>".format(args.account))
def mute(app, user, args):
account = _find_account(app, user, args.account)
api.mute(app, user, account['id'])
print_out("<green>✓ You have muted {}</green>".format(args.account))
def unmute(app, user, args):
account = _find_account(app, user, args.account)
api.unmute(app, user, account['id'])
print_out("<green>✓ {} is no longer muted</green>".format(args.account))
def block(app, user, args):
account = _find_account(app, user, args.account)
api.block(app, user, account['id'])
print_out("<green>✓ You are now blocking {}</green>".format(args.account))
def unblock(app, user, args):
account = _find_account(app, user, args.account)
api.unblock(app, user, account['id'])
print_out("<green>✓ {} is no longer blocked</green>".format(args.account))
def whoami(app, user, args):
account = api.verify_credentials(app, user)
print_account(account)
def whois(app, user, args):
account = _find_account(app, user, args.account)
print_account(account)
def instance(app, user, args):
name = args.instance or (app and app.instance)
if not name:
raise ConsoleError("Please specify instance name.")
assert_domain_exists(name)
try:
instance = api.get_instance(name, args.scheme)
print_instance(instance)
except NotFoundError:
raise ConsoleError(
"Instance not found at {}.\n"
"The given domain probably does not host a Mastodon instance.".format(name)
)
def notifications(app, user, args):
if args.clear:
api.clear_notifications(app, user)
print_out("<green>Cleared notifications</green>")
return
notifications = api.get_notifications(app, user)
if not notifications:
print_out("<yellow>No notification</yellow>")
return
print_notifications(notifications)
|
ihabunek/toot | toot/config_legacy.py | add_username | python | def add_username(user, apps):
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.pop(), user)
return User(user.instance, creds['username'], user.access_token) | When using broser login, username was not stored so look it up | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/config_legacy.py#L42-L55 | [
"def verify_credentials(app, user):\n return http.get(app, user, '/api/v1/accounts/verify_credentials').json()\n"
] | # -*- coding: utf-8 -*-
import os
from . import User, App
# The dir where all toot configuration is stored
CONFIG_DIR = os.environ['HOME'] + '/.config/toot/'
# Subfolder where application access keys for various instances are stored
INSTANCES_DIR = CONFIG_DIR + 'instances/'
# File in which user access token is stored
CONFIG_USER_FILE = CONFIG_DIR + 'user.cfg'
def load_user(path):
if not os.path.exists(path):
return None
with open(path, 'r') as f:
lines = f.read().split()
try:
return User(*lines)
except TypeError:
return None
def load_apps(path):
if not os.path.exists(path):
return []
for name in os.listdir(path):
with open(path + name) as f:
values = f.read().split()
try:
yield App(*values)
except TypeError:
pass
def load_legacy_config():
apps = list(load_apps(INSTANCES_DIR))
user = load_user(CONFIG_USER_FILE)
user = add_username(user, apps)
return apps, user
|
ihabunek/toot | toot/utils.py | get_text | python | def get_text(html):
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text) | Converts html to text, strips all tags. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L19-L29 | null | # -*- coding: utf-8 -*-
import os
import re
import socket
import unicodedata
import warnings
from bs4 import BeautifulSoup
from toot.exceptions import ConsoleError
def str_bool(b):
"""Convert boolean to string, in the way expected by the API."""
return "true" if b else "false"
def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs]
def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False
def domain_exists(name):
try:
socket.gethostbyname(name)
return True
except OSError:
return False
def assert_domain_exists(domain):
if not domain_exists(domain):
raise ConsoleError("Domain {} not found".format(domain))
EOF_KEY = "Ctrl-Z" if os.name == 'nt' else "Ctrl-D"
def multiline_input():
"""Lets user input multiple lines of text, terminated by EOF."""
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip()
|
ihabunek/toot | toot/utils.py | parse_html | python | def parse_html(html):
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs] | Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L32-L42 | null | # -*- coding: utf-8 -*-
import os
import re
import socket
import unicodedata
import warnings
from bs4 import BeautifulSoup
from toot.exceptions import ConsoleError
def str_bool(b):
"""Convert boolean to string, in the way expected by the API."""
return "true" if b else "false"
def get_text(html):
"""Converts html to text, strips all tags."""
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text)
def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False
def domain_exists(name):
try:
socket.gethostbyname(name)
return True
except OSError:
return False
def assert_domain_exists(domain):
if not domain_exists(domain):
raise ConsoleError("Domain {} not found".format(domain))
EOF_KEY = "Ctrl-Z" if os.name == 'nt' else "Ctrl-D"
def multiline_input():
"""Lets user input multiple lines of text, terminated by EOF."""
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip()
|
ihabunek/toot | toot/utils.py | format_content | python | def format_content(content):
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False | Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L45-L62 | [
"def parse_html(html):\n \"\"\"Attempt to convert html to plain text while keeping line breaks.\n Returns a list of paragraphs, each being a list of lines.\n \"\"\"\n paragraphs = re.split(\"</?p[^>]*>\", html)\n\n # Convert <br>s to line breaks and remove empty paragraphs\n paragraphs = [re.split... | # -*- coding: utf-8 -*-
import os
import re
import socket
import unicodedata
import warnings
from bs4 import BeautifulSoup
from toot.exceptions import ConsoleError
def str_bool(b):
"""Convert boolean to string, in the way expected by the API."""
return "true" if b else "false"
def get_text(html):
"""Converts html to text, strips all tags."""
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text)
def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs]
def domain_exists(name):
try:
socket.gethostbyname(name)
return True
except OSError:
return False
def assert_domain_exists(domain):
if not domain_exists(domain):
raise ConsoleError("Domain {} not found".format(domain))
EOF_KEY = "Ctrl-Z" if os.name == 'nt' else "Ctrl-D"
def multiline_input():
"""Lets user input multiple lines of text, terminated by EOF."""
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip()
|
ihabunek/toot | toot/utils.py | multiline_input | python | def multiline_input():
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return "\n".join(lines).strip() | Lets user input multiple lines of text, terminated by EOF. | train | https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/utils.py#L81-L90 | null | # -*- coding: utf-8 -*-
import os
import re
import socket
import unicodedata
import warnings
from bs4 import BeautifulSoup
from toot.exceptions import ConsoleError
def str_bool(b):
"""Convert boolean to string, in the way expected by the API."""
return "true" if b else "false"
def get_text(html):
"""Converts html to text, strips all tags."""
# Ignore warnings made by BeautifulSoup, if passed something that looks like
# a file (e.g. a dot which matches current dict), it will warn that the file
# should be opened instead of passing a filename.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
text = BeautifulSoup(html.replace(''', "'"), "html.parser").get_text()
return unicodedata.normalize('NFKC', text)
def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for p in paragraphs if p]
# Convert each line in each paragraph to plain text:
return [[get_text(l) for l in p] for p in paragraphs]
def format_content(content):
"""Given a Status contents in HTML, converts it into lines of plain text.
Returns a generator yielding lines of content.
"""
paragraphs = parse_html(content)
first = True
for paragraph in paragraphs:
if not first:
yield ""
for line in paragraph:
yield line
first = False
def domain_exists(name):
try:
socket.gethostbyname(name)
return True
except OSError:
return False
def assert_domain_exists(domain):
if not domain_exists(domain):
raise ConsoleError("Domain {} not found".format(domain))
EOF_KEY = "Ctrl-Z" if os.name == 'nt' else "Ctrl-D"
|
yuce/pyswip | pyswip/easy.py | getAtomChars | python | def getAtomChars(t):
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom") | If t is an atom, return it as a string, otherwise raise InvalidTypeError. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L333-L340 | [
"def check_and_call(*args):\n args = list(args)\n for i in strings:\n arg = args[i]\n args[i] = str_to_bytes(arg)\n for i in arrays:\n arg = args[i]\n args[i] = list_to_bytes_list(arg)\n\n return func(*args)\n"
] | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | getBool | python | def getBool(t):
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool") | If t is of type bool, return it, otherwise raise InvalidTypeError. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L349-L356 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | getLong | python | def getLong(t):
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long") | If t is of type long, return it, otherwise raise InvalidTypeError. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L359-L366 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | getFloat | python | def getFloat(t):
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float") | If t is of type float, return it, otherwise raise InvalidTypeError. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L372-L379 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | getString | python | def getString(t):
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string") | If t is of type string, return it, otherwise raise InvalidTypeError. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L382-L390 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | getList | python | def getList(x):
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result | Return t as a list. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L411-L423 | [
"def getTerm(t):\n global mappedTerms\n #print 'mappedTerms', mappedTerms\n\n #if t in mappedTerms:\n # return mappedTerms[t]\n p = PL_term_type(t)\n if p < PL_TERM:\n res = _getterm_router[p](t)\n elif PL_is_list(t):\n res = getList(t)\n else:\n res = getFunctor(t)\n... | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | registerForeign | python | def registerForeign(func, name=None, arity=None, flags=0):
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags) | Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L475-L496 | [
"def _callbackWrapper(arity=1):\n global arities\n\n res = arities.get(arity)\n if res is None:\n res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))\n arities[arity] = res\n return res\n",
"def _foreignWrapper(fun):\n global funwraps\n\n res = funwraps.get(fun)\n if res is None:\n... | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | call | python | def call(*terms, **kwargs):
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module) | Call term in module.
``term``: a Term or term handle | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L509-L523 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def newModule(name):
"""Create a new module.
``name``: An Atom or a string
"""
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | newModule | python | def newModule(name):
if isinstance(name, str):
name = Atom(name)
return PL_new_module(name.handle) | Create a new module.
``name``: An Atom or a string | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L526-L533 | null | # -*- coding: utf-8 -*-
# pyswip.easy -- PySwip helper functions
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from pyswip.core import *
class InvalidTypeError(TypeError):
def __init__(self, *args):
type_ = args and args[0] or "Unknown"
msg = "Term is expected to be of type: '%s'" % type_
Exception.__init__(self, msg, *args)
class ArgumentTypeError(Exception):
"""
Thrown when an argument has the wrong type.
"""
def __init__(self, expected, got):
msg = "Expected an argument of type '%s' but got '%s'" % (expected, got)
Exception.__init__(self, msg)
class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
class Term(object):
__slots__ = "handle", "chars", "__value", "a0"
def __init__(self, handle=None, a0=None):
if handle:
#self.handle = PL_copy_term_ref(handle)
self.handle = handle
else:
self.handle = PL_new_term_ref()
self.chars = None
self.a0 = a0
def __invert__(self):
return _not(self)
def get_value(self):
pass
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Variable(object):
__slots__ = "handle", "chars"
def __init__(self, handle=None, name=None):
self.chars = None
if name:
self.chars = name
if handle:
self.handle = handle
s = create_string_buffer(b"\00"*64) # FIXME:
ptr = cast(s, c_char_p)
if PL_get_chars(handle, byref(ptr), CVT_VARIABLE|BUF_RING):
self.chars = ptr.value
else:
self.handle = PL_new_term_ref()
#PL_put_variable(self.handle)
if (self.chars is not None) and not isinstance(self.chars, str):
self.chars = self.chars.decode()
def unify(self, value):
if type(value) == str:
fun = PL_unify_atom_chars
elif type(value) == int:
fun = PL_unify_integer
elif type(value) == bool:
fun = PL_unify_bool
elif type(value) == float:
fun = PL_unify_float
elif type(value) == list:
fun = PL_unify_list
else:
raise
if self.handle is None:
t = PL_new_term_ref(self.handle)
else:
t = PL_copy_term_ref(self.handle)
fun(t, value)
self.handle = t
def get_value(self):
return getTerm(self.handle)
value = property(get_value, unify)
def unified(self):
return PL_term_type(self.handle) == PL_VARIABLE
def __str__(self):
if self.chars is not None:
return self.chars
else:
return self.__repr__()
def __repr__(self):
return "Variable(%s)" % self.handle
def put(self, term):
#PL_put_variable(term)
PL_put_term(term, self.handle)
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
def _unifier(arity, *args):
assert arity == 2
#if PL_is_variable(args[0]):
# args[0].unify(args[1])
try:
return {args[0].value:args[1].value}
except AttributeError:
return {args[0].value:args[1]}
_unify = Functor("=", 2)
Functor.func[_unify.handle] = _unifier
_not = Functor("not", 1)
_comma = Functor(",", 2)
def putTerm(term, value):
if isinstance(value, Term):
PL_put_term(term, value.handle)
elif isinstance(value, str):
PL_put_atom_chars(term, value)
elif isinstance(value, int):
PL_put_integer(term, value)
elif isinstance(value, Variable):
value.put(term)
elif isinstance(value, list):
putList(term, value)
elif isinstance(value, Atom):
print("ATOM")
elif isinstance(value, Functor):
PL_put_functor(term, value.handle)
else:
raise Exception("Not implemented")
def putList(l, ls):
PL_put_nil(l)
for item in reversed(ls):
a = PL_new_term_ref() #PL_new_term_refs(len(ls))
putTerm(a, item)
PL_cons_list(l, a, l)
# deprecated
def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
def getAtom(t):
"""If t is an atom, return it , otherwise raise InvalidTypeError.
"""
return Atom.fromTerm(t)
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
else:
raise InvalidTypeError("long")
getInteger = getLong # just an alias for getLong
def getFloat(t):
"""If t is of type float, return it, otherwise raise InvalidTypeError.
"""
d = c_double()
if PL_get_float(t, byref(d)):
return d.value
else:
raise InvalidTypeError("float")
def getString(t):
"""If t is of type string, return it, otherwise raise InvalidTypeError.
"""
slen = c_int()
s = c_char_p()
if PL_get_string_chars(t, byref(s), byref(slen)):
return s.value
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
res = _getterm_router[p](t)
elif PL_is_list(t):
res = getList(t)
else:
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""
Return t as a list.
"""
t = PL_copy_term_ref(x)
head = PL_new_term_ref()
result = []
while PL_get_list(t, head, t):
result.append(getTerm(head))
head = PL_new_term_ref()
return result
def getFunctor(t):
"""Return t as a functor
"""
return Functor.fromTerm(t)
def getVariable(t):
return Variable(t)
_getterm_router = {
PL_VARIABLE: getVariable,
PL_ATOM: getAtom,
PL_STRING: getString,
PL_INTEGER: getInteger,
PL_FLOAT: getFloat,
PL_TERM: getTerm,
}
arities = {}
def _callbackWrapper(arity=1):
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
``func``: Function to be registered. The function should return a value in
``foreign_t``, ``True`` or ``False``.
``name`` : Name of the function. If this value is not used, ``func.func_name``
should exist.
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.__name__
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, fwrap2, flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
def newTermRefs(count):
a = PL_new_term_refs(count)
return list(range(a, a + count))
def call(*terms, **kwargs):
"""Call term in module.
``term``: a Term or term handle
"""
for kwarg in kwargs:
if kwarg not in ["module"]:
raise KeyError
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
return PL_call(t.handle, module)
class Query(object):
qid = None
fid = None
def __init__(self, *terms, **kwargs):
for key in kwargs:
if key not in ["flags", "module"]:
raise Exception("Invalid kwarg: %s" % key, key)
flags = kwargs.get("flags", PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION)
module = kwargs.get("module", None)
t = terms[0]
for tx in terms[1:]:
t = _comma(t, tx)
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
# self.closeQuery()
def nextSolution():
return PL_next_solution(Query.qid)
nextSolution = staticmethod(nextSolution)
def cutQuery():
PL_cut_query(Query.qid)
cutQuery = staticmethod(cutQuery)
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
Query.qid = None
closeQuery = staticmethod(closeQuery)
|
yuce/pyswip | pyswip/easy.py | Atom.fromTerm | python | def fromTerm(cls, term):
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(c_void_p)), str(type(term)))
a = atom_t()
if PL_get_atom(term, byref(a)):
return cls(a.value) | Create an atom from a Term or term handle. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L62-L72 | null | class Atom(object):
__slots__ = "handle", "chars"
def __init__(self, handleOrChars):
"""Create an atom.
``handleOrChars``: handle or string of the atom.
"""
if isinstance(handleOrChars, str):
self.handle = PL_new_atom(handleOrChars)
self.chars = handleOrChars
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
fromTerm = classmethod(fromTerm)
def __del__(self):
if not cleaned:
PL_unregister_atom(self.handle)
def get_value(self):
ret = self.chars
if not isinstance(ret, str):
ret = ret.decode()
return ret
value = property(get_value)
def __str__(self):
if self.chars is not None:
return self.value
else:
return self.__repr__()
def __repr__(self):
return str(self.handle).join(["Atom('", "')"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return self.handle == other.handle
def __hash__(self):
return self.handle
|
yuce/pyswip | pyswip/easy.py | Functor.fromTerm | python | def fromTerm(cls, term):
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
# get args
args = []
arity = PL_functor_arity(f.value)
# let's have all args be consecutive
a0 = PL_new_term_refs(arity)
for i, a in enumerate(range(1, arity + 1)):
if PL_get_arg(a, term, a0 + i):
args.append(getTerm(a0 + i))
return cls(f.value, args=args, a0=a0) | Create a functor from a Term or term handle. | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/easy.py#L235-L254 | [
"def getTerm(t):\n global mappedTerms\n #print 'mappedTerms', mappedTerms\n\n #if t in mappedTerms:\n # return mappedTerms[t]\n p = PL_term_type(t)\n if p < PL_TERM:\n res = _getterm_router[p](t)\n elif PL_is_list(t):\n res = getList(t)\n else:\n res = getFunctor(t)\n... | class Functor(object):
__slots__ = "handle", "name", "arity", "args", "__value", "a0"
func = {}
def __init__(self, handleOrName, arity=1, args=None, a0=None):
"""Create a functor.
``handleOrName``: functor handle, a string or an atom.
"""
self.args = args or []
self.arity = arity
self.a0 = a0
if isinstance(handleOrName, str):
self.name = Atom(handleOrName)
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
elif isinstance(handleOrName, Atom):
self.name = handleOrName
self.handle = PL_new_functor(self.name.handle, arity)
self.__value = "Functor%d" % self.handle
else:
self.handle = handleOrName
self.name = Atom(PL_functor_name(self.handle))
self.arity = PL_functor_arity(self.handle)
try:
self.__value = self.func[self.handle](self.arity, *self.args)
except KeyError:
self.__value = str(self)
fromTerm = classmethod(fromTerm)
value = property(lambda s: s.__value)
def __call__(self, *args):
assert self.arity == len(args) # FIXME: Put a decent error message
a = PL_new_term_refs(len(args))
for i, arg in enumerate(args):
putTerm(a + i, arg)
t = PL_new_term_ref()
PL_cons_functor_v(t, self.handle, a)
return Term(t)
def __str__(self):
if self.name is not None and self.arity is not None:
return "%s(%s)" % (self.name,
', '.join([str(arg) for arg in self.args]))
else:
return self.__repr__()
def __repr__(self):
return "".join(["Functor(", ",".join(str(x) for x
in [self.handle,self.arity]+self.args), ")"])
def __eq__(self, other):
if type(self) != type(other):
return False
else:
return PL_compare(self.handle, other.handle) == 0
def __hash__(self):
return self.handle
|
yuce/pyswip | pyswip/core.py | _findSwiplFromExec | python | def _findSwiplFromExec():
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome) | This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None}) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L64-L156 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _findSwiplWin | python | def _findSwiplWin():
import re
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None) | This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None}) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L159-L232 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _findSwiplLin | python | def _findSwiplLin():
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None) | This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None}) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L234-L271 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | walk | python | def walk(path, name):
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None | This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L274-L303 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _findSwiplMacOSHome | python | def _findSwiplMacOSHome():
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None) | This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None}) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L317-L355 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _findSwiplDar | python | def _findSwiplDar():
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None) | This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None}) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L358-L390 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _findSwipl | python | def _findSwipl():
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome) | This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L393-L432 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | _fixWindowsPath | python | def _fixWindowsPath(dll):
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath) | When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L435-L454 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | str_to_bytes | python | def str_to_bytes(string):
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string | Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None) | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L457-L476 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | list_to_bytes_list | python | def list_to_bytes_list(strList):
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList | This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L478-L502 | [
"def str_to_bytes(string):\n \"\"\"\n Turns a string into a bytes if necessary (i.e. if it is not already a bytes\n object or None).\n If string is None, int or c_char_p it will be returned directly.\n\n :param string: The string that shall be transformed\n :type string: str, bytes or type(None)\n... | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
def check_strings(strings, arrays):
"""
Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers
"""
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/core.py | check_strings | python | def check_strings(strings, arrays):
# if given a single element, turn it into a list
if isinstance(strings, int):
strings = [strings]
elif strings is None:
strings = []
# check if all entries are integers
for i,k in enumerate(strings):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in strings. Must be int, not {1}!').format(i,k))
# if given a single element, turn it into a list
if isinstance(arrays, int):
arrays = [arrays]
elif arrays is None:
arrays = []
# check if all entries are integers
for i,k in enumerate(arrays):
if not isinstance(k, int):
raise TypeError(('Wrong type for index at {0} '+
'in arrays. Must be int, not {1}!').format(i,k))
# check if some index occurs in both
if set(strings).intersection(arrays):
raise ValueError('One or more elements occur in both arrays and ' +
' strings. One parameter cannot be both list and string!')
# create the checker that will check all arguments given by argsToCheck
# and turn them into the right datatype.
def checker(func):
def check_and_call(*args):
args = list(args)
for i in strings:
arg = args[i]
args[i] = str_to_bytes(arg)
for i in arrays:
arg = args[i]
args[i] = list_to_bytes_list(arg)
return func(*args)
return check_and_call
return checker | Decorator function which can be used to automatically turn an incoming
string into a bytes object and an incoming list to a pointer array if
necessary.
:param strings: Indices of the arguments must be pointers to bytes
:type strings: List of integers
:param arrays: Indices of the arguments must be arrays of pointers to bytes
:type arrays: List of integers | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/core.py#L506-L563 | null | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 Yüce Tekol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
import os
import sys
import glob
import warnings
import atexit
from subprocess import Popen, PIPE
from ctypes import *
from ctypes.util import find_library
# To initialize the SWI-Prolog environment, two things need to be done: the
# first is to find where the SO/DLL is located and the second is to find the
# SWI-Prolog home, to get the saved state.
#
# The goal of the (entangled) process below is to make the library installation
# independent.
def _findSwiplPathFromFindLib():
"""
This function resorts to ctype's find_library to find the path to the
DLL. The biggest problem is that find_library does not give the path to the
resource file.
:returns:
A path to the swipl SO/DLL or None if it is not found.
:returns type:
{str, None}
"""
path = (find_library('swipl') or
find_library('pl') or
find_library('libswipl')) # This last one is for Windows
return path
def _findSwiplFromExec():
"""
This function tries to use an executable on the path to find SWI-Prolog
SO/DLL and the resource file.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
platform = sys.platform[:3]
fullName = None
swiHome = None
try: # try to get library path from swipl executable.
# We may have pl or swipl as the executable
try:
cmd = Popen(['swipl', '--dump-runtime-variables'], stdout=PIPE)
except OSError:
cmd = Popen(['pl', '--dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].decode().replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret) # [1:-1] gets
# rid of the
# quotes
if rtvars['PLSHARED'] == 'no':
raise ImportError('SWI-Prolog is not installed as a shared '
'library.')
else: # PLSHARED == 'yes'
swiHome = rtvars['PLBASE'] # The environment is in PLBASE
if not os.path.exists(swiHome):
swiHome = None
# determine platform specific path
if platform == "win":
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'bin')
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "cyg":
# e.g. /usr/lib/pl-5.6.36/bin/i686-cygwin/cygpl.dll
dllName = 'cygpl.dll'
path = os.path.join(rtvars['PLBASE'], 'bin', rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if not os.path.exists(fullName):
fullName = None
elif platform == "dar":
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
fullName = None
else: # assume UNIX-like
# The SO name in some linuxes is of the form libswipl.so.5.10.2,
# so we have to use glob to find the correct one
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'], 'lib', rtvars['PLARCH'])
baseName = os.path.join(path, dllName)
if os.path.exists(baseName):
fullName = baseName
else: # We will search for versions
pattern = baseName + '.*'
files = glob.glob(pattern)
if len(files) == 0:
fullName = None
elif len(files) == 1:
fullName = files[0]
else: # Will this ever happen?
fullName = None
except (OSError, KeyError): # KeyError from accessing rtvars
pass
return (fullName, swiHome)
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:returns:
A tuple of (path to the swipl DLL, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
dllNames = ('swipl.dll', 'libswipl.dll')
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
paths = [os.path.join(programFiles, r'pl\bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
# Second try: use the find_library
path = _findSwiplPathFromFindLib()
if path is not None and os.path.exists(path):
return (path, None)
# Third try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
except OSError:
# reg.exe not found? Weird...
pass
# May the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# Last try: maybe it is in the current dir
for dllName in dllNames:
if os.path.exists(dllName):
return (dllName, None)
return (None, None)
def _findSwiplLin():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in Linuxes.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Maybe the exec is on path?
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Our last try: some hardcoded paths.
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
names = ['libswipl.so', 'libpl.so']
path = None
for name in names:
for try_ in paths:
try_ = os.path.join(try_, name)
if os.path.exists(try_):
path = try_
break
if path is not None:
return (path, swiHome)
return (None, None)
def walk(path, name):
"""
This function is a 2-time recursive func,
that findin file in dirs
:parameters:
- `path` (str) - Directory path
- `name` (str) - Name of file, that we lookin for
:returns:
Path to the swipl so, path to the resource file
:returns type:
(str)
"""
back_path = path[:]
path = os.path.join(path, name)
if os.path.exists(path):
return path
else:
for dir_ in os.listdir(back_path):
path = os.path.join(back_path, dir_)
if os.path.isdir(path):
res_path = walk(path, name)
if res_path is not None:
return (res_path, back_path)
return None
def get_swi_ver():
import re
swi_ver = input(
'Please enter you SWI-Prolog version in format "X.Y.Z": ')
match = re.search(r'[0-9]\.[0-9]\.[0-9]')
if match is None:
raise InputError('Error, type normal version')
return swi_ver
def _findSwiplMacOSHome():
"""
This function is guesing where SWI-Prolog is
installed in MacOS via .app.
:parameters:
- `swi_ver` (str) - Version of SWI-Prolog in '[0-9].[0-9].[0-9]' format
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# Need more help with MacOS
# That way works, but need more work
names = ['libswipl.dylib', 'libpl.dylib']
path = os.environ.get('SWI_HOME_DIR')
if path is None:
path = os.environ.get('SWI_LIB_DIR')
if path is None:
path = os.environ.get('PLBASE')
if path is None:
swi_ver = get_swi_ver()
path = '/Applications/SWI-Prolog.app/Contents/swipl-' + swi_ver + '/lib/'
paths = [path]
for name in names:
for path in paths:
(path_res, back_path) = walk(path, name)
if path_res is not None:
os.environ['SWI_LIB_DIR'] = back_path
return (path_res, None)
return (None, None)
def _findSwiplDar():
"""
This function uses several heuristics to guess where SWI-Prolog is
installed in MacOS.
:returns:
A tuple of (path to the swipl so, path to the resource file)
:returns type:
({str, None}, {str, None})
"""
# If the exec is in path
(path, swiHome) = _findSwiplFromExec()
if path is not None:
return (path, swiHome)
# If it is not, use find_library
path = _findSwiplPathFromFindLib()
if path is not None:
return (path, swiHome)
# Last guess, searching for the file
paths = ['.', './lib', '/usr/lib/', '/usr/local/lib', '/opt/local/lib']
names = ['libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return (path, None)
return (None, None)
def _findSwipl():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Tuple. Fist element is the name or path to the library that can be
used by CDLL. Second element is the path were SWI-Prolog resource
file may be found (this is needed in some Linuxes)
:rtype: Tuple of strings
:raises ImportError: If we cannot guess the name of the library
"""
# Now begins the guesswork
platform = sys.platform[:3]
if platform == "win": # In Windows, we have the default installer
# path and the registry to look
(path, swiHome) = _findSwiplWin()
elif platform in ("lin", "cyg"):
(path, swiHome) = _findSwiplLin()
elif platform == "dar": # Help with MacOS is welcome!!
(path, swiHome) = _findSwiplDar()
if path is None:
(path, swiHome) = _findSwiplMacOSHome()
else:
# This should work for other UNIX
(path, swiHome) = _findSwiplLin()
# This is a catch all raise
if path is None:
raise ImportError('Could not find the SWI-Prolog library in this '
'platform. If you are sure it is installed, please '
'open an issue.')
else:
return (path, swiHome)
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:parameters:
- `dll` (str) - File name of the DLL
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
_stringMap = {}
def str_to_bytes(string):
"""
Turns a string into a bytes if necessary (i.e. if it is not already a bytes
object or None).
If string is None, int or c_char_p it will be returned directly.
:param string: The string that shall be transformed
:type string: str, bytes or type(None)
:return: Transformed string
:rtype: c_char_p compatible object (bytes, c_char_p, int or None)
"""
if string is None or isinstance(string, (int, c_char_p)):
return string
if not isinstance(string, bytes):
if string not in _stringMap:
_stringMap[string] = string.encode()
string = _stringMap[string]
return string
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:returns: Pointer array with pointers pointing to bytes
:raises: TypeError if strList is not list, set or tuple
"""
pList = c_char_p * len(strList)
# if strList is already a pointerarray or None, there is nothing to do
if isinstance(strList, (pList, type(None))):
return strList
if not isinstance(strList, (list, set, tuple)):
raise TypeError("strList must be list, set or tuple, not " +
str(type(strList)))
pList = pList()
for i, elem in enumerate(strList):
pList[i] = str_to_bytes(elem)
return pList
# create a decorator that turns the incoming strings into c_char_p compatible
# butes or pointer arrays
# Find the path and resource file. SWI_HOME_DIR shall be treated as a constant
# by users of this module
(_path, SWI_HOME_DIR) = _findSwipl()
_fixWindowsPath(_path)
# Load the library
_lib = CDLL(_path, mode=RTLD_GLOBAL)
# PySwip constants
PYSWIP_MAXSTR = 1024
c_int_p = c_void_p
c_long_p = c_void_p
c_double_p = c_void_p
c_uint_p = c_void_p
# constants (from SWI-Prolog.h)
# PL_unify_term() arguments
PL_VARIABLE = 1 # nothing
PL_ATOM = 2 # const char
PL_INTEGER = 3 # int
PL_FLOAT = 4 # double
PL_STRING = 5 # const char *
PL_TERM = 6 #
# PL_unify_term()
PL_FUNCTOR = 10 # functor_t, arg ...
PL_LIST = 11 # length, arg ...
PL_CHARS = 12 # const char *
PL_POINTER = 13 # void *
# /* PlArg::PlArg(text, type) */
#define PL_CODE_LIST (14) /* [ascii...] */
#define PL_CHAR_LIST (15) /* [h,e,l,l,o] */
#define PL_BOOL (16) /* PL_set_feature() */
#define PL_FUNCTOR_CHARS (17) /* PL_unify_term() */
#define _PL_PREDICATE_INDICATOR (18) /* predicate_t (Procedure) */
#define PL_SHORT (19) /* short */
#define PL_INT (20) /* int */
#define PL_LONG (21) /* long */
#define PL_DOUBLE (22) /* double */
#define PL_NCHARS (23) /* unsigned, const char * */
#define PL_UTF8_CHARS (24) /* const char * */
#define PL_UTF8_STRING (25) /* const char * */
#define PL_INT64 (26) /* int64_t */
#define PL_NUTF8_CHARS (27) /* unsigned, const char * */
#define PL_NUTF8_CODES (29) /* unsigned, const char * */
#define PL_NUTF8_STRING (30) /* unsigned, const char * */
#define PL_NWCHARS (31) /* unsigned, const wchar_t * */
#define PL_NWCODES (32) /* unsigned, const wchar_t * */
#define PL_NWSTRING (33) /* unsigned, const wchar_t * */
#define PL_MBCHARS (34) /* const char * */
#define PL_MBCODES (35) /* const char * */
#define PL_MBSTRING (36) /* const char * */
# /********************************
# * NON-DETERMINISTIC CALL/RETURN *
# *********************************/
#
# Note 1: Non-deterministic foreign functions may also use the deterministic
# return methods PL_succeed and PL_fail.
#
# Note 2: The argument to PL_retry is a 30 bits signed integer (long).
PL_FIRST_CALL = 0
PL_CUTTED = 1
PL_REDO = 2
PL_FA_NOTRACE = 0x01 # foreign cannot be traced
PL_FA_TRANSPARENT = 0x02 # foreign is module transparent
PL_FA_NONDETERMINISTIC = 0x04 # foreign is non-deterministic
PL_FA_VARARGS = 0x08 # call using t0, ac, ctx
PL_FA_CREF = 0x10 # Internal: has clause-reference */
# /*******************************
# * CALL-BACK *
# *******************************/
PL_Q_DEBUG = 0x01 # = TRUE for backward compatibility
PL_Q_NORMAL = 0x02 # normal usage
PL_Q_NODEBUG = 0x04 # use this one
PL_Q_CATCH_EXCEPTION = 0x08 # handle exceptions in C
PL_Q_PASS_EXCEPTION = 0x10 # pass to parent environment
PL_Q_DETERMINISTIC = 0x20 # call was deterministic
# /*******************************
# * BLOBS *
# *******************************/
#define PL_BLOB_MAGIC_B 0x75293a00 /* Magic to validate a blob-type */
#define PL_BLOB_VERSION 1 /* Current version */
#define PL_BLOB_MAGIC (PL_BLOB_MAGIC_B|PL_BLOB_VERSION)
#define PL_BLOB_UNIQUE 0x01 /* Blob content is unique */
#define PL_BLOB_TEXT 0x02 /* blob contains text */
#define PL_BLOB_NOCOPY 0x04 /* do not copy the data */
#define PL_BLOB_WCHAR 0x08 /* wide character string */
# /*******************************
# * CHAR BUFFERS *
# *******************************/
CVT_ATOM = 0x0001
CVT_STRING = 0x0002
CVT_LIST = 0x0004
CVT_INTEGER = 0x0008
CVT_FLOAT = 0x0010
CVT_VARIABLE = 0x0020
CVT_NUMBER = CVT_INTEGER | CVT_FLOAT
CVT_ATOMIC = CVT_NUMBER | CVT_ATOM | CVT_STRING
CVT_WRITE = 0x0040 # as of version 3.2.10
CVT_ALL = CVT_ATOMIC | CVT_LIST
CVT_MASK = 0x00ff
BUF_DISCARDABLE = 0x0000
BUF_RING = 0x0100
BUF_MALLOC = 0x0200
CVT_EXCEPTION = 0x10000 # throw exception on error
argv = list_to_bytes_list(sys.argv + [None])
argc = len(sys.argv)
# /*******************************
# * TYPES *
# *******************************/
#
# typedef uintptr_t atom_t; /* Prolog atom */
# typedef uintptr_t functor_t; /* Name/arity pair */
# typedef void * module_t; /* Prolog module */
# typedef void * predicate_t; /* Prolog procedure */
# typedef void * record_t; /* Prolog recorded term */
# typedef uintptr_t term_t; /* opaque term handle */
# typedef uintptr_t qid_t; /* opaque query handle */
# typedef uintptr_t PL_fid_t; /* opaque foreign context handle */
# typedef void * control_t; /* non-deterministic control arg */
# typedef void * PL_engine_t; /* opaque engine handle */
# typedef uintptr_t PL_atomic_t; /* same a word */
# typedef uintptr_t foreign_t; /* return type of foreign functions */
# typedef wchar_t pl_wchar_t; /* Prolog wide character */
# typedef foreign_t (*pl_function_t)(); /* foreign language functions */
atom_t = c_uint_p
functor_t = c_uint_p
module_t = c_void_p
predicate_t = c_void_p
record_t = c_void_p
term_t = c_uint_p
qid_t = c_uint_p
PL_fid_t = c_uint_p
fid_t = c_uint_p
control_t = c_void_p
PL_engine_t = c_void_p
PL_atomic_t = c_uint_p
foreign_t = c_uint_p
pl_wchar_t = c_wchar
PL_initialise = _lib.PL_initialise
PL_initialise = check_strings(None, 1)(PL_initialise)
#PL_initialise.argtypes = [c_int, c_c??
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
PL_new_term_ref = _lib.PL_new_term_ref
PL_new_term_ref.restype = term_t
PL_new_term_refs = _lib.PL_new_term_refs
PL_new_term_refs.argtypes = [c_int]
PL_new_term_refs.restype = term_t
PL_chars_to_term = _lib.PL_chars_to_term
PL_chars_to_term.argtypes = [c_char_p, term_t]
PL_chars_to_term.restype = c_int
PL_chars_to_term = check_strings(0, None)(PL_chars_to_term)
PL_call = _lib.PL_call
PL_call.argtypes = [term_t, module_t]
PL_call.restype = c_int
PL_call_predicate = _lib.PL_call_predicate
PL_call_predicate.argtypes = [module_t, c_int, predicate_t, term_t]
PL_call_predicate.restype = c_int
PL_discard_foreign_frame = _lib.PL_discard_foreign_frame
PL_discard_foreign_frame.argtypes = [fid_t]
PL_discard_foreign_frame.restype = None
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
PL_put_list_chars.restype = c_int
PL_put_list_chars = check_strings(1, None)(PL_put_list_chars)
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
PL_register_atom.restype = None
#PL_EXPORT(void) PL_unregister_atom(atom_t a);
PL_unregister_atom = _lib.PL_unregister_atom
PL_unregister_atom.argtypes = [atom_t]
PL_unregister_atom.restype = None
#PL_EXPORT(atom_t) PL_functor_name(functor_t f);
PL_functor_name = _lib.PL_functor_name
PL_functor_name.argtypes = [functor_t]
PL_functor_name.restype = atom_t
#PL_EXPORT(int) PL_functor_arity(functor_t f);
PL_functor_arity = _lib.PL_functor_arity
PL_functor_arity.argtypes = [functor_t]
PL_functor_arity.restype = c_int
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom.restype = c_int
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
PL_get_bool.restype = c_int
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_chars.restype = c_int
PL_get_atom_chars = check_strings(None, 1)(PL_get_atom_chars)
PL_get_string_chars = _lib.PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = check_strings(None, 1)(PL_get_chars)
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_atom_nchars(term_t t, size_t *len, char **a);
#PL_EXPORT(int) PL_get_list_nchars(term_t l,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_nchars(term_t t,
# size_t *len, char **s,
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.restype = c_int
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.restype = c_int
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
PL_get_float.restype = c_int
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
PL_get_functor.restype = c_int
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
PL_get_name_arity.restype = c_int
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
PL_get_arg = _lib.PL_get_arg
PL_get_arg.argtypes = [c_int, term_t, term_t]
PL_get_arg.restype = c_int
#PL_EXPORT(int) PL_get_list(term_t l, term_t h, term_t t);
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
PL_get_head.restype = c_int
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
PL_get_tail.restype = c_int
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
PL_get_nil.restype = c_int
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_chars.restype = c_int
PL_put_atom_chars = check_strings(1, None)(PL_put_atom_chars)
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
PL_predicate = _lib.PL_predicate
PL_predicate.argtypes = [c_char_p, c_int, c_char_p]
PL_predicate.restype = predicate_t
PL_predicate = check_strings([0,2], None)(PL_predicate)
PL_pred = _lib.PL_pred
PL_pred.argtypes = [functor_t, module_t]
PL_pred.restype = predicate_t
PL_open_query = _lib.PL_open_query
PL_open_query.argtypes = [module_t, c_int, predicate_t, term_t]
PL_open_query.restype = qid_t
PL_next_solution = _lib.PL_next_solution
PL_next_solution.argtypes = [qid_t]
PL_next_solution.restype = c_int
PL_copy_term_ref = _lib.PL_copy_term_ref
PL_copy_term_ref.argtypes = [term_t]
PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_list.restype = c_int
PL_get_chars = _lib.PL_get_chars # FIXME
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
PL_close_query.restype = None
#void PL_cut_query(qid)
PL_cut_query = _lib.PL_cut_query
PL_cut_query.argtypes = [qid_t]
PL_cut_query.restype = None
PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_halt.restype = None
# PL_EXPORT(int) PL_cleanup(int status);
PL_cleanup = _lib.PL_cleanup
PL_cleanup.restype = c_int
PL_unify_integer = _lib.PL_unify_integer
PL_unify = _lib.PL_unify
PL_unify.restype = c_int
#PL_EXPORT(int) PL_unify_arg(int index, term_t t, term_t a) WUNUSED;
PL_unify_arg = _lib.PL_unify_arg
PL_unify_arg.argtypes = [c_int, term_t, term_t]
PL_unify_arg.restype = c_int
# Verify types
PL_term_type = _lib.PL_term_type
PL_term_type.argtypes = [term_t]
PL_term_type.restype = c_int
PL_is_variable = _lib.PL_is_variable
PL_is_variable.argtypes = [term_t]
PL_is_variable.restype = c_int
PL_is_ground = _lib.PL_is_ground
PL_is_ground.argtypes = [term_t]
PL_is_ground.restype = c_int
PL_is_atom = _lib.PL_is_atom
PL_is_atom.argtypes = [term_t]
PL_is_atom.restype = c_int
PL_is_integer = _lib.PL_is_integer
PL_is_integer.argtypes = [term_t]
PL_is_integer.restype = c_int
PL_is_string = _lib.PL_is_string
PL_is_string.argtypes = [term_t]
PL_is_string.restype = c_int
PL_is_float = _lib.PL_is_float
PL_is_float.argtypes = [term_t]
PL_is_float.restype = c_int
#PL_is_rational = _lib.PL_is_rational
#PL_is_rational.argtypes = [term_t]
#PL_is_rational.restype = c_int
PL_is_compound = _lib.PL_is_compound
PL_is_compound.argtypes = [term_t]
PL_is_compound.restype = c_int
PL_is_functor = _lib.PL_is_functor
PL_is_functor.argtypes = [term_t, functor_t]
PL_is_functor.restype = c_int
PL_is_list = _lib.PL_is_list
PL_is_list.argtypes = [term_t]
PL_is_list.restype = c_int
PL_is_atomic = _lib.PL_is_atomic
PL_is_atomic.argtypes = [term_t]
PL_is_atomic.restype = c_int
PL_is_number = _lib.PL_is_number
PL_is_number.argtypes = [term_t]
PL_is_number.restype = c_int
# /* Assign to term-references */
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_list_codes(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_atom_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_string_nchars(term_t t, size_t len, const char *chars);
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
PL_cons_functor_v.argtypes = [term_t, functor_t, term_t]
PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
PL_cons_list.restype = None
#
# term_t PL_exception(qid_t qid)
PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign = check_strings(0, None)(PL_register_foreign)
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
PL_new_atom = _lib.PL_new_atom
PL_new_atom.argtypes = [c_char_p]
PL_new_atom.restype = atom_t
PL_new_atom = check_strings(0, None)(PL_new_atom)
#PL_EXPORT(functor_t) PL_new_functor(atom_t f, int a);
PL_new_functor = _lib.PL_new_functor
PL_new_functor.argtypes = [atom_t, c_int]
PL_new_functor.restype = functor_t
# /*******************************
# * COMPARE *
# *******************************/
#
#PL_EXPORT(int) PL_compare(term_t t1, term_t t2);
#PL_EXPORT(int) PL_same_compound(term_t t1, term_t t2);
PL_compare = _lib.PL_compare
PL_compare.argtypes = [term_t, term_t]
PL_compare.restype = c_int
PL_same_compound = _lib.PL_same_compound
PL_same_compound.argtypes = [term_t, term_t]
PL_same_compound.restype = c_int
# /*******************************
# * RECORDED DATABASE *
# *******************************/
#
#PL_EXPORT(record_t) PL_record(term_t term);
PL_record = _lib.PL_record
PL_record.argtypes = [term_t]
PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t, term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
#PL_EXPORT(int) PL_erase_external(char *rec);
PL_new_module = _lib.PL_new_module
PL_new_module.argtypes = [atom_t]
PL_new_module.restype = module_t
PL_is_initialised = _lib.PL_is_initialised
intptr_t = c_long
ssize_t = intptr_t
wint_t = c_uint
#typedef struct
#{
# int __count;
# union
# {
# wint_t __wch;
# char __wchb[4];
# } __value; /* Value so far. */
#} __mbstate_t;
class _mbstate_t_value(Union):
_fields_ = [("__wch",wint_t),
("__wchb",c_char*4)]
class mbstate_t(Structure):
_fields_ = [("__count",c_int),
("__value",_mbstate_t_value)]
# stream related funcs
Sread_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Swrite_function = CFUNCTYPE(ssize_t, c_void_p, c_char_p, c_size_t)
Sseek_function = CFUNCTYPE(c_long, c_void_p, c_long, c_int)
Sseek64_function = CFUNCTYPE(c_int64, c_void_p, c_int64, c_int)
Sclose_function = CFUNCTYPE(c_int, c_void_p)
Scontrol_function = CFUNCTYPE(c_int, c_void_p, c_int, c_void_p)
# IOLOCK
IOLOCK = c_void_p
# IOFUNCTIONS
class IOFUNCTIONS(Structure):
_fields_ = [("read",Sread_function),
("write",Swrite_function),
("seek",Sseek_function),
("close",Sclose_function),
("seek64",Sseek64_function),
("reserved",intptr_t*2)]
# IOENC
ENC_UNKNOWN,ENC_OCTET,ENC_ASCII,ENC_ISO_LATIN_1,ENC_ANSI,ENC_UTF8,ENC_UNICODE_BE,ENC_UNICODE_LE,ENC_WCHAR = tuple(range(9))
IOENC = c_int
# IOPOS
class IOPOS(Structure):
_fields_ = [("byteno",c_int64),
("charno",c_int64),
("lineno",c_int),
("linepos",c_int),
("reserved", intptr_t*2)]
# IOSTREAM
class IOSTREAM(Structure):
_fields_ = [("bufp",c_char_p),
("limitp",c_char_p),
("buffer",c_char_p),
("unbuffer",c_char_p),
("lastc",c_int),
("magic",c_int),
("bufsize",c_int),
("flags",c_int),
("posbuf",IOPOS),
("position",POINTER(IOPOS)),
("handle",c_void_p),
("functions",IOFUNCTIONS),
("locks",c_int),
("mutex",IOLOCK),
("closure_hook",CFUNCTYPE(None, c_void_p)),
("closure",c_void_p),
("timeout",c_int),
("message",c_char_p),
("encoding",IOENC)]
IOSTREAM._fields_.extend([("tee",IOSTREAM),
("mbstate",POINTER(mbstate_t)),
("reserved",intptr_t*6)])
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
#create an exit hook which captures the exit code for our cleanup function
class ExitHook(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
_hook = ExitHook()
_hook.hook()
_isCleaned = False
#create a property for Atom's delete method in order to avoid segmentation fault
cleaned = property(_isCleaned)
#register the cleanup function to be executed on system exit
@atexit.register
def cleanupProlog():
# only do something if prolog has been initialised
if PL_is_initialised(None,None):
# clean up the prolog system using the caught exit code
# if exit code is None, the program exits normally and we can use 0
# instead.
# TODO Prolog documentation says cleanup with code 0 may be interrupted
# If the program has come to an end the prolog system should not
# interfere with that. Therefore we may want to use 1 instead of 0.
PL_cleanup(int(_hook.exit_code or 0))
_isCleaned = True
|
yuce/pyswip | pyswip/prolog.py | Prolog.query | python | def query(cls, query, maxresult=-1, catcherrors=True, normalize=True):
return cls._QueryWrapper()(query, maxresult, catcherrors, normalize) | Run a prolog query and return a generator.
If the query is a yes/no question, returns {} for yes, and nothing for no.
Otherwise returns a generator of dicts with variables as keys.
>>> prolog = Prolog()
>>> prolog.assertz("father(michael,john)")
>>> prolog.assertz("father(michael,gina)")
>>> bool(list(prolog.query("father(michael,john)")))
True
>>> bool(list(prolog.query("father(michael,olivia)")))
False
>>> print sorted(prolog.query("father(michael,X)"))
[{'X': 'gina'}, {'X': 'john'}] | train | https://github.com/yuce/pyswip/blob/f7c1f1e8c3a13b90bd775861d374788a8b5677d8/pyswip/prolog.py#L159-L174 | null | class Prolog:
"""Easily query SWI-Prolog.
This is a singleton class
"""
# We keep track of open queries to avoid nested queries.
_queryIsOpen = False
class _QueryWrapper(object):
def __init__(self):
if Prolog._queryIsOpen:
raise NestedQueryError("The last query was not closed")
def __call__(self, query, maxresult, catcherrors, normalize):
swipl_fid = PL_open_foreign_frame()
swipl_head = PL_new_term_ref()
swipl_args = PL_new_term_refs(2)
swipl_goalCharList = swipl_args
swipl_bindingList = swipl_args + 1
PL_put_list_chars(swipl_goalCharList, query)
swipl_predicate = PL_predicate("pyrun", 2, None)
plq = catcherrors and (PL_Q_NODEBUG|PL_Q_CATCH_EXCEPTION) or PL_Q_NORMAL
swipl_qid = PL_open_query(None, plq, swipl_predicate, swipl_args)
Prolog._queryIsOpen = True # From now on, the query will be considered open
try:
while maxresult and PL_next_solution(swipl_qid):
maxresult -= 1
bindings = []
swipl_list = PL_copy_term_ref(swipl_bindingList)
t = getTerm(swipl_list)
if normalize:
try:
v = t.value
except AttributeError:
v = {}
for r in [x.value for x in t]:
v.update(r)
yield v
else:
yield t
if PL_exception(swipl_qid):
term = getTerm(PL_exception(swipl_qid))
raise PrologError("".join(["Caused by: '", query, "'. ",
"Returned: '", str(term), "'."]))
finally: # This ensures that, whatever happens, we close the query
PL_cut_query(swipl_qid)
PL_discard_foreign_frame(swipl_fid)
Prolog._queryIsOpen = False
@classmethod
def asserta(cls, assertion, catcherrors=False):
next(cls.query(assertion.join(["asserta((", "))."]), catcherrors=catcherrors))
@classmethod
def assertz(cls, assertion, catcherrors=False):
next(cls.query(assertion.join(["assertz((", "))."]), catcherrors=catcherrors))
@classmethod
def dynamic(cls, term, catcherrors=False):
next(cls.query(term.join(["dynamic((", "))."]), catcherrors=catcherrors))
@classmethod
def retract(cls, term, catcherrors=False):
next(cls.query(term.join(["retract((", "))."]), catcherrors=catcherrors))
@classmethod
def retractall(cls, term, catcherrors=False):
next(cls.query(term.join(["retractall((", "))."]), catcherrors=catcherrors))
@classmethod
def consult(cls, filename, catcherrors=False):
next(cls.query(filename.join(["consult('", "')"]), catcherrors=catcherrors))
@classmethod
|
pokerregion/poker | poker/website/pocketfives.py | get_ranked_players | python | def get_ranked_players():
rankings_page = requests.get(RANKINGS_URL)
root = etree.HTML(rankings_page.text)
player_rows = root.xpath('//div[@id="ranked"]//tr')
for row in player_rows[1:]:
player_row = row.xpath('td[@class!="country"]//text()')
yield _Player(
name=player_row[1],
country=row[1][0].get('title'),
triple_crowns=player_row[3],
monthly_win=player_row[4],
biggest_cash=player_row[5],
plb_score=player_row[6],
biggest_score=player_row[7],
average_score=player_row[8],
previous_rank=player_row[9],
) | Get the list of the first 100 ranked players. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/pocketfives.py#L31-L50 | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import attr
import requests
from lxml import etree
from .._common import _make_float
__all__ = ['get_ranked_players', 'WEBSITE_URL', 'RANKINGS_URL']
WEBSITE_URL = 'http://www.pocketfives.com'
RANKINGS_URL = WEBSITE_URL + '/rankings/'
@attr.s(slots=True)
class _Player(object):
"""Pocketfives player data."""
name = attr.ib()
country = attr.ib()
triple_crowns = attr.ib(convert=int)
monthly_win = attr.ib(convert=int)
biggest_cash = attr.ib()
plb_score = attr.ib(convert=_make_float)
biggest_score = attr.ib(convert=_make_float)
average_score = attr.ib(convert=_make_float)
previous_rank = attr.ib(convert=_make_float)
|
pokerregion/poker | poker/card.py | Rank.difference | python | def difference(cls, first, second):
# so we always get a Rank instance even if string were passed in
first, second = cls(first), cls(second)
rank_list = list(cls)
return abs(rank_list.index(first) - rank_list.index(second)) | Tells the numerical difference between two ranks. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/card.py#L42-L48 | null | class Rank(PokerEnum):
__order__ = 'DEUCE THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING ACE'
DEUCE = '2', 2
THREE = '3', 3
FOUR = '4', 4
FIVE = '5', 5
SIX = '6', 6
SEVEN = '7', 7
EIGHT = '8', 8
NINE = '9', 9
TEN = 'T', 10
JACK = 'J',
QUEEN = 'Q',
KING = 'K',
ACE = 'A', 1
@classmethod
|
pokerregion/poker | poker/card.py | _CardMeta.make_random | python | def make_random(cls):
self = object.__new__(cls)
self.rank = Rank.make_random()
self.suit = Suit.make_random()
return self | Returns a random Card instance. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/card.py#L64-L69 | null | class _CardMeta(type):
def __new__(metacls, clsname, bases, classdict):
"""Cache all possible Card instances on the class itself."""
cls = super(_CardMeta, metacls).__new__(metacls, clsname, bases, classdict)
cls._all_cards = list(cls('{}{}'.format(rank, suit))
for rank, suit in itertools.product(Rank, Suit))
return cls
def __iter__(cls):
return iter(cls._all_cards)
|
pokerregion/poker | poker/commands.py | range_ | python | def range_(range, no_border, html):
from .hand import Range
border = not no_border
result = Range(range).to_html() if html else Range(range).to_ascii(border)
click.echo(result) | Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+" | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L46-L54 | [
"def to_html(self):\n \"\"\"Returns a 13x13 HTML table representing the range.\n\n The table's CSS class is ``range``, pair cells (td element) are ``pair``, offsuit hands are\n ``offsuit`` and suited hand cells has ``suited`` css class.\n The HTML contains no extra whitespace at all.\n Calculating it... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import sys
import collections
import contextlib
import datetime as dt
from dateutil import tz
import click
LOCALTIMEZONE = tz.tzlocal()
def _print_header(title):
click.echo(title)
click.echo('-' * len(title))
def _print_values(*args):
for what, value in args:
valueformat = "{!s}"
if not value:
value = '-'
elif isinstance(value, int):
valueformat = "{:,}"
elif isinstance(value, dt.datetime):
value = value.astimezone(LOCALTIMEZONE)
valueformat = "{:%Y-%m-%d (%A) %H:%M (%Z)}"
elif isinstance(value, dt.date):
valueformat = "{:%Y-%m-%d}"
elif isinstance(value, collections.Sequence) and not isinstance(value, unicode):
value = ', '.join(value)
click.echo(('{:<20}' + valueformat).format(what + ': ', value))
@click.group()
def poker():
"""Main command for the poker framework."""
@poker.command('range', short_help="Prints the range in a formatted table in ASCII or HTML.")
@click.argument('range')
@click.option('--no-border', is_flag=True, help="Don't show border.")
@click.option('--html', is_flag=True, help="Output html, so you can paste it on a website.")
@poker.command('2p2player', short_help="Get profile information about a Two plus Two member.")
@click.argument('username')
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickException('User "%s" not found!' % username)
except AmbiguousUserNameError as e:
click.echo('Got multiple users with similar names!', err=True)
for ind, user in enumerate(e.users):
click.echo('{}. {}'.format(ind + 1, user.name), err=True)
number = click.prompt('Which would you like to see [{}-{}]'.format(1, len(e.users)),
prompt_suffix='? ', type=click.IntRange(1, len(e.users)), err=True)
userid = e.users[int(number) - 1].id
member = ForumMember.from_userid(userid)
click.echo(err=True) # empty line after input
_print_header('Two plus two forum member')
_print_values(
('Username', member.username),
('Forum id', member.id),
('Location', member.location),
('Total posts', member.total_posts),
('Posts per day', member.posts_per_day),
('Rank', member.rank),
('Last activity', member.last_activity),
('Join date', member.join_date),
('Usergroups', member.public_usergroups),
('Profile picture', member.profile_picture),
('Avatar', member.avatar),
)
@poker.command(short_help="List pocketfives ranked players (1-100).")
@click.argument('num', type=click.IntRange(1, 100), default=100)
def p5list(num):
"""List pocketfives ranked players, max 100 if no NUM, or NUM if specified."""
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(format_str.format(
'Rank' , 'Player name', 'Country', 'Triple', 'Monthly', 'Biggest cash',
'PLB score', 'Biggest s', 'Average s', 'Prev'
))
# just generate the appropriate number of underlines and cut them with format_str
underlines = ['-' * 20] * 10
click.echo(format_str.format(*underlines))
for ind, player in enumerate(get_ranked_players()):
click.echo(format_str.format(str(ind + 1) + '.', *player))
if ind == num - 1:
break
@poker.command(short_help="Show PokerStars status like active players.")
def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', status.players),
('Active tournaments', status.active_tournaments),
('Total tournaments', status.total_tournaments),
('Clubs', status.clubs),
('Club members', status.club_members),
)
site_format_str = '{0.id:<12} {0.tables:<7,} {0.players:<8,} {0.active_tournaments:,}'
click.echo('\nSite Tables Players Tournaments')
click.echo('----------- ------ ------- -----------')
for site in status.sites:
click.echo(site_format_str.format(site))
|
pokerregion/poker | poker/commands.py | twoplustwo_player | python | def twoplustwo_player(username):
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickException('User "%s" not found!' % username)
except AmbiguousUserNameError as e:
click.echo('Got multiple users with similar names!', err=True)
for ind, user in enumerate(e.users):
click.echo('{}. {}'.format(ind + 1, user.name), err=True)
number = click.prompt('Which would you like to see [{}-{}]'.format(1, len(e.users)),
prompt_suffix='? ', type=click.IntRange(1, len(e.users)), err=True)
userid = e.users[int(number) - 1].id
member = ForumMember.from_userid(userid)
click.echo(err=True) # empty line after input
_print_header('Two plus two forum member')
_print_values(
('Username', member.username),
('Forum id', member.id),
('Location', member.location),
('Total posts', member.total_posts),
('Posts per day', member.posts_per_day),
('Rank', member.rank),
('Last activity', member.last_activity),
('Join date', member.join_date),
('Usergroups', member.public_usergroups),
('Profile picture', member.profile_picture),
('Avatar', member.avatar),
) | Get profile information about a Two plus Two Forum member given the username. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L59-L95 | [
"def _print_header(title):\n click.echo(title)\n click.echo('-' * len(title))\n",
"def _print_values(*args):\n for what, value in args:\n valueformat = \"{!s}\"\n if not value:\n value = '-'\n elif isinstance(value, int):\n valueformat = \"{:,}\"\n elif i... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import sys
import collections
import contextlib
import datetime as dt
from dateutil import tz
import click
LOCALTIMEZONE = tz.tzlocal()
def _print_header(title):
click.echo(title)
click.echo('-' * len(title))
def _print_values(*args):
for what, value in args:
valueformat = "{!s}"
if not value:
value = '-'
elif isinstance(value, int):
valueformat = "{:,}"
elif isinstance(value, dt.datetime):
value = value.astimezone(LOCALTIMEZONE)
valueformat = "{:%Y-%m-%d (%A) %H:%M (%Z)}"
elif isinstance(value, dt.date):
valueformat = "{:%Y-%m-%d}"
elif isinstance(value, collections.Sequence) and not isinstance(value, unicode):
value = ', '.join(value)
click.echo(('{:<20}' + valueformat).format(what + ': ', value))
@click.group()
def poker():
"""Main command for the poker framework."""
@poker.command('range', short_help="Prints the range in a formatted table in ASCII or HTML.")
@click.argument('range')
@click.option('--no-border', is_flag=True, help="Don't show border.")
@click.option('--html', is_flag=True, help="Output html, so you can paste it on a website.")
def range_(range, no_border, html):
"""Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+"
"""
from .hand import Range
border = not no_border
result = Range(range).to_html() if html else Range(range).to_ascii(border)
click.echo(result)
@poker.command('2p2player', short_help="Get profile information about a Two plus Two member.")
@click.argument('username')
@poker.command(short_help="List pocketfives ranked players (1-100).")
@click.argument('num', type=click.IntRange(1, 100), default=100)
def p5list(num):
"""List pocketfives ranked players, max 100 if no NUM, or NUM if specified."""
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(format_str.format(
'Rank' , 'Player name', 'Country', 'Triple', 'Monthly', 'Biggest cash',
'PLB score', 'Biggest s', 'Average s', 'Prev'
))
# just generate the appropriate number of underlines and cut them with format_str
underlines = ['-' * 20] * 10
click.echo(format_str.format(*underlines))
for ind, player in enumerate(get_ranked_players()):
click.echo(format_str.format(str(ind + 1) + '.', *player))
if ind == num - 1:
break
@poker.command(short_help="Show PokerStars status like active players.")
def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', status.players),
('Active tournaments', status.active_tournaments),
('Total tournaments', status.total_tournaments),
('Clubs', status.clubs),
('Club members', status.club_members),
)
site_format_str = '{0.id:<12} {0.tables:<7,} {0.players:<8,} {0.active_tournaments:,}'
click.echo('\nSite Tables Players Tournaments')
click.echo('----------- ------ ------- -----------')
for site in status.sites:
click.echo(site_format_str.format(site))
|
pokerregion/poker | poker/commands.py | p5list | python | def p5list(num):
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(format_str.format(
'Rank' , 'Player name', 'Country', 'Triple', 'Monthly', 'Biggest cash',
'PLB score', 'Biggest s', 'Average s', 'Prev'
))
# just generate the appropriate number of underlines and cut them with format_str
underlines = ['-' * 20] * 10
click.echo(format_str.format(*underlines))
for ind, player in enumerate(get_ranked_players()):
click.echo(format_str.format(str(ind + 1) + '.', *player))
if ind == num - 1:
break | List pocketfives ranked players, max 100 if no NUM, or NUM if specified. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L100-L119 | [
"def get_ranked_players():\n \"\"\"Get the list of the first 100 ranked players.\"\"\"\n\n rankings_page = requests.get(RANKINGS_URL)\n root = etree.HTML(rankings_page.text)\n player_rows = root.xpath('//div[@id=\"ranked\"]//tr')\n\n for row in player_rows[1:]:\n player_row = row.xpath('td[@cl... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import sys
import collections
import contextlib
import datetime as dt
from dateutil import tz
import click
LOCALTIMEZONE = tz.tzlocal()
def _print_header(title):
click.echo(title)
click.echo('-' * len(title))
def _print_values(*args):
for what, value in args:
valueformat = "{!s}"
if not value:
value = '-'
elif isinstance(value, int):
valueformat = "{:,}"
elif isinstance(value, dt.datetime):
value = value.astimezone(LOCALTIMEZONE)
valueformat = "{:%Y-%m-%d (%A) %H:%M (%Z)}"
elif isinstance(value, dt.date):
valueformat = "{:%Y-%m-%d}"
elif isinstance(value, collections.Sequence) and not isinstance(value, unicode):
value = ', '.join(value)
click.echo(('{:<20}' + valueformat).format(what + ': ', value))
@click.group()
def poker():
"""Main command for the poker framework."""
@poker.command('range', short_help="Prints the range in a formatted table in ASCII or HTML.")
@click.argument('range')
@click.option('--no-border', is_flag=True, help="Don't show border.")
@click.option('--html', is_flag=True, help="Output html, so you can paste it on a website.")
def range_(range, no_border, html):
"""Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+"
"""
from .hand import Range
border = not no_border
result = Range(range).to_html() if html else Range(range).to_ascii(border)
click.echo(result)
@poker.command('2p2player', short_help="Get profile information about a Two plus Two member.")
@click.argument('username')
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickException('User "%s" not found!' % username)
except AmbiguousUserNameError as e:
click.echo('Got multiple users with similar names!', err=True)
for ind, user in enumerate(e.users):
click.echo('{}. {}'.format(ind + 1, user.name), err=True)
number = click.prompt('Which would you like to see [{}-{}]'.format(1, len(e.users)),
prompt_suffix='? ', type=click.IntRange(1, len(e.users)), err=True)
userid = e.users[int(number) - 1].id
member = ForumMember.from_userid(userid)
click.echo(err=True) # empty line after input
_print_header('Two plus two forum member')
_print_values(
('Username', member.username),
('Forum id', member.id),
('Location', member.location),
('Total posts', member.total_posts),
('Posts per day', member.posts_per_day),
('Rank', member.rank),
('Last activity', member.last_activity),
('Join date', member.join_date),
('Usergroups', member.public_usergroups),
('Profile picture', member.profile_picture),
('Avatar', member.avatar),
)
@poker.command(short_help="List pocketfives ranked players (1-100).")
@click.argument('num', type=click.IntRange(1, 100), default=100)
@poker.command(short_help="Show PokerStars status like active players.")
def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', status.players),
('Active tournaments', status.active_tournaments),
('Total tournaments', status.total_tournaments),
('Clubs', status.clubs),
('Club members', status.club_members),
)
site_format_str = '{0.id:<12} {0.tables:<7,} {0.players:<8,} {0.active_tournaments:,}'
click.echo('\nSite Tables Players Tournaments')
click.echo('----------- ------ ------- -----------')
for site in status.sites:
click.echo(site_format_str.format(site))
|
pokerregion/poker | poker/commands.py | psstatus | python | def psstatus():
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', status.players),
('Active tournaments', status.active_tournaments),
('Total tournaments', status.total_tournaments),
('Clubs', status.clubs),
('Club members', status.club_members),
)
site_format_str = '{0.id:<12} {0.tables:<7,} {0.players:<8,} {0.active_tournaments:,}'
click.echo('\nSite Tables Players Tournaments')
click.echo('----------- ------ ------- -----------')
for site in status.sites:
click.echo(site_format_str.format(site)) | Shows PokerStars status such as number of players, tournaments. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L123-L145 | [
"def _print_header(title):\n click.echo(title)\n click.echo('-' * len(title))\n",
"def _print_values(*args):\n for what, value in args:\n valueformat = \"{!s}\"\n if not value:\n value = '-'\n elif isinstance(value, int):\n valueformat = \"{:,}\"\n elif i... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import sys
import collections
import contextlib
import datetime as dt
from dateutil import tz
import click
LOCALTIMEZONE = tz.tzlocal()
def _print_header(title):
click.echo(title)
click.echo('-' * len(title))
def _print_values(*args):
for what, value in args:
valueformat = "{!s}"
if not value:
value = '-'
elif isinstance(value, int):
valueformat = "{:,}"
elif isinstance(value, dt.datetime):
value = value.astimezone(LOCALTIMEZONE)
valueformat = "{:%Y-%m-%d (%A) %H:%M (%Z)}"
elif isinstance(value, dt.date):
valueformat = "{:%Y-%m-%d}"
elif isinstance(value, collections.Sequence) and not isinstance(value, unicode):
value = ', '.join(value)
click.echo(('{:<20}' + valueformat).format(what + ': ', value))
@click.group()
def poker():
"""Main command for the poker framework."""
@poker.command('range', short_help="Prints the range in a formatted table in ASCII or HTML.")
@click.argument('range')
@click.option('--no-border', is_flag=True, help="Don't show border.")
@click.option('--html', is_flag=True, help="Output html, so you can paste it on a website.")
def range_(range, no_border, html):
"""Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+"
"""
from .hand import Range
border = not no_border
result = Range(range).to_html() if html else Range(range).to_ascii(border)
click.echo(result)
@poker.command('2p2player', short_help="Get profile information about a Two plus Two member.")
@click.argument('username')
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickException('User "%s" not found!' % username)
except AmbiguousUserNameError as e:
click.echo('Got multiple users with similar names!', err=True)
for ind, user in enumerate(e.users):
click.echo('{}. {}'.format(ind + 1, user.name), err=True)
number = click.prompt('Which would you like to see [{}-{}]'.format(1, len(e.users)),
prompt_suffix='? ', type=click.IntRange(1, len(e.users)), err=True)
userid = e.users[int(number) - 1].id
member = ForumMember.from_userid(userid)
click.echo(err=True) # empty line after input
_print_header('Two plus two forum member')
_print_values(
('Username', member.username),
('Forum id', member.id),
('Location', member.location),
('Total posts', member.total_posts),
('Posts per day', member.posts_per_day),
('Rank', member.rank),
('Last activity', member.last_activity),
('Join date', member.join_date),
('Usergroups', member.public_usergroups),
('Profile picture', member.profile_picture),
('Avatar', member.avatar),
)
@poker.command(short_help="List pocketfives ranked players (1-100).")
@click.argument('num', type=click.IntRange(1, 100), default=100)
def p5list(num):
"""List pocketfives ranked players, max 100 if no NUM, or NUM if specified."""
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(format_str.format(
'Rank' , 'Player name', 'Country', 'Triple', 'Monthly', 'Biggest cash',
'PLB score', 'Biggest s', 'Average s', 'Prev'
))
# just generate the appropriate number of underlines and cut them with format_str
underlines = ['-' * 20] * 10
click.echo(format_str.format(*underlines))
for ind, player in enumerate(get_ranked_players()):
click.echo(format_str.format(str(ind + 1) + '.', *player))
if ind == num - 1:
break
@poker.command(short_help="Show PokerStars status like active players.")
|
pokerregion/poker | poker/room/pokerstars.py | Notes.notes | python | def notes(self):
return tuple(self._get_note_data(note) for note in self.root.iter('note')) | Tuple of notes.. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L335-L337 | null | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.