This commit is contained in:
gsinghpal
2026-05-16 13:07:50 -04:00
parent 00981a502a
commit 191a9c82be
1290 changed files with 220094 additions and 0 deletions

View File

@@ -0,0 +1,247 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"

View File

@@ -0,0 +1,76 @@
# This file must be used with "source bin/activate" *from bash*
# You cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# Call hash to forget past locations. Without forgetting
# past locations the $PATH changes we made may not be respected.
# See "man bash" for more details. hash is usually a builtin of your shell
hash -r 2> /dev/null
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
# on Windows, a path can contain colons and backslashes and has to be converted:
case "$(uname)" in
CYGWIN*|MSYS*|MINGW*)
# transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW
# and to /cygdrive/d/path/to/venv on Cygwin
VIRTUAL_ENV=$(cygpath /Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv)
export VIRTUAL_ENV
;;
*)
# use the path as-is
export VIRTUAL_ENV=/Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv
;;
esac
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"bin":$PATH"
export PATH
VIRTUAL_ENV_PROMPT='(.venv) '
export VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1="("'(.venv) '") ${PS1:-}"
export PS1
fi
# Call hash to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
hash -r 2> /dev/null

View File

@@ -0,0 +1,27 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV /Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
set prompt = '(.venv) '"$prompt"
setenv VIRTUAL_ENV_PROMPT '(.venv) '
endif
alias pydoc python -m pydoc
rehash

View File

@@ -0,0 +1,69 @@
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
# (https://fishshell.com/). You cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment"
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
set -e _OLD_FISH_PROMPT_OVERRIDE
# prevents error when using nested fish instances (Issue #93858)
if functions -q _old_fish_prompt
functions -e fish_prompt
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
end
set -e VIRTUAL_ENV
set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != "nondestructive"
# Self-destruct!
functions -e deactivate
end
end
# Unset irrelevant variables.
deactivate nondestructive
set -gx VIRTUAL_ENV /Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
# Unset PYTHONHOME if set.
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt.
functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own.
function fish_prompt
# Save the return status of the last command.
set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo.
printf "%s%s%s" (set_color 4B8BBE) '(.venv) ' (set_color normal)
# Restore the return status of the previous command.
echo "exit $old_status" | .
# Output the original/"old" prompt.
_old_fish_prompt
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
set -gx VIRTUAL_ENV_PROMPT '(.venv) '
end

View File

@@ -0,0 +1,7 @@
#!/Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv/bin/python3.12
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
if sys.argv[0].endswith('.exe'):
sys.argv[0] = sys.argv[0][:-4]
sys.exit(main())

View File

@@ -0,0 +1,7 @@
#!/Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv/bin/python3.12
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
if sys.argv[0].endswith('.exe'):
sys.argv[0] = sys.argv[0][:-4]
sys.exit(main())

View File

@@ -0,0 +1,7 @@
#!/Users/gurpreet/Github/Odoo-Modules/tools/fusion_clock_acr_wedge/.venv/bin/python3.12
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
if sys.argv[0].endswith('.exe'):
sys.argv[0] = sys.argv[0][:-4]
sys.exit(main())

View File

@@ -0,0 +1 @@
python3.12

View File

@@ -0,0 +1 @@
python3.12

View File

@@ -0,0 +1 @@
/opt/homebrew/opt/python@3.12/bin/python3.12

View File

@@ -0,0 +1,234 @@
"""
Python mapping for the AppKit framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import Foundation
import objc
from . import _metadata, _nsapp, _AppKit
from ._inlines import _inline_list_
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="AppKit",
frameworkIdentifier="com.apple.AppKit",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/AppKit.framework"
),
globals_dict=globals(),
inline_list=_inline_list_,
parents=(
_nsapp,
_AppKit,
Foundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
for cls, sel in (
("NSTouchBarItem", b"init"),
("NSTextFieldCell", b"initImageCell:"),
("NSTextViewportLayoutController", b"init"),
("NSTextViewportLayoutController", b"new"),
("NSFormCell", b"initImageCell:"),
("NSTextListElement", b"initWithAttributedString:"),
("NSTextSelectionNavigation", b"init"),
("NSTextSelectionNavigation", b"new"),
("NSTextRange", b"init"),
("NSTextRange", b"new"),
("NSTextCheckingController", b"init"),
("NSFontAssetRequest", b"init"),
("NSDictionaryControllerKeyValuePair", b"init"),
("NSSharingService", b"init"),
("NSSharingServicePicker", b"init"),
("NSMenuItemBadge", b"init"),
("NSTextInputContext", b"init"),
("NSAccessibilityCustomRotorItemResult", b"init"),
("NSAccessibilityCustomRotorItemResult", b"new"),
("NSWindow", b"initWithCoder:"),
("NSCollectionViewDiffableDataSource", b"init"),
("NSCollectionViewDiffableDataSource", b"new"),
("NSDraggingImageComponent", b"init"),
("NSDraggingItem", b"init"),
("NSSearchToolbarItem", b"view"),
("NSTableViewDiffableDataSource", b"init"),
("NSTableViewDiffableDataSource", b"new"),
("NSSearchFieldCell", b"initImageCell:"),
("NSDataAsset", b"init"),
("NSRulerMarker", b"init"),
("NSTextSelection", b"init"),
("NSDatePickerCell", b"initWithImageCell:"),
("NSCollectionViewCompositionalLayout", b"init"),
("NSCollectionViewCompositionalLayout", b"new"),
("NSCollectionLayoutSection", b"init"),
("NSCollectionLayoutSection", b"new"),
("NSCollectionLayoutItem", b"init"),
("NSCollectionLayoutItem", b"new"),
("NSCollectionLayoutGroupCustomItem", b"init"),
("NSCollectionLayoutGroupCustomItem", b"new"),
("NSCollectionLayoutGroup", b"init"),
("NSCollectionLayoutGroup", b"new"),
("NSCollectionLayoutDimension", b"init"),
("NSCollectionLayoutDimension", b"new"),
("NSCollectionLayoutSize", b"init"),
("NSCollectionLayoutSize", b"new"),
("NSCollectionLayoutSpacing", b"init"),
("NSCollectionLayoutSpacing", b"new"),
("NSCollectionLayoutEdgeSpacing", b"init"),
("NSCollectionLayoutEdgeSpacing", b"new"),
("NSCollectionLayoutSupplementaryItem", b"init"),
("NSCollectionLayoutSupplementaryItem", b"new"),
("NSCollectionLayoutBoundarySupplementaryItem", b"init"),
("NSCollectionLayoutBoundarySupplementaryItem", b"new"),
("NSCollectionLayoutDecorationItem", b"init"),
("NSCollectionLayoutDecorationItem", b"new"),
("NSCollectionLayoutAnchor", b"init"),
("NSCollectionLayoutAnchor", b"new"),
("NSTextLineFragment", b"init"),
("NSPreviewRepresentingActivityItem", b"init"),
("NSPreviewRepresentingActivityItem", b"new"),
("NSTextLayoutFragment", b"init"),
("NSBindingSelectionMarker", b"init"),
("NSTextAttachmentViewProvider", b"init"),
("NSTextAttachmentViewProvider", b"new"),
("NSWritingToolsCoordinatorAnimationParameters", b"init"),
("NSWritingToolsCoordinatorAnimationParameters", b"new"),
("NSWritingToolsCoordinatorContext", b"init"),
("NSWritingToolsCoordinatorContext", b"new"),
("NSViewLayoutRegion", b"init"),
("NSViewLayoutRegion", b"new"),
):
objc.registerUnavailableMethod(cls, sel)
del sys.modules["AppKit._metadata"]
def fontdescriptor_get(self, key, default=None):
value = self.objectForKey_(key)
if value is None:
return default
return value
def fontdescriptor_getitem(self, key, default=None):
value = self.objectForKey_(key)
if value is None:
raise KeyError(key)
return value
objc.addConvenienceForClass(
"NSFontDescriptor",
(("__getitem__", fontdescriptor_getitem), ("get", fontdescriptor_get)),
)
# Fix types for a number of character constants
# XXX: Move this to metadata
globals_dict = globals()
for nm in [
"NSEnterCharacter",
"NSBackspaceCharacter",
"NSTabCharacter",
"NSNewlineCharacter",
"NSFormFeedCharacter",
"NSCarriageReturnCharacter",
"NSBackTabCharacter",
"NSDeleteCharacter",
"NSLineSeparatorCharacter",
"NSParagraphSeparatorCharacter",
"NSUpArrowFunctionKey",
"NSDownArrowFunctionKey",
"NSLeftArrowFunctionKey",
"NSRightArrowFunctionKey",
"NSF1FunctionKey",
"NSF2FunctionKey",
"NSF3FunctionKey",
"NSF4FunctionKey",
"NSF5FunctionKey",
"NSF6FunctionKey",
"NSF7FunctionKey",
"NSF8FunctionKey",
"NSF9FunctionKey",
"NSF10FunctionKey",
"NSF11FunctionKey",
"NSF12FunctionKey",
"NSF13FunctionKey",
"NSF14FunctionKey",
"NSF15FunctionKey",
"NSF16FunctionKey",
"NSF17FunctionKey",
"NSF18FunctionKey",
"NSF19FunctionKey",
"NSF20FunctionKey",
"NSF21FunctionKey",
"NSF22FunctionKey",
"NSF23FunctionKey",
"NSF24FunctionKey",
"NSF25FunctionKey",
"NSF26FunctionKey",
"NSF27FunctionKey",
"NSF28FunctionKey",
"NSF29FunctionKey",
"NSF30FunctionKey",
"NSF31FunctionKey",
"NSF32FunctionKey",
"NSF33FunctionKey",
"NSF34FunctionKey",
"NSF35FunctionKey",
"NSInsertFunctionKey",
"NSDeleteFunctionKey",
"NSHomeFunctionKey",
"NSBeginFunctionKey",
"NSEndFunctionKey",
"NSPageUpFunctionKey",
"NSPageDownFunctionKey",
"NSPrintScreenFunctionKey",
"NSScrollLockFunctionKey",
"NSPauseFunctionKey",
"NSSysReqFunctionKey",
"NSBreakFunctionKey",
"NSResetFunctionKey",
"NSStopFunctionKey",
"NSMenuFunctionKey",
"NSUserFunctionKey",
"NSSystemFunctionKey",
"NSPrintFunctionKey",
"NSClearLineFunctionKey",
"NSClearDisplayFunctionKey",
"NSInsertLineFunctionKey",
"NSDeleteLineFunctionKey",
"NSInsertCharFunctionKey",
"NSDeleteCharFunctionKey",
"NSPrevFunctionKey",
"NSNextFunctionKey",
"NSSelectFunctionKey",
"NSExecuteFunctionKey",
"NSUndoFunctionKey",
"NSRedoFunctionKey",
"NSFindFunctionKey",
"NSHelpFunctionKey",
"NSModeSwitchFunctionKey",
]:
try:
globals_dict[nm] = chr(__getattr__(nm)) # noqa: F821
except AttributeError:
pass
globals().pop("_setup")()
def NSDictionaryOfVariableBindings(*names):
"""
Return a dictionary with the given names and there values.
"""
import sys
variables = sys._getframe(1).f_locals
return {nm: variables[nm] for nm in names}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
import objc as _objc
import AppKit as _AppKit
class _NSApp:
"""
Helper class to emulate NSApp in Python.
"""
def __getrealapp(self):
d = {}
_objc.loadBundleVariables(_AppKit.__bundle__, d, [("NSApp", b"@")])
return d.get("NSApp")
__class__ = property(lambda self: self.__getrealapp().__class__)
def __getattr__(self, name):
return getattr(self.__getrealapp(), name)
def __setattr__(self, name, value):
return setattr(self.__getrealapp(), name, value)
def __call__(self):
# Compatibility with previous versions.
return self.__getrealapp()
NSApp = _NSApp()
del _NSApp

View File

@@ -0,0 +1,27 @@
"""
Python mapping for the Cocoa framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import AppKit
import objc
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Cocoa",
frameworkIdentifier=None,
frameworkPath=None,
globals_dict=globals(),
inline_list=None,
parents=(AppKit,),
metadict={},
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
globals().pop("_setup")()

View File

@@ -0,0 +1,37 @@
"""
Python mapping for the CoreFoundation framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import objc
from . import _metadata, _CoreFoundation, _static
from ._inlines import _inline_list_
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="CoreFoundation",
frameworkIdentifier="com.apple.CoreFoundation",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/CoreFoundation.framework"
),
globals_dict=globals(),
inline_list=_inline_list_,
parents=(
_CoreFoundation,
_static,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["CoreFoundation._metadata"]
globals().pop("_setup")()

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,107 @@
import CoreFoundation as _CF
import objc as _objc
#
# 'Emulation' for CFArray constructors
#
def _setup():
NSArray = _objc.lookUpClass("NSArray")
NSMutableArray = _objc.lookUpClass("NSMutableArray")
def CFArrayCreate(allocator, values, numvalues, callbacks):
assert callbacks is None
return NSArray.alloc().initWithArray_(values[:numvalues])
def CFArrayCreateMutable(allocator, capacity, callbacks):
assert callbacks is None
return NSMutableArray.alloc().init()
return CFArrayCreate, CFArrayCreateMutable
CFArrayCreate, CFArrayCreateMutable = _setup()
# CFDictionary emulation functions
def _setup():
NSDictionary = _objc.lookUpClass("NSDictionary")
NSMutableDictionary = _objc.lookUpClass("NSMutableDictionary")
def CFDictionaryCreate(
allocator, keys, values, numValues, keyCallbacks, valueCallbacks
):
assert keyCallbacks is None
assert valueCallbacks is None
keys = list(keys)[:numValues]
values = list(values)[:numValues]
return NSDictionary.dictionaryWithDictionary_(dict(zip(keys, values)))
def CFDictionaryCreateMutable(allocator, capacity, keyCallbacks, valueCallbacks):
assert keyCallbacks is None
assert valueCallbacks is None
return NSMutableDictionary.dictionary()
return CFDictionaryCreate, CFDictionaryCreateMutable
CFDictionaryCreate, CFDictionaryCreateMutable = _setup()
# CFSet emulation functions
def _setup():
NSSet = _objc.lookUpClass("NSSet")
NSMutableSet = _objc.lookUpClass("NSMutableSet")
def CFSetCreate(allocator, values, numvalues, callbacks):
assert callbacks is None
return NSSet.alloc().initWithArray_(values[:numvalues])
def CFSetCreateMutable(allocator, capacity, callbacks):
assert callbacks is None
return NSMutableSet.alloc().init()
return CFSetCreate, CFSetCreateMutable
CFSetCreate, CFSetCreateMutable = _setup()
kCFTypeArrayCallBacks = None
kCFTypeDictionaryKeyCallBacks = None
kCFTypeDictionaryValueCallBacks = None
kCFTypeSetCallBacks = None
#
# Implementation of a number of macro's in the CFBundle API
#
def CFCopyLocalizedString(key, comment):
return _CF.CFBundleCopyLocalizedString(
_CF.CFBundleGetMainBundle(), (key), (key), None
)
def CFCopyLocalizedStringFromTable(key, tbl, comment):
return _CF.CFBundleCopyLocalizedString(
_CF.CFBundleGetMainBundle(), (key), (key), (tbl)
)
def CFCopyLocalizedStringFromTableInBundle(key, tbl, bundle, comment):
return _CF.CFBundleCopyLocalizedString((bundle), (key), (key), (tbl))
def CFCopyLocalizedStringWithDefaultValue(key, tbl, bundle, value, comment):
return _CF.CFBundleCopyLocalizedString((bundle), (key), (value), (tbl))
def CFSTR(strval):
return _objc.lookUpClass("NSString").stringWithString_(strval)

View File

@@ -0,0 +1,229 @@
"""
Python mapping for the Foundation framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import CoreFoundation
import objc
from . import _Foundation, _metadata, _functiondefines, _context
from ._inlines import _inline_list_
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Foundation",
frameworkIdentifier="com.apple.Foundation",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/Foundation.framework"
),
globals_dict=globals(),
inline_list=_inline_list_,
parents=(
_Foundation,
_functiondefines,
_context,
CoreFoundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
for cls, sel in (
("NSPresentationIntent", b"init"),
("NSURLSessionWebSocketMessage", b"init"),
("NSURLSessionWebSocketMessage", b"new"),
("NSURLSessionWebSocketTask", b"init"),
("NSURLSessionWebSocketTask", b"new"),
("NSInflectionRule", b"init"),
("NSMorphologyPronoun", b"init"),
("NSMorphologyPronoun", b"new"),
("NSTermOfAddress", b"init"),
("NSTermOfAddress", b"new"),
("NSObject", b"poseAsClass:"),
("NSBundleResourceRequest", b"init"),
("NSBundleResourceRequest", b"new"),
("NSCalendar", b"init"),
("NSCalendar", b"new"),
("NSDistributedLock", b"init"),
("NSDistributedLock", b"new"),
("NSLocale", b"init"),
("NSLocale", b"new"),
("NSMeasurement", b"init"),
("NSMeasurement", b"new"),
("NSOrderedCollectionChange", b"init"),
("NSOrderedCollectionChange", b"new"),
("NSScriptCommandDescription", b"init"),
("NSScriptCommandDescription", b"new"),
("NSScriptWhoseTests", b"init"),
("NSScriptWhoseTests", b"new"),
("NSUnit", b"init"),
("NSUnit", b"new"),
):
objc.registerUnavailableMethod(cls, sel)
del sys.modules["Foundation._metadata"]
objc.addConvenienceForClass(
"NSAttributedString", (("__len__", lambda self: self.length()),)
)
objc.addConvenienceForBasicMapping("NSMergeConflict", True)
objc.addConvenienceForBasicMapping("NSUbiquitousKeyValueStore", False)
objc.addConvenienceForBasicMapping("NSUserDefaults", False)
NSNull = objc.lookUpClass("NSNull")
def nscache_getitem(self, key):
value = self.objectForKey_(key)
if value is None:
raise KeyError(key)
elif value is NSNull.null():
return None
else:
return value
def nscache_get(self, key, default=None):
value = self.objectForKey_(key)
if value is None:
return default
elif value is NSNull.null():
return None
return value
def nscache_setitem(self, key, value):
if value is None:
value = NSNull.null()
self.setObject_forKey_(value, key)
objc.addConvenienceForClass(
"NSCache",
(
("__getitem__", nscache_getitem),
("get", nscache_get),
("__setitem__", nscache_setitem),
("__delitem__", lambda self, key: self.removeObjectForKey_(key)),
("clear", lambda self: self.removeAllObjects()),
),
)
def hash_add(self, value):
if value is None:
value = NSNull.null()
self.addObject_(value)
def hash_contains(self, value):
if value is None:
value = NSNull.null()
return self.containsObject_(value)
def hash_remove(self, value):
if value is None:
value = NSNull.null()
self.removeObject_(value)
def hash_pop(self):
value = self.anyObject()
self.removeObject_(value)
if value is NSNull.null():
return None
else:
return value
objc.addConvenienceForClass(
"NSHashTable",
(
("__len__", lambda self: self.count()),
("clear", lambda self: self.removeAllObjects()),
("__iter__", lambda self: iter(self.objectEnumerator())),
("add", hash_add),
("remove", hash_remove),
("__contains__", hash_contains),
("pop", hash_pop),
),
)
objc.addConvenienceForClass(
"NSIndexPath", (("__len__", lambda self: self.count()),)
)
if sys.maxsize > 2**32:
NSNotFound = 0x7FFFFFFFFFFFFFFF
else:
NSNotFound = 0x7FFFFFFF
def indexset_iter(self):
value = self.firstIndex()
while value != NSNotFound:
yield value
value = self.indexGreaterThanIndex_(value)
def indexset_reversed(self):
value = self.lastIndex()
while value != NSNotFound:
yield value
value = self.indexLessThanIndex_(value)
NSIndexSet = objc.lookUpClass("NSIndexSet")
def indexset_eq(self, other):
if not isinstance(other, NSIndexSet):
return False
return self.isEqualToIndexSet_(other)
def indexset_ne(self, other):
if not isinstance(other, NSIndexSet):
return True
return not self.isEqualToIndexSet_(other)
def indexset_contains(self, value):
try:
return self.containsIndex_(value)
except ValueError:
return False
objc.addConvenienceForClass(
"NSIndexSet",
(
("__len__", lambda self: self.count()),
("__iter__", indexset_iter),
("__reversed__", indexset_reversed),
("__eq__", indexset_eq),
("__ne__", indexset_ne),
("__contains__", indexset_contains),
),
)
# Add 'update', '-=', '+='
objc.addConvenienceForClass(
"NSMutableIndexSet",
(
("clear", lambda self: self.removeAllIndexes()),
("add", lambda self, value: self.addIndex_(value)),
("remove", lambda self, value: self.removeIndex_(value)),
),
)
objc.addConvenienceForClass(
"NSLocale", (("__getitem__", lambda self, key: self.objectForKey_(key)),)
)
globals().pop("_setup")()
from objc import NSDecimal, YES, NO # isort:skip # noqa: E402, F401
import Foundation._context # isort:skip # noqa: E402
import Foundation._functiondefines # isort:skip # noqa: E402
import Foundation._nsindexset # isort:skip # noqa: E402
import Foundation._nsobject # isort:skip # noqa: E402, F401
import Foundation._nsurl # isort:skip # noqa: E402, F401

View File

@@ -0,0 +1,26 @@
import Foundation
class NSDisabledAutomaticTermination:
def __init__(self, reason):
self._reason = reason
self._info = Foundation.NSProcessInfo.processInfo()
def __enter__(self):
self._info.disableAutomaticTermination_(self._reason)
def __exit__(self, exc_type, exc_val, exc_tb):
self._info.enableAutomaticTermination_(self._reason)
return False
class NSDisabledSuddenTermination:
def __init__(self):
self._info = Foundation.NSProcessInfo.processInfo()
def __enter__(self):
self._info.disableSuddenTermination()
def __exit__(self, exc_type, exc_val, exc_tb):
self._info.enableSuddenTermination()
return False

View File

@@ -0,0 +1,64 @@
"""
Port of "function defines".
"""
import Foundation as _Foundation
def NSLocalizedString(key, comment):
return _Foundation.NSBundle.mainBundle().localizedStringForKey_value_table_(
key, "", None
)
def NSLocalizedStringFromTable(key, tbl, comment):
return _Foundation.NSBundle.mainBundle().localizedStringForKey_value_table_(
key, "", tbl
)
def NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment):
return bundle.localizedStringForKey_value_table_(key, "", tbl)
def NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment):
return bundle.localizedStringForKey_value_table_(key, val, tbl)
def NSLocalizedAttributedString(key, comment):
return (
_Foundation.NSBundle.mainBundle().localizedAttributedStringForKey_value_table_(
key, "", None
)
)
def NSLocalizedAttributedStringFromTable(key, tbl, comment):
return _Foundation.NSBundle.mainBundle.localizedAttributedStringForKey_value_table_(
key, "", tbl
)
def NSLocalizedAttributedStringFromTableInBundle(key, tbl, bundle, comment):
return bundle.localizedAttributedStringForKey_value_table_(key, "", tbl)
def NSLocalizedAttributedStringWithDefaultValue(key, tbl, bundle, val, comment):
return bundle.localizedAttributedStringForKey_value_table_(key, val, tbl)
def MIN(a, b):
if a < b:
return a
else:
return b
def MAX(a, b):
if a < b:
return b
else:
return a
ABS = abs

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import objc
def __len__(self):
return self.length()
def __getitem__(self, idx):
if isinstance(idx, slice):
raise ValueError(idx)
return self.indexAtPosition_(idx)
def __add__(self, value):
return self.indexPathByAddingIndex_(value)
objc.addConvenienceForClass(
"NSIndexPath",
(("__len__", __len__), ("__getitem__", __getitem__), ("__add__", __add__)),
)

View File

@@ -0,0 +1,225 @@
"""
Define a category on NSObject with some useful methods.
"""
import sys
import objc
def _str(v):
if isinstance(v, str):
return v
return v.decode("ascii")
def _raise(exc_type, exc_value, exc_trace):
raise exc_type(exc_value).with_traceback(exc_trace)
NSObject = objc.lookUpClass("NSObject")
class NSObject(objc.Category(NSObject)):
@objc.namedSelector(b"_pyobjc_performOnThread:")
def _pyobjc_performOnThread_(self, callinfo):
try:
sel, arg = callinfo
m = getattr(self, _str(sel))
m(arg)
except: # noqa: E722, B001
import traceback
traceback.print_exc(file=sys.stderr)
@objc.namedSelector(b"_pyobjc_performOnThreadWithResult:")
def _pyobjc_performOnThreadWithResult_(self, callinfo):
try:
sel, arg, result = callinfo
m = getattr(self, _str(sel))
r = m(arg)
result.append((True, r))
except: # noqa: E722, B001
result.append((False, sys.exc_info()))
if hasattr(NSObject, "performSelector_onThread_withObject_waitUntilDone_"):
@objc.namedSelector(
b"pyobjc_performSelector:onThread:withObject:waitUntilDone:"
)
def pyobjc_performSelector_onThread_withObject_waitUntilDone_(
self, aSelector, thread, arg, wait
):
"""
A version of performSelector:onThread:withObject:waitUntilDone: that
will log exceptions in the called method (instead of aborting the
NSRunLoop on the other thread).
"""
self.performSelector_onThread_withObject_waitUntilDone_(
b"_pyobjc_performOnThread:", thread, (aSelector, arg), wait
)
@objc.namedSelector(
b"pyobjc_performSelector:onThread:withObject:waitUntilDone:modes:"
)
def pyobjc_performSelector_onThread_withObject_waitUntilDone_modes_(
self, aSelector, thread, arg, wait, modes
):
"""
A version of performSelector:onThread:withObject:waitUntilDone:modes:
that will log exceptions in the called method (instead of aborting the
NSRunLoop on the other thread).
"""
self.performSelector_onThread_withObject_waitUntilDone_modes_(
b"_pyobjc_performOnThread:", thread, (aSelector, arg), wait, modes
)
@objc.namedSelector(b"pyobjc_performSelector:withObject:afterDelay:")
def pyobjc_performSelector_withObject_afterDelay_(self, aSelector, arg, delay):
"""
A version of performSelector:withObject:afterDelay:
that will log exceptions in the called method (instead of aborting the
NSRunLoop).
"""
self.performSelector_withObject_afterDelay_(
b"_pyobjc_performOnThread:", (aSelector, arg), delay
)
@objc.namedSelector(b"pyobjc_performSelector:withObject:afterDelay:inModes:")
def pyobjc_performSelector_withObject_afterDelay_inModes_(
self, aSelector, arg, delay, modes
):
"""
A version of performSelector:withObject:afterDelay:inModes:
that will log exceptions in the called method (instead of aborting the
NSRunLoop).
"""
self.performSelector_withObject_afterDelay_inModes_(
b"_pyobjc_performOnThread:", (aSelector, arg), delay, modes
)
if hasattr(NSObject, "performSelectorInBackground_withObject_"):
@objc.namedSelector(b"pyobjc_performSelectorInBackground:withObject:")
def pyobjc_performSelectorInBackground_withObject_(self, aSelector, arg):
"""
A version of performSelectorInBackground:withObject:
that will log exceptions in the called method (instead of aborting the
NSRunLoop).
"""
self.performSelectorInBackground_withObject_(
b"_pyobjc_performOnThread:", (aSelector, arg)
)
@objc.namedSelector(b"pyobjc_performSelectorOnMainThread:withObject:waitUntilDone:")
def pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_(
self, aSelector, arg, wait
):
"""
A version of performSelectorOnMainThread:withObject:waitUntilDone:
that will log exceptions in the called method (instead of aborting the
NSRunLoop in the main thread).
"""
self.performSelectorOnMainThread_withObject_waitUntilDone_(
b"_pyobjc_performOnThread:", (aSelector, arg), wait
)
@objc.namedSelector(
b"pyobjc_performSelectorOnMainThread:withObject:waitUntilDone:modes:"
)
def pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_modes_(
self, aSelector, arg, wait, modes
):
"""
A version of performSelectorOnMainThread:withObject:waitUntilDone:modes:
that will log exceptions in the called method (instead of aborting the
NSRunLoop in the main thread).
"""
self.performSelectorOnMainThread_withObject_waitUntilDone_modes_(
b"_pyobjc_performOnThread:", (aSelector, arg), wait, modes
)
# And some a some versions that return results
@objc.namedSelector(b"pyobjc_performSelectorOnMainThread:withObject:modes:")
def pyobjc_performSelectorOnMainThread_withObject_modes_(
self, aSelector, arg, modes
):
"""
Similar to performSelectorOnMainThread:withObject:waitUntilDone:modes:,
but:
- always waits until done
- returns the return value of the called method
- if the called method raises an exception, this will raise the same
exception
"""
result = []
self.performSelectorOnMainThread_withObject_waitUntilDone_modes_(
b"_pyobjc_performOnThreadWithResult:", (aSelector, arg, result), True, modes
)
isOK, result = result[0]
if isOK:
return result
else:
exc_type, exc_value, exc_trace = result
_raise(exc_type, exc_value, exc_trace)
@objc.namedSelector(b"pyobjc_performSelectorOnMainThread:withObject:")
def pyobjc_performSelectorOnMainThread_withObject_(self, aSelector, arg):
result = []
self.performSelectorOnMainThread_withObject_waitUntilDone_(
b"_pyobjc_performOnThreadWithResult:", (aSelector, arg, result), True
)
isOK, result = result[0]
if isOK:
return result
else:
exc_type, exc_value, exc_trace = result
_raise(exc_type, exc_value, exc_trace)
if hasattr(NSObject, "performSelector_onThread_withObject_waitUntilDone_"):
# These methods require Leopard, don't define them if the
# platform functionality isn't present.
@objc.namedSelector(b"pyobjc_performSelector:onThread:withObject:modes:")
def pyobjc_performSelector_onThread_withObject_modes_(
self, aSelector, thread, arg, modes
):
result = []
self.performSelector_onThread_withObject_waitUntilDone_modes_(
b"_pyobjc_performOnThreadWithResult:",
thread,
(aSelector, arg, result),
True,
modes,
)
isOK, result = result[0]
if isOK:
return result
else:
exc_type, exc_value, exc_trace = result
_raise(exc_type, exc_value, exc_trace)
@objc.namedSelector(b"pyobjc_performSelector:onThread:withObject:")
def pyobjc_performSelector_onThread_withObject_(self, aSelector, thread, arg):
result = []
self.performSelector_onThread_withObject_waitUntilDone_(
b"_pyobjc_performOnThreadWithResult:",
thread,
(aSelector, arg, result),
True,
)
isOK, result = result[0]
if isOK:
return result
else:
exc_type, exc_value, exc_trace = result
_raise(exc_type, exc_value, exc_trace)
del NSObject

View File

@@ -0,0 +1,24 @@
"""
Helpers for NSURL
"""
import sys
import objc
def __fspath__(self):
if self.scheme() == "file":
# self.fileSystemRepresentation returns a byte string,
# whereas most user code expects regular strings. Decode
# in the same way as extension functions in the ``os`` module.
return self.fileSystemRepresentation().decode(
sys.getfilesystemencoding(), sys.getfilesystemencodeerrors()
)
raise TypeError(f"NSURL with scheme {self.scheme()!r} instead of 'file'")
objc.addConvenienceForClass(
"NSURL",
(("__fspath__", __fspath__),),
)

View File

@@ -0,0 +1,38 @@
"""
A number of useful categories on AppKit classes
"""
__all__ = ()
import objc
from AppKit import NSAnimationContext, NSGraphicsContext
class _ctxHelper:
def __enter__(self):
NSGraphicsContext.saveGraphicsState()
def __exit__(self, exc_type, exc_value, exc_tb):
NSGraphicsContext.restoreGraphicsState()
return False
class NSGraphicsContext(objc.Category(NSGraphicsContext)):
@classmethod
def savedGraphicsState(self):
return _ctxHelper()
@objc.python_method
def __enter__(cls):
cls.beginGrouping()
@objc.python_method
def __exit__(cls, exc_type, exc_value, exc_tb):
cls.endGrouping()
# Cannot use a category here because these special methods
# must be defined on the metaclass.
type(NSAnimationContext).__enter__ = __enter__
type(NSAnimationContext).__exit__ = __exit__

View File

@@ -0,0 +1,347 @@
"""AppKit helpers.
Exported functions:
* runEventLoop - run NSApplicationMain in a safer way
* runConsoleEventLoop - run NSRunLoop.run() in a stoppable manner
* stopEventLoop - stops the event loop or terminates the application
* endSheetMethod - set correct signature for NSSheet callbacks
* callAfter - call a function on the main thread (async)
* callLater - call a function on the main thread after a delay (async)
"""
__all__ = (
"runEventLoop",
"runConsoleEventLoop",
"stopEventLoop",
"endSheetMethod",
"callAfter",
"callLater",
)
import os
import sys
import traceback
import objc
from AppKit import (
NSApp,
NSApplicationDidFinishLaunchingNotification,
NSApplicationMain,
NSRunAlertPanel,
)
from Foundation import (
NSAutoreleasePool,
NSDate,
NSDefaultRunLoopMode,
NSLog,
NSNotificationCenter,
NSObject,
NSRunLoop,
NSThread,
NSTimer,
)
from objc import super # noqa: A004
class PyObjCMessageRunner(NSObject):
"""
Wraps a Python function and its arguments and allows it to be posted to the
MainThread's `NSRunLoop`.
"""
def initWithPayload_(self, payload):
"""
Designated initializer.
"""
self = super().init()
if not self:
return None
self._payload = payload
return self
def callAfter(self):
"""
Posts a message to the Main thread, to be executed immediately.
"""
self.performSelectorOnMainThread_withObject_waitUntilDone_(
self.scheduleCallWithDelay_, None, False
)
def callLater_(self, delay):
"""
Posts a message to the Main thread, to be executed after the given
delay, in seconds.
"""
self.performSelectorOnMainThread_withObject_waitUntilDone_(
self.scheduleCallWithDelay_, delay, False
)
def scheduleCallWithDelay_(self, delay):
"""
This is run once we're on the Main thread.
"""
assert NSThread.isMainThread(), "Call is not executing on the Main thread!"
# There's no delay, just run the call now.
if not delay:
self.performCall()
return
# There's a delay, schedule it for later.
self.performSelector_withObject_afterDelay_(self.performCall, None, delay)
def performCall(self):
"""
Actually runs the payload.
"""
assert NSThread.isMainThread(), "Call is not executing on the Main thread!"
# Unpack the payload.
(func, args, kwargs) = self._payload
# Run it.
func(*args, **kwargs)
def callAfter(func, *args, **kwargs):
"""
Call a function on the Main thread (async).
"""
pool = NSAutoreleasePool.alloc().init()
runner = PyObjCMessageRunner.alloc().initWithPayload_((func, args, kwargs))
runner.callAfter()
del runner
del pool
def callLater(delay, func, *args, **kwargs):
"""
Call a function on the Main thread after a delay (async).
"""
pool = NSAutoreleasePool.alloc().init()
runner = PyObjCMessageRunner.alloc().initWithPayload_((func, args, kwargs))
runner.callLater_(delay)
del runner
del pool
class PyObjCAppHelperApplicationActivator(NSObject):
def activateNow_(self, aNotification):
NSApp().activateIgnoringOtherApps_(True)
class PyObjCAppHelperRunLoopStopper(NSObject):
singletons = {}
@classmethod
def currentRunLoopStopper(cls):
runLoop = NSRunLoop.currentRunLoop()
return cls.singletons.get(runLoop)
def init(self):
self = super().init()
self.shouldStop = False
self.isConsole = False
return self
def shouldRun(self):
return not self.shouldStop
@classmethod
def addRunLoopStopper_toRunLoop_(cls, runLoopStopper, runLoop):
if runLoop in cls.singletons:
raise ValueError("Stopper already registered for this runLoop")
cls.singletons[runLoop] = runLoopStopper
@classmethod
def removeRunLoopStopperFromRunLoop_(cls, runLoop):
if runLoop not in cls.singletons:
raise ValueError("Stopper not registered for this runLoop")
del cls.singletons[runLoop]
def stop(self):
self.shouldStop = True
# this should go away when/if runEventLoop uses
# runLoop iteration
if not self.isConsole:
if NSApp() is not None:
NSApp().terminate_(self)
def performStop_(self, sender):
self.stop()
def stopEventLoop():
"""
Stop the current event loop if possible
returns True if it expects that it was successful, False otherwise
"""
stopper = PyObjCAppHelperRunLoopStopper.currentRunLoopStopper()
if stopper is None:
if NSApp() is not None:
NSApp().terminate_(None)
return True
return False
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
0.0, stopper, "performStop:", None, False
)
return True
def endSheetMethod(meth):
"""
Return a selector that can be used as the delegate callback for
sheet methods
"""
return objc.selector(
meth, signature=b"v@:@" + objc._C_NSInteger + objc._C_NSInteger
)
def unexpectedErrorAlertPanel():
exceptionInfo = traceback.format_exception_only(*sys.exc_info()[:2])[0].strip()
return NSRunAlertPanel(
"An unexpected error has occurred",
"%@",
"Continue",
"Quit",
None,
"(%s)" % exceptionInfo,
)
def unexpectedErrorAlertPdb():
import pdb
traceback.print_exc()
pdb.post_mortem(sys.exc_info()[2])
return True
def machInterrupt(signum):
stopper = PyObjCAppHelperRunLoopStopper.currentRunLoopStopper()
if stopper is not None:
stopper.stop()
elif NSApp() is not None:
NSApp().terminate_(None)
else:
import os
os._exit(1)
def installMachInterrupt():
import signal
from PyObjCTools import MachSignals
MachSignals.signal(signal.SIGINT, machInterrupt)
def runConsoleEventLoop(
argv=None, installInterrupt=False, mode=NSDefaultRunLoopMode, maxTimeout=3.0
):
if argv is None:
argv = sys.argv
if installInterrupt:
installMachInterrupt()
runLoop = NSRunLoop.currentRunLoop()
stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
stopper.isConsole = True
PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)
try:
while stopper.shouldRun():
nextfire = runLoop.limitDateForMode_(mode)
if not stopper.shouldRun():
break
soon = NSDate.dateWithTimeIntervalSinceNow_(maxTimeout)
if nextfire is not None:
nextfire = soon.earlierDate_(nextfire)
if not runLoop.runMode_beforeDate_(mode, nextfire):
stopper.stop()
finally:
PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
RAISETHESE = (SystemExit, MemoryError, KeyboardInterrupt)
def runEventLoop(
argv=None,
unexpectedErrorAlert=None,
installInterrupt=None,
pdb=None,
main=NSApplicationMain,
):
"""Run the event loop, ask the user if we should continue if an
exception is caught. Use this function instead of NSApplicationMain().
"""
if argv is None:
argv = sys.argv
if pdb is None:
pdb = "USE_PDB" in os.environ
if pdb:
from PyObjCTools import Debugging
Debugging.installVerboseExceptionHandler()
# bring it to the front, starting from terminal
# often won't
activator = PyObjCAppHelperApplicationActivator.alloc().init()
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
activator, "activateNow:", NSApplicationDidFinishLaunchingNotification, None
)
else:
Debugging = None
if installInterrupt is None and pdb:
installInterrupt = True
if unexpectedErrorAlert is None:
if pdb:
unexpectedErrorAlert = unexpectedErrorAlertPdb
else:
unexpectedErrorAlert = unexpectedErrorAlertPanel
runLoop = NSRunLoop.currentRunLoop()
stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)
firstRun = NSApp() is None
try:
while stopper.shouldRun():
try:
if firstRun:
firstRun = False
if installInterrupt:
installMachInterrupt()
main(argv)
else:
NSApp().run()
except RAISETHESE:
traceback.print_exc()
break
except: # noqa: E722, B001
exctype, e, tb = sys.exc_info()
if isinstance(e, objc.error):
error_str = str(e)
NSLog("%@", error_str)
elif not unexpectedErrorAlert():
NSLog("%@", "An exception has occurred:")
traceback.print_exc()
sys.exit(0)
else:
NSLog("%@", "An exception has occurred:")
traceback.print_exc()
else:
break
finally:
if Debugging is not None:
Debugging.removeExceptionHandler()
PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)

View File

@@ -0,0 +1,238 @@
"""
Conversion.py -- Tools for converting between Python and Objective-C objects.
Conversion offers API to convert between Python and Objective-C instances of
various classes. Currently, the focus is on Python and Objective-C
collections.
"""
__all__ = [
"pythonCollectionFromPropertyList",
"propertyListFromPythonCollection",
"serializePropertyList",
"deserializePropertyList",
"toPythonDecimal",
"fromPythonDecimal",
]
import datetime
import decimal
import time
import Foundation
import objc
from objc._pythonify import OC_PythonFloat, OC_PythonLong
PYTHON_TYPES = (
str,
bool,
int,
float,
list,
tuple,
dict,
set,
datetime.date,
datetime.datetime,
bool,
type(None),
bytes,
)
DECIMAL_LOCALE = Foundation.NSDictionary.dictionaryWithObject_forKey_(
".", "NSDecimalSeparator"
)
def toPythonDecimal(aNSDecimalNumber):
"""
Convert a NSDecimalNumber to a Python decimal.Decimal
"""
return decimal.Decimal(aNSDecimalNumber.descriptionWithLocale_(DECIMAL_LOCALE))
def fromPythonDecimal(aPythonDecimal):
"""
Convert a Python decimal.Decimal to a NSDecimalNumber
"""
value_str = str(aPythonDecimal)
return Foundation.NSDecimalNumber.decimalNumberWithString_locale_(
value_str, DECIMAL_LOCALE
)
FORMATS = {
"xml": Foundation.NSPropertyListXMLFormat_v1_0,
"binary": Foundation.NSPropertyListBinaryFormat_v1_0,
"ascii": Foundation.NSPropertyListOpenStepFormat,
}
def serializePropertyList(aPropertyList, format="xml"): # noqa: A002
"""
Serialize a property list to an NSData object. Format is one of the
following strings:
xml (default):
NSPropertyListXMLFormat_v1_0, the XML representation
binary:
NSPropertyListBinaryFormat_v1_0, the efficient binary representation
ascii:
NSPropertyListOpenStepFormat, the old-style ASCII property list
It is expected that this property list is comprised of Objective-C
objects. In most cases Python data structures will work, but
decimal.Decimal and datetime.datetime objects are not transparently
bridged so it will fail in that case. If you expect to have these
objects in your property list, then use propertyListFromPythonCollection
before serializing it.
"""
try:
formatOption = FORMATS[format]
except KeyError:
raise ValueError(f"Invalid format: {format}")
(
data,
err,
) = Foundation.NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_( # noqa: B950
aPropertyList, formatOption, None
)
if err is not None:
raise ValueError(err)
return data
def deserializePropertyList(propertyListData):
"""
Deserialize a property list from a NSData, str or bytes object
Returns an Objective-C property list.
"""
if isinstance(propertyListData, str):
propertyListData = propertyListData.encode("utf-8")
(
plist,
fmt,
err,
) = Foundation.NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( # noqa: B950
propertyListData, Foundation.NSPropertyListMutableContainers, None, None
)
if err is not None:
raise ValueError(err)
return plist
def propertyListFromPythonCollection(aPyCollection, conversionHelper=None):
"""
Convert a Python collection (dict, list, tuple, string) into an
Objective-C collection.
If conversionHelper is defined, it must be a callable. It will be called
for any object encountered for which propertyListFromPythonCollection()
cannot automatically convert the object. The supplied helper function
should convert the object and return the converted form. If the conversion
helper cannot convert the type, it should raise an exception or return
None.
"""
if isinstance(aPyCollection, dict):
collection = Foundation.NSMutableDictionary.dictionary()
for aKey in aPyCollection:
if not isinstance(aKey, str):
raise TypeError("Property list keys must be strings")
convertedValue = propertyListFromPythonCollection(
aPyCollection[aKey], conversionHelper=conversionHelper
)
collection[aKey] = convertedValue
return collection
elif isinstance(aPyCollection, (list, tuple)):
collection = Foundation.NSMutableArray.array()
for aValue in aPyCollection:
convertedValue = propertyListFromPythonCollection(
aValue, conversionHelper=conversionHelper
)
collection.append(convertedValue)
return collection
elif isinstance(aPyCollection, (datetime.datetime, datetime.date)):
return Foundation.NSDate.dateWithTimeIntervalSince1970_(
time.mktime(aPyCollection.timetuple())
)
elif isinstance(aPyCollection, (set, frozenset)):
collection = Foundation.NSMutableSet.set()
for aValue in aPyCollection:
convertedValue = propertyListFromPythonCollection(
aValue, conversionHelper=conversionHelper
)
collection.add(convertedValue)
return collection
elif isinstance(aPyCollection, decimal.Decimal):
return fromPythonDecimal(aPyCollection)
elif isinstance(aPyCollection, PYTHON_TYPES):
# bridge will convert
return aPyCollection
elif conversionHelper is not None:
return conversionHelper(aPyCollection)
raise TypeError(
"Type '%s' encountered in Python collection; don't know how to convert."
% type(aPyCollection)
)
def pythonCollectionFromPropertyList(aCollection, conversionHelper=None):
"""
Converts a Foundation based property list into a Python
collection (all members will be instances or subclasses of standard Python
types)
Like propertyListFromPythonCollection(), conversionHelper is an optional
callable that will be invoked any time an encountered object cannot be
converted.
"""
if isinstance(aCollection, Foundation.NSDictionary):
pyCollection = {}
for k in aCollection:
convertedValue = pythonCollectionFromPropertyList(
aCollection[k], conversionHelper
)
pyCollection[pythonCollectionFromPropertyList(k)] = convertedValue
return pyCollection
elif isinstance(aCollection, Foundation.NSArray):
return [
pythonCollectionFromPropertyList(item, conversionHelper)
for item in aCollection
]
elif isinstance(aCollection, Foundation.NSSet):
value = set()
for item in aCollection:
item = pythonCollectionFromPropertyList(item, conversionHelper)
if isinstance(item, list):
item = tuple(item)
value.add(item)
return value
elif isinstance(aCollection, Foundation.NSData):
return bytes(aCollection)
elif isinstance(aCollection, Foundation.NSDate):
return datetime.datetime.fromtimestamp(aCollection.timeIntervalSince1970())
elif isinstance(aCollection, (objc.pyobjc_unicode, Foundation.NSString)):
return str(aCollection)
elif isinstance(aCollection, OC_PythonLong):
return int(aCollection)
elif isinstance(aCollection, OC_PythonFloat):
return float(aCollection)
elif isinstance(aCollection, Foundation.NSDecimalNumber):
return toPythonDecimal(aCollection)
elif aCollection is Foundation.NSNull.null():
return None
elif isinstance(aCollection, PYTHON_TYPES):
return aCollection
elif conversionHelper:
return conversionHelper(aCollection)
raise TypeError(
"Type '%s' encountered in ObjC collection; don't know how to convert."
% type(aCollection)
)

View File

@@ -0,0 +1,37 @@
"""
A number of useful categories on Foundation classes
"""
__all__ = ()
import objc
from Foundation import NSAffineTransform
class NSAffineTransform(objc.Category(NSAffineTransform)):
def rotateByDegrees_atPoint_(self, angle, point):
"""
Rotate the coordinatespace ``angle`` degrees around
``point``.
"""
self.rotateByDegrees_(angle)
tf = NSAffineTransform.transform()
tf.rotateByDegrees_(-angle)
oldPt = tf.transformPoint_(point)
oldPt.x -= point.x
oldPt.y -= point.y
self.translateXBy_yBy_(oldPt.x, oldPt.y)
def rotateByRadians_atPoint_(self, angle, point):
"""
Rotate the coordinatespace ``angle`` radians around
``point``.
"""
self.rotateByRadians_(angle)
tf = NSAffineTransform.transform()
tf.rotateByRadians_(-angle)
oldPt = tf.transformPoint_(point)
oldPt.x -= point.x
oldPt.y -= point.y
self.translateXBy_yBy_(oldPt.x, oldPt.y)

View File

@@ -0,0 +1,392 @@
"""
Support for Key-Value Coding in Python. This provides a simple functional
interface to Cocoa's Key-Value coding that also works for regular Python
objects.
Public API:
setKey(obj, key, value) -> None
setKeyPath (obj, keypath, value) -> None
getKey(obj, key) -> value
getKeyPath (obj, keypath) -> value
A keypath is a string containing a sequence of keys separated by dots. The
path is followed by repeated calls to 'getKey'. This can be used to easily
access nested attributes.
This API is mirroring the 'getattr' and 'setattr' APIs in Python, this makes
it more natural to work with Key-Value coding from Python. It also doesn't
require changes to existing Python classes to make use of Key-Value coding,
making it easier to build applications as a platform independent core with
a Cocoa GUI layer.
See the Cocoa documentation on the Apple developer website for more
information on Key-Value coding. The protocol is basically used to enable
weaker coupling between the view and model layers.
"""
import collections.abc
import types
__all__ = ("getKey", "setKey", "getKeyPath", "setKeyPath")
def keyCaps(s):
return s[:1].capitalize() + s[1:]
# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090
# Title: Binary floating point summation accurate to full precision
# Version no: 2.2
def msum(iterable):
"""
Full precision summation using multiple floats for intermediate values
"""
# sorted, non-overlapping partial sums
partials = []
for x in iterable:
i = 0
for y in partials:
if abs(x) < abs(y):
x, y = y, x
hi = x + y
lo = y - (hi - x)
if lo:
partials[i] = lo
i += 1
x = hi
partials[i:] = [x]
return sum(partials, 0.0)
class _ArrayOperators:
@staticmethod
def avg(obj, segments):
path = ".".join(segments)
lst = getKeyPath(obj, path)
count = len(lst)
if count == 0:
return 0.0
return msum(float(x) if x is not _null else 0.0 for x in lst) / count
@staticmethod
def count(obj, segments):
return len(obj)
@staticmethod
def distinctUnionOfArrays(obj, segments):
path = ".".join(segments)
rval = []
s = set()
r = []
for lst in obj:
for item in (getKeyPath(item, path) for item in lst):
try:
if item in s or item in r:
continue
rval.append(item)
s.add(item)
except TypeError:
if item in rval:
continue
rval.append(item)
r.append(item)
return rval
@staticmethod
def distinctUnionOfSets(obj, segments):
path = ".".join(segments)
rval = set()
for lst in obj:
for item in (getKeyPath(item, path) for item in lst):
rval.add(item)
return rval
@staticmethod
def distinctUnionOfObjects(obj, segments):
path = ".".join(segments)
rval = []
s = set()
r = []
for item in (getKeyPath(item, path) for item in obj):
try:
if item in s or item in r:
continue
rval.append(item)
s.add(item)
except TypeError:
if item in rval:
continue
rval.append(item)
r.append(item)
return rval
@staticmethod
def max(obj, segments): # noqa: A003
path = ".".join(segments)
return max(x for x in getKeyPath(obj, path) if x is not _null)
@staticmethod
def min(obj, segments): # noqa: A003
path = ".".join(segments)
return min(x for x in getKeyPath(obj, path) if x is not _null)
@staticmethod
def sum(obj, segments): # noqa: A003
path = ".".join(segments)
lst = getKeyPath(obj, path)
return msum(float(x) if x is not _null else 0.0 for x in lst)
@staticmethod
def unionOfArrays(obj, segments):
path = ".".join(segments)
rval = []
for lst in obj:
rval.extend(getKeyPath(item, path) for item in lst)
return rval
@staticmethod
def unionOfObjects(obj, segments):
path = ".".join(segments)
return [getKeyPath(item, path) for item in obj]
def getKey(obj, key):
"""
Get the attribute referenced by 'key'. The key is used
to build the name of an attribute, or attribute accessor method.
The following attributes and accessors are tried (in this order):
- Accessor 'getKey'
- Accesoor 'get_key'
- Accessor or attribute 'key'
- Accessor or attribute 'isKey'
- Attribute '_key'
If none of these exist, raise KeyError
"""
if obj is None:
return None
if isinstance(obj, (objc.objc_object, objc.objc_class)):
return obj.valueForKey_(key)
# check for dict-like objects
getitem = getattr(obj, "__getitem__", None)
if getitem is not None:
try:
return getitem(key)
except (KeyError, IndexError, TypeError):
pass
# check for array-like objects
if isinstance(
obj, (collections.abc.Sequence, collections.abc.Set)
) and not isinstance(obj, (str, collections.abc.Mapping)):
def maybe_get(obj, key):
try:
return getKey(obj, key)
except KeyError:
return _null
return [maybe_get(obj, key) for obj in iter(obj)]
try:
m = getattr(obj, "get" + keyCaps(key))
except AttributeError:
pass
else:
return m()
try:
m = getattr(obj, "get_" + key)
except AttributeError:
pass
else:
return m()
for keyName in (key, "is" + keyCaps(key)):
try:
m = getattr(obj, keyName)
except AttributeError:
continue
if isinstance(m, types.MethodType) and m.__self__ is obj:
return m()
elif isinstance(m, types.BuiltinMethodType):
# Can't access the bound self of methods of builtin classes :-(
return m()
elif isinstance(m, objc.selector) and m.self is obj:
return m()
else:
return m
try:
return getattr(obj, "_" + key)
except AttributeError:
raise KeyError(f"Key {key} does not exist")
def setKey(obj, key, value):
"""
Set the attribute referenced by 'key' to 'value'. The key is used
to build the name of an attribute, or attribute accessor method.
The following attributes and accessors are tried (in this order):
- Mapping access (that is __setitem__ for collection.Mapping instances)
- Accessor 'setKey_'
- Accessor 'setKey'
- Accessor 'set_key'
- Attribute '_key'
- Attribute 'key'
Raises KeyError if the key doesn't exist.
"""
if obj is None:
return
if isinstance(obj, (objc.objc_object, objc.objc_class)):
obj.setValue_forKey_(value, key)
return
if isinstance(obj, collections.abc.Mapping):
obj[key] = value
return
aBase = "set" + keyCaps(key)
for accessor in (aBase + "_", aBase, "set_" + key):
m = getattr(obj, accessor, None)
if m is None:
continue
try:
m(value)
return
except TypeError:
pass
try:
m = getattr(obj, key)
except AttributeError:
pass
else:
if isinstance(m, types.MethodType) and m.__self__ is obj:
# This looks like a getter method, don't call setattr
pass
else:
try:
setattr(obj, key, value)
return
except AttributeError:
raise KeyError(f"Key {key} does not exist")
try:
getattr(obj, "_" + key)
except AttributeError:
pass
else:
setattr(obj, "_" + key, value)
return
try:
setattr(obj, key, value)
except AttributeError:
raise KeyError(f"Key {key} does not exist")
def getKeyPath(obj, keypath):
"""
Get the value for the keypath. Keypath is a string containing a
path of keys, path elements are separated by dots.
"""
if not keypath:
raise KeyError
if obj is None:
return None
if isinstance(obj, (objc.objc_object, objc.objc_class)):
return obj.valueForKeyPath_(keypath)
elements = keypath.split(".")
cur = obj
elemiter = iter(elements)
for e in elemiter:
if e[:1] == "@":
try:
oper = getattr(_ArrayOperators, e[1:])
except AttributeError:
raise KeyError(f"Array operator {e} not implemented")
return oper(cur, elemiter)
cur = getKey(cur, e)
return cur
def setKeyPath(obj, keypath, value):
"""
Set the value at 'keypath'. The keypath is a string containing a
path of keys, separated by dots.
"""
if obj is None:
return
if isinstance(obj, (objc.objc_object, objc.objc_class)):
return obj.setValue_forKeyPath_(value, keypath)
elements = keypath.split(".")
cur = obj
for e in elements[:-1]:
cur = getKey(cur, e)
return setKey(cur, elements[-1], value)
class kvc:
def __init__(self, obj):
self.__pyobjc_object__ = obj
def __getattr__(self, attr):
return getKey(self.__pyobjc_object__, attr)
def __repr__(self):
return repr(self.__pyobjc_object__)
def __setattr__(self, attr, value):
if not attr.startswith("_"):
setKey(self.__pyobjc_object__, attr, value)
else:
object.__setattr__(self, attr, value)
def __getitem__(self, item):
if not isinstance(item, str):
raise TypeError("Keys must be strings")
return getKeyPath(self.__pyobjc_object__, item)
def __setitem__(self, item, value):
if not isinstance(item, str):
raise TypeError("Keys must be strings")
setKeyPath(self.__pyobjc_object__, item, value)
# The import of 'objc' is at the end of the module
# to avoid problems when importing this module before
# importing objc due to the objc package importing bits
# of this module.
import objc # noqa: E402
_null = objc.lookUpClass("NSNull").null()

View File

@@ -0,0 +1,42 @@
"""
Substitute for the signal module when using a CFRunLoop.
This module is generally only used to support:
PyObjCTools.AppHelper.installMachInterrupt()
A mach port is opened and registered to the CFRunLoop.
When a signal occurs the signal number is sent in a mach
message to the CFRunLoop. The handler then causes Python
code to get executed.
In other words, Python's signal handling code does not wake
reliably when not running Python code, but this does.
Note that signals will only be processed while a Cocoa
run loop is running in the default mode.
"""
from objc import _machsignals
__all__ = ["getsignal", "signal"]
def getsignal(signum):
"""
Return the signal handler for signal ``signum``. Returns ``None`` when
there is no signal handler for the signal.
"""
return _machsignals._signalmapping.get(signum)
def signal(signum, handler):
"""
Install a new signal handler for ``signum``. Returns the old signal
handler (``None`` when there is no previous handler.
The handler should have one argument: the signal number
"""
rval = getsignal(signum)
_machsignals._signalmapping[signum] = handler
_machsignals.handle_signal(signum)
return rval

View File

@@ -0,0 +1,91 @@
"""Signals.py -- dump a python stacktrace if something bad happens.
DO NOT USE THIS MODULE IN PRODUCTION CODE
This module has two functions in its public API:
- dumpStackOnFatalSignal()
This function will install signal handlers that print a stacktrace and
then reraise the signal.
- resetFatalSignals()
Restores the signal handlers to the state they had before the call to
dumpStackOnFatalSignal.
This module is not designed to provide fine grained control over signal
handling. Nor is it intended to be terribly robust. It may give useful
information when your program gets unexpected signals, but it might just
as easily cause a crash when such a signal gets in.
DO NOT USE THIS MODULE IN PRODUCTION CODE
"""
import os
import signal
import traceback
import warnings
import sys
__all__ = ["dumpStackOnFatalSignal", "resetFatalSignals"]
warnings.warn(
"PyObjCTools.Signals is deprecated and will be removed in PyObjC 9",
DeprecationWarning,
stacklevel=1,
)
originalHandlers = None
def dumpHandler(signum, frame):
"""
the signal handler used in this module: print a stacktrace and
then re-raise the signal
"""
resetFatalSignals()
print("*** Handling fatal signal '%d'." % signum, file=sys.stderr)
traceback.print_stack(frame)
print("*** Restored handlers and resignaling.", file=sys.stderr)
os.kill(os.getpid(), signum)
def installHandler(sig):
"""
Install our signal handler for a signal. The original handler
is saved in 'originalHandlers'.
"""
originalHandlers[sig] = signal.signal(sig, dumpHandler)
def dumpStackOnFatalSignal():
"""
Install signal handlers that might print a useful stack trace when
this process receives a fatal signal.
NOTE: See module docstring
"""
global originalHandlers
if not originalHandlers:
originalHandlers = {}
installHandler(signal.SIGQUIT)
installHandler(signal.SIGILL)
installHandler(signal.SIGTRAP)
installHandler(signal.SIGABRT)
installHandler(signal.SIGEMT)
installHandler(signal.SIGFPE)
installHandler(signal.SIGBUS)
installHandler(signal.SIGSEGV)
installHandler(signal.SIGSYS)
def resetFatalSignals():
"""
Restore the original signal handlers
"""
global originalHandlers
if originalHandlers:
for sig in originalHandlers:
signal.signal(sig, originalHandlers[sig])
originalHandlers = None

View File

@@ -0,0 +1,80 @@
"""
Python mapping for the CoreGraphics framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import CoreFoundation
import objc
import os
from . import (
_metadata,
_callbacks,
_doubleindirect,
_sortandmap,
_coregraphics,
_contextmanager,
)
from ._inlines import _inline_list_
if os.path.exists("/System/Library/Frameworks/CoreGraphics.framework"):
frameworkPath = "/System/Library/Frameworks/CoreGraphics.framework"
frameworkIdentifier = "com.apple.CoreGraphics"
else:
frameworkPath = "/System/Library/Frameworks/ApplicationServices.framework"
frameworkIdentifier = "com.apple.ApplicationServices"
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.CoreGraphics",
frameworkIdentifier=frameworkIdentifier,
frameworkPath=objc.pathForFramework(frameworkPath),
globals_dict=globals(),
inline_list=_inline_list_,
parents=(
_callbacks,
_doubleindirect,
_sortandmap,
_coregraphics,
_contextmanager,
CoreFoundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.CoreGraphics._metadata"]
# XXX: To be verified
from . import CGPathElement
_sortandmap.setCGPathElement(CGPathElement)
del _sortandmap.setCGPathElement
# XXX: Move these to metadata!
global CGFLOAT_MIN, CGFLOAT_MAX
CGFLOAT_MIN = 1.175_494_350_822_287_5e-38
CGFLOAT_MAX = 3.402_823_466_385_288_6e38
global kCGAnyInputEventType
kCGAnyInputEventType = 0xFFFFFFFF
global CGEventMaskBit
def CGEventMaskBit(eventType):
return 1 << eventType
global kCGColorSpaceUserGray, kCGColorSpaceUserRGB, kCGColorSpaceUserCMYK
kCGColorSpaceUserGray = "kCGColorSpaceUserGray"
kCGColorSpaceUserRGB = "kCGColorSpaceUserRGB"
kCGColorSpaceUserCMYK = "kCGColorSpaceUserCMYK"
globals().pop("_setup")()

View File

@@ -0,0 +1,105 @@
"""
This module defines a number of context managers. These are meant to be used
in the context of the with statement (introduced in Python 2.5).
"""
__all__ = ("CGSavedGState", "CGTransparencyLayer", "CGContextPage")
import Quartz
class CGSavedGState:
"""
Context manager for saving and restoring the graphics state.
Usage::
with CGSavedGState(context):
statement
This is equivalent to:
CGContextSaveGState(context)
try:
statement
finally:
CGContextRestoreGState(context)
"""
def __init__(self, context):
self.context = context
def __enter__(self):
Quartz.CGContextSaveGState(self.context)
return self
def __exit__(self, exc_type, exc_value, exc_tp):
Quartz.CGContextRestoreGState(self.context)
return False
class CGTransparencyLayer:
"""
Context manager for working in a transparancylayer.
Usage::
with CGTransparencyLayer(context, info [, rect]):
statement
This is equivalent to:
CGContextBeginTransparencyLayer(context, info)
try:
statement
finally:
CGContextEndTransparencyLayer(context)
"""
def __init__(self, context, info, rect=None):
self.context = context
self.info = info
self.rect = rect
def __enter__(self):
if self.rect is None:
result = Quartz.CGContextBeginTransparencyLayer(self.context, self.info)
else:
result = Quartz.CGContextBeginTransparencyLayerWithRect(
self.context, self.rect, self.info
)
return result
def __exit__(self, exc_type, exc_value, exc_tp):
Quartz.CGContextEndTransparencyLayer(self.context)
return False
class CGContextPage:
"""
Context manager for saving and restoring the graphics state.
Usage::
with CGContextPage(context) as mediaRect:
statement
This is equivalent to:
mediaRect = CGContextBeginPage(context, None)
try:
statement
finally:
CGContextEndPage(context)
"""
def __init__(self, context, mediaBox=None):
self.context = context
self.mediaBox = mediaBox
def __enter__(self):
mediaRect = Quartz.CGContextBeginPage(self.context, self.mediaBox)
return mediaRect
def __exit__(self, exc_type, exc_value, exc_tp):
Quartz.CGContextEndPage(self.context)
return False

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
"""
Python mapping for the CoreVideo framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import CoreFoundation
import objc
from . import _metadata, _CVPixelBuffer
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.CoreVideo",
frameworkIdentifier="com.apple.CoreVideo",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/CoreVideo.framework"
),
globals_dict=globals(),
inline_list=None,
parents=(
_CVPixelBuffer,
CoreFoundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.CoreVideo._metadata"]
globals().pop("_setup")()

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,393 @@
<?xml version='1.0'?>
<!DOCTYPE signatures SYSTEM "file://localhost/System/Library/DTDs/BridgeSupport.dtd">
<signatures version='1.0'>
<cftype gettypeid_func='CGImageDestinationGetTypeID' name='CGImageDestinationRef' type='^{CGImageDestination=}' type64='^{CGImageDestination=}' />
<cftype gettypeid_func='CGImageSourceGetTypeID' name='CGImageSourceRef' type='^{CGImageSource=}' type64='^{CGImageSource=}' />
<constant name='kCGImageDestinationBackgroundColor' type='^{__CFString=}' />
<constant name='kCGImageDestinationLossyCompressionQuality' type='^{__CFString=}' />
<constant name='kCGImageProperty8BIMDictionary' type='^{__CFString=}' />
<constant name='kCGImageProperty8BIMLayerNames' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFCameraSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFContinuousDrive' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFDescription' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFFirmware' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFFlashExposureComp' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFFocusMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFImageFileName' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFImageName' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFImageSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFLensMaxMM' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFLensMinMM' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFMeasuredEV' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFMeteringMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFOwnerName' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFRecordID' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFReleaseMethod' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFReleaseTiming' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFSelfTimingTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFShootingMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyCIFFWhiteBalanceIndex' type='^{__CFString=}' />
<constant name='kCGImagePropertyColorModel' type='^{__CFString=}' />
<constant name='kCGImagePropertyColorModelCMYK' type='^{__CFString=}' />
<constant name='kCGImagePropertyColorModelGray' type='^{__CFString=}' />
<constant name='kCGImagePropertyColorModelLab' type='^{__CFString=}' />
<constant name='kCGImagePropertyColorModelRGB' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGBackwardVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGCameraSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGLensInfo' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGLocalizedCameraModel' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGUniqueCameraModel' type='^{__CFString=}' />
<constant name='kCGImagePropertyDNGVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyDPIHeight' type='^{__CFString=}' />
<constant name='kCGImagePropertyDPIWidth' type='^{__CFString=}' />
<constant name='kCGImagePropertyDepth' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifApertureValue' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifBrightnessValue' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifCFAPattern' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifColorSpace' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifComponentsConfiguration' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifCompressedBitsPerPixel' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifContrast' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifCustomRendered' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifDateTimeDigitized' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifDateTimeOriginal' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifDeviceSettingDescription' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifDigitalZoomRatio' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifExposureBiasValue' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifExposureIndex' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifExposureMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifExposureProgram' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifExposureTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFileSource' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFlash' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFlashEnergy' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFlashPixVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFocalLenIn35mmFilm' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFocalLength' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFocalPlaneResolutionUnit' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFocalPlaneXResolution' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifFocalPlaneYResolution' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifGainControl' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifGamma' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifISOSpeedRatings' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifImageUniqueID' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifLightSource' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifMakerNote' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifMaxApertureValue' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifMeteringMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifOECF' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifPixelXDimension' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifPixelYDimension' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifRelatedSoundFile' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSaturation' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSceneCaptureType' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSceneType' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSensingMethod' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSharpness' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifShutterSpeedValue' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSpatialFrequencyResponse' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSpectralSensitivity' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubjectArea' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubjectDistRange' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubjectDistance' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubjectLocation' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubsecTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubsecTimeDigitized' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifSubsecTimeOrginal' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifUserComment' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyExifWhiteBalance' type='^{__CFString=}' />
<constant name='kCGImagePropertyFileSize' type='^{__CFString=}' />
<constant name='kCGImagePropertyGIFDelayTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyGIFDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyGIFHasGlobalColorMap' type='^{__CFString=}' />
<constant name='kCGImagePropertyGIFImageColorMap' type='^{__CFString=}' />
<constant name='kCGImagePropertyGIFLoopCount' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSAltitude' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSAltitudeRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSAreaInformation' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDOP' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDateStamp' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestBearing' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestBearingRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestDistance' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestDistanceRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestLatitude' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestLatitudeRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestLongitude' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDestLongitudeRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSDifferental' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSImgDirection' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSImgDirectionRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSLatitude' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSLatitudeRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSLongitude' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSLongitudeRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSMapDatum' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSMeasureMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSProcessingMethod' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSSatellites' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSSpeed' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSSpeedRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSStatus' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSTimeStamp' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSTrack' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSTrackRef' type='^{__CFString=}' />
<constant name='kCGImagePropertyGPSVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyHasAlpha' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCActionAdvised' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCByline' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCBylineTitle' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCaptionAbstract' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCategory' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCity' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCContact' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCContentLocationCode' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCContentLocationName' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCopyrightNotice' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCountryPrimaryLocationCode' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCountryPrimaryLocationName' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCCredit' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCDateCreated' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCDigitalCreationDate' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCDigitalCreationTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCEditStatus' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCEditorialUpdate' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCExpirationDate' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCExpirationTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCFixtureIdentifier' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCHeadline' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCImageOrientation' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCImageType' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCKeywords' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCLanguageIdentifier' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCObjectAttributeReference' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCObjectCycle' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCObjectName' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCObjectTypeReference' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCOriginalTransmissionReference' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCOriginatingProgram' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCProgramVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCProvinceState' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCReferenceDate' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCReferenceNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCReferenceService' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCReleaseDate' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCReleaseTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCSource' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCSpecialInstructions' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCStarRating' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCSubLocation' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCSubjectReference' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCSupplementalCategory' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCTimeCreated' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCUrgency' type='^{__CFString=}' />
<constant name='kCGImagePropertyIPTCWriterEditor' type='^{__CFString=}' />
<constant name='kCGImagePropertyIsFloat' type='^{__CFString=}' />
<constant name='kCGImagePropertyIsIndexed' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFDensityUnit' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFIsProgressive' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFVersion' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFXDensity' type='^{__CFString=}' />
<constant name='kCGImagePropertyJFIFYDensity' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonCameraSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonContinuousDrive' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonFlashExposureComp' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonImageSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonLensModel' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerCanonOwnerName' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonCameraSerialNumber' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonColorMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonDigitalZoom' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonFlashExposureComp' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonFlashSetting' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonFocusDistance' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonFocusMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonISOSelection' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonISOSetting' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonImageAdjustment' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonLensAdapter' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonQuality' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonSharpenMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonShootingMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyMakerNikonWhiteBalanceMode' type='^{__CFString=}' />
<constant name='kCGImagePropertyOrientation' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGChromaticities' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGGamma' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGInterlaceType' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGXPixelsPerMeter' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGYPixelsPerMeter' type='^{__CFString=}' />
<constant name='kCGImagePropertyPNGsRGBIntent' type='^{__CFString=}' />
<constant name='kCGImagePropertyPixelHeight' type='^{__CFString=}' />
<constant name='kCGImagePropertyPixelWidth' type='^{__CFString=}' />
<constant name='kCGImagePropertyProfileName' type='^{__CFString=}' />
<constant name='kCGImagePropertyRawDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFArtist' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFCompression' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFCopyright' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFDateTime' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFDictionary' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFDocumentName' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFHostComputer' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFImageDescription' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFMake' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFModel' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFOrientation' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFPhotometricInterpretation' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFPrimaryChromaticities' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFResolutionUnit' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFSoftware' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFTransferFunction' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFWhitePoint' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFXResolution' type='^{__CFString=}' />
<constant name='kCGImagePropertyTIFFYResolution' type='^{__CFString=}' />
<constant name='kCGImageSourceCreateThumbnailFromImageAlways' type='^{__CFString=}' />
<constant name='kCGImageSourceCreateThumbnailFromImageIfAbsent' type='^{__CFString=}' />
<constant name='kCGImageSourceCreateThumbnailWithTransform' type='^{__CFString=}' />
<constant name='kCGImageSourceShouldAllowFloat' type='^{__CFString=}' />
<constant name='kCGImageSourceShouldCache' type='^{__CFString=}' />
<constant name='kCGImageSourceThumbnailMaxPixelSize' type='^{__CFString=}' />
<constant name='kCGImageSourceTypeIdentifierHint' type='^{__CFString=}' />
<enum name='kCGImageStatusComplete' value='0' />
<enum name='kCGImageStatusIncomplete' value='-1' />
<enum name='kCGImageStatusInvalidData' value='-4' />
<enum name='kCGImageStatusReadingHeader' value='-2' />
<enum name='kCGImageStatusUnexpectedEOF' value='-5' />
<enum name='kCGImageStatusUnknownType' value='-3' />
<function name='CGImageDestinationAddImage'>
<retval type='v' />
<arg type='^{CGImageDestination=}' />
<arg type='^{CGImage=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageDestinationAddImageFromSource'>
<retval type='v' />
<arg type='^{CGImageDestination=}' />
<arg type='^{CGImageSource=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageDestinationCopyTypeIdentifiers'>
<retval already_retained='true' type='^{__CFArray=}' />
</function>
<function name='CGImageDestinationCreateWithData'>
<retval already_retained='true' type='^{CGImageDestination=}' />
<arg type='^{__CFData=}' />
<arg type='^{__CFString=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageDestinationCreateWithDataConsumer'>
<retval already_retained='true' type='^{CGImageDestination=}' />
<arg type='^{CGDataConsumer=}' />
<arg type='^{__CFString=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageDestinationCreateWithURL'>
<retval already_retained='true' type='^{CGImageDestination=}' />
<arg type='^{__CFURL=}' />
<arg type='^{__CFString=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageDestinationFinalize'>
<retval type='B' />
<arg type='^{CGImageDestination=}' />
</function>
<function name='CGImageDestinationGetTypeID'>
<retval type='L' type64='Q' />
</function>
<function name='CGImageDestinationSetProperties'>
<retval type='v' />
<arg type='^{CGImageDestination=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCopyProperties'>
<retval already_retained='true' type='^{__CFDictionary=}' />
<arg type='^{CGImageSource=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCopyPropertiesAtIndex'>
<retval already_retained='true' type='^{__CFDictionary=}' />
<arg type='^{CGImageSource=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCopyTypeIdentifiers'>
<retval already_retained='true' type='^{__CFArray=}' />
</function>
<function name='CGImageSourceCreateImageAtIndex'>
<retval already_retained='true' type='^{CGImage=}' />
<arg type='^{CGImageSource=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCreateIncremental'>
<retval already_retained='true' type='^{CGImageSource=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCreateThumbnailAtIndex'>
<retval already_retained='true' type='^{CGImage=}' />
<arg type='^{CGImageSource=}' />
<arg type='L' type64='L' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCreateWithData'>
<retval already_retained='true' type='^{CGImageSource=}' />
<arg type='^{__CFData=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCreateWithDataProvider'>
<retval already_retained='true' type='^{CGImageSource=}' />
<arg type='^{CGDataProvider=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceCreateWithURL'>
<retval already_retained='true' type='^{CGImageSource=}' />
<arg type='^{__CFURL=}' />
<arg type='^{__CFDictionary=}' />
</function>
<function name='CGImageSourceGetCount'>
<retval type='L' type64='Q' />
<arg type='^{CGImageSource=}' />
</function>
<function name='CGImageSourceGetStatus'>
<retval type='i' />
<arg type='^{CGImageSource=}' />
</function>
<function name='CGImageSourceGetStatusAtIndex'>
<retval type='i' />
<arg type='^{CGImageSource=}' />
<arg type='L' type64='L' />
</function>
<function name='CGImageSourceGetType'>
<retval type='^{__CFString=}' />
<arg type='^{CGImageSource=}' />
</function>
<function name='CGImageSourceGetTypeID'>
<retval type='L' type64='Q' />
</function>
<function name='CGImageSourceUpdateData'>
<retval type='v' />
<arg type='^{CGImageSource=}' />
<arg type='^{__CFData=}' />
<arg type='B' />
</function>
<function name='CGImageSourceUpdateDataProvider'>
<retval type='v' />
<arg type='^{CGImageSource=}' />
<arg type='^{CGDataProvider=}' />
<arg type='B' />
</function>
</signatures>

View File

@@ -0,0 +1,34 @@
"""
Python mapping for the ImageIO framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
from Quartz import CoreGraphics
import objc
from . import _metadata
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.ImageIO",
frameworkIdentifier="com.apple.ApplicationServices",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/ApplicationServices.framework"
),
globals_dict=globals(),
inline_list=None,
parents=(CoreGraphics,),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.ImageIO._metadata"]
globals().pop("_setup")()

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,49 @@
"""
Python mapping for the ImageKit framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import AppKit
import objc
from . import _metadata, _imagekit
if objc.macos_available(14, 0):
identifier = "com.apple.quartzframework"
elif objc.macos_available(13, 0):
identifier = "com.apple.Quartz"
else:
identifier = "com.apple.quartzframework"
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.ImageKit",
frameworkIdentifier=identifier,
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/Quartz.framework"
),
globals_dict=globals(),
inline_list=None,
parents=(
_imagekit,
AppKit,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.ImageKit._metadata"]
objc.addConvenienceForBasicMapping("IKImageBrowserGridGroup", False)
objc.addConvenienceForBasicMapping("IKImageCell", False)
objc.addConvenienceForBasicMapping("IKImageState", False)
objc.addConvenienceForBasicSequence("IKLinkedList", True)
globals().pop("_setup")()

View File

@@ -0,0 +1,607 @@
# This file is generated by objective.metadata
#
# Last update: Wed Oct 15 17:16:10 2025
#
# flake8: noqa
import objc, sys
from typing import NewType
if sys.maxsize > 2**32:
def sel32or64(a, b):
return b
else:
def sel32or64(a, b):
return a
if objc.arch == "arm64":
def selAorI(a, b):
return a
else:
def selAorI(a, b):
return b
misc = {}
constants = """$IKFilterBrowserDefaultInputImage$IKFilterBrowserExcludeCategories$IKFilterBrowserExcludeFilters$IKFilterBrowserFilterDoubleClickNotification$IKFilterBrowserFilterSelectedNotification$IKFilterBrowserShowCategories$IKFilterBrowserShowPreview$IKFilterBrowserWillPreviewFilterNotification$IKImageBrowserBackgroundColorKey$IKImageBrowserCGImageRepresentationType$IKImageBrowserCGImageSourceRepresentationType$IKImageBrowserCellBackgroundLayer$IKImageBrowserCellForegroundLayer$IKImageBrowserCellLayerTypeBackground$IKImageBrowserCellLayerTypeForeground$IKImageBrowserCellLayerTypePlaceHolder$IKImageBrowserCellLayerTypeSelection$IKImageBrowserCellPlaceHolderLayer$IKImageBrowserCellSelectionLayer$IKImageBrowserCellsHighlightedTitleAttributesKey$IKImageBrowserCellsOutlineColorKey$IKImageBrowserCellsSubtitleAttributesKey$IKImageBrowserCellsTitleAttributesKey$IKImageBrowserGroupBackgroundColorKey$IKImageBrowserGroupFooterLayer$IKImageBrowserGroupHeaderLayer$IKImageBrowserGroupRangeKey$IKImageBrowserGroupStyleKey$IKImageBrowserGroupTitleKey$IKImageBrowserIconRefPathRepresentationType$IKImageBrowserIconRefRepresentationType$IKImageBrowserNSBitmapImageRepresentationType$IKImageBrowserNSDataRepresentationType$IKImageBrowserNSImageRepresentationType$IKImageBrowserNSURLRepresentationType$IKImageBrowserPDFPageRepresentationType$IKImageBrowserPathRepresentationType$IKImageBrowserQCCompositionPathRepresentationType$IKImageBrowserQCCompositionRepresentationType$IKImageBrowserQTMoviePathRepresentationType$IKImageBrowserQTMovieRepresentationType$IKImageBrowserQuickLookPathRepresentationType$IKImageBrowserSelectionColorKey$IKOverlayTypeBackground$IKOverlayTypeImage$IKPictureTakerAllowsEditingKey$IKPictureTakerAllowsFileChoosingKey$IKPictureTakerAllowsVideoCaptureKey$IKPictureTakerCropAreaSizeKey$IKPictureTakerImageTransformsKey$IKPictureTakerInformationalTextKey$IKPictureTakerOutputImageMaxSizeKey$IKPictureTakerRemainOpenAfterValidateKey$IKPictureTakerShowAddressBookPicture$IKPictureTakerShowAddressBookPictureKey$IKPictureTakerShowEffectsKey$IKPictureTakerShowEmptyPicture$IKPictureTakerShowEmptyPictureKey$IKPictureTakerShowRecentPictureKey$IKPictureTakerUpdateRecentPictureKey$IKSlideshowAudioFile$IKSlideshowModeImages$IKSlideshowModeOther$IKSlideshowModePDF$IKSlideshowPDFDisplayBox$IKSlideshowPDFDisplayMode$IKSlideshowPDFDisplaysAsBook$IKSlideshowScreen$IKSlideshowStartIndex$IKSlideshowStartPaused$IKSlideshowWrapAround$IKToolModeAnnotate$IKToolModeCrop$IKToolModeMove$IKToolModeNone$IKToolModeRotate$IKToolModeSelect$IKToolModeSelectEllipse$IKToolModeSelectLasso$IKToolModeSelectRect$IKUIFlavorAllowFallback$IKUISizeFlavor$IKUISizeMini$IKUISizeRegular$IKUISizeSmall$IKUImaxSize$IK_ApertureBundleIdentifier$IK_MailBundleIdentifier$IK_PhotosBundleIdentifier$IK_iPhotoBundleIdentifier$"""
enums = """$IKCameraDeviceViewDisplayModeIcon@1$IKCameraDeviceViewDisplayModeNone@-1$IKCameraDeviceViewDisplayModeTable@0$IKCameraDeviceViewTransferModeFileBased@0$IKCameraDeviceViewTransferModeMemoryBased@1$IKCellsStyleNone@0$IKCellsStyleOutlined@2$IKCellsStyleShadowed@1$IKCellsStyleSubtitled@8$IKCellsStyleTitled@4$IKDeviceBrowserViewDisplayModeIcon@2$IKDeviceBrowserViewDisplayModeOutline@1$IKDeviceBrowserViewDisplayModeTable@0$IKGroupBezelStyle@0$IKGroupDisclosureStyle@1$IKImageBrowserDropBefore@1$IKImageBrowserDropOn@0$IKImageStateInvalid@1$IKImageStateNoImage@0$IKImageStateReady@2$IKScannerDeviceViewDisplayModeAdvanced@1$IKScannerDeviceViewDisplayModeNone@-1$IKScannerDeviceViewDisplayModeSimple@0$IKScannerDeviceViewTransferModeFileBased@0$IKScannerDeviceViewTransferModeMemoryBased@1$"""
misc.update(
{
"IKCameraDeviceViewDisplayMode": NewType("IKCameraDeviceViewDisplayMode", int),
"IKCameraDeviceViewTransferMode": NewType(
"IKCameraDeviceViewTransferMode", int
),
"IKImageBrowserCellState": NewType("IKImageBrowserCellState", int),
"IKScannerDeviceViewDisplayMode": NewType(
"IKScannerDeviceViewDisplayMode", int
),
"IKScannerDeviceViewTransferMode": NewType(
"IKScannerDeviceViewTransferMode", int
),
"IKImageBrowserDropOperation": NewType("IKImageBrowserDropOperation", int),
"IKDeviceBrowserViewDisplayMode": NewType(
"IKDeviceBrowserViewDisplayMode", int
),
}
)
misc.update({})
misc.update({})
aliases = {
"IKImagePickerShowEffectsKey": "IKPictureTakerShowEffectsKey",
"IKImagePickerOutputImageMaxSizeKey": "IKPictureTakerOutputImageMaxSizeKey",
"IKImagePickerImageTransformsKey": "IKPictureTakerImageTransformsKey",
"IKImagePickerAllowsFileChoosingKey": "IKPictureTakerAllowsFileChoosingKey",
"IK_API_DEPRECATED": "API_DEPRECATED",
"IKImagePickerAllowsEditingKey": "IKPictureTakerAllowsEditingKey",
"IKImagePickerInformationalTextKey": "IKPictureTakerInformationalTextKey",
"IKImagePickerCropAreaSizeKey": "IKPictureTakerCropAreaSizeKey",
"IKImagePickerAllowsVideoCaptureKey": "IKPictureTakerAllowsVideoCaptureKey",
"IKImagePickerUpdateRecentPictureKey": "IKPictureTakerUpdateRecentPictureKey",
"IKImagePickerShowRecentPictureKey": "IKPictureTakerShowRecentPictureKey",
}
r = objc.registerMetaDataForSelector
objc._updatingMetadata(True)
try:
r(b"IKCameraDeviceView", b"canDeleteSelectedItems", {"retval": {"type": b"Z"}})
r(b"IKCameraDeviceView", b"canDownloadSelectedItems", {"retval": {"type": b"Z"}})
r(b"IKCameraDeviceView", b"canRotateSelectedItemsLeft", {"retval": {"type": b"Z"}})
r(b"IKCameraDeviceView", b"canRotateSelectedItemsRight", {"retval": {"type": b"Z"}})
r(
b"IKCameraDeviceView",
b"displaysDownloadsDirectoryControl",
{"retval": {"type": b"Z"}},
)
r(
b"IKCameraDeviceView",
b"displaysPostProcessApplicationControl",
{"retval": {"type": b"Z"}},
)
r(b"IKCameraDeviceView", b"hasDisplayModeIcon", {"retval": {"type": b"Z"}})
r(b"IKCameraDeviceView", b"hasDisplayModeTable", {"retval": {"type": b"Z"}})
r(
b"IKCameraDeviceView",
b"selectIndexes:byExtendingSelection:",
{"arguments": {3: {"type": b"Z"}}},
)
r(
b"IKCameraDeviceView",
b"setDisplaysDownloadsDirectoryControl:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKCameraDeviceView",
b"setDisplaysPostProcessApplicationControl:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKCameraDeviceView",
b"setHasDisplayModeIcon:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKCameraDeviceView",
b"setHasDisplayModeTable:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKCameraDeviceView",
b"setShowStatusInfoAsWindowSubtitle:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"IKDeviceBrowserView", b"displaysLocalCameras", {"retval": {"type": b"Z"}})
r(b"IKDeviceBrowserView", b"displaysLocalScanners", {"retval": {"type": b"Z"}})
r(b"IKDeviceBrowserView", b"displaysNetworkCameras", {"retval": {"type": b"Z"}})
r(b"IKDeviceBrowserView", b"displaysNetworkScanners", {"retval": {"type": b"Z"}})
r(
b"IKDeviceBrowserView",
b"setDisplaysLocalCameras:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKDeviceBrowserView",
b"setDisplaysLocalScanners:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKDeviceBrowserView",
b"setDisplaysNetworkCameras:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKDeviceBrowserView",
b"setDisplaysNetworkScanners:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKFilterBrowserPanel",
b"beginSheetWithOptions:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
{"arguments": {5: {"sel_of_type": b"v@:@q^v"}}},
)
r(
b"IKFilterBrowserPanel",
b"beginWithOptions:modelessDelegate:didEndSelector:contextInfo:",
{"arguments": {4: {"sel_of_type": b"v@:@q^v"}}},
)
r(b"IKFilterBrowserView", b"setPreviewState:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageBrowserCell", b"isSelected", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"allowsDroppingOnItems", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"allowsEmptySelection", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"allowsMultipleSelection", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"allowsReordering", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"animates", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"canControlQuickLookPanel", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"constrainsToOriginalSize", {"retval": {"type": b"Z"}})
r(b"IKImageBrowserView", b"isGroupExpandedAtIndex:", {"retval": {"type": b"Z"}})
r(
b"IKImageBrowserView",
b"setAllowsDroppingOnItems:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKImageBrowserView",
b"setAllowsEmptySelection:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKImageBrowserView",
b"setAllowsMultipleSelection:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKImageBrowserView",
b"setAllowsReordering:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"IKImageBrowserView", b"setAnimates:", {"arguments": {2: {"type": b"Z"}}})
r(
b"IKImageBrowserView",
b"setCanControlQuickLookPanel:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKImageBrowserView",
b"setConstrainsToOriginalSize:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKImageBrowserView",
b"setSelectionIndexes:byExtendingSelection:",
{"arguments": {3: {"type": b"Z"}}},
)
r(
b"IKImagePicker",
b"beginImagePickerSheetForWindow:withDelegate:didEndSelector:contextInfo:",
{"arguments": {4: {"sel_of_type": b"v@:@Q^v"}}},
)
r(
b"IKImagePicker",
b"beginImagePickerWithDelegate:didEndSelector:contextInfo:",
{"arguments": {3: {"sel_of_type": b"v@:@Q^v"}}},
)
r(b"IKImageView", b"autohidesScrollers", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"autoresizes", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"doubleClickOpensImageEditPanel", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"editable", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"hasHorizontalScroller", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"hasVerticalScroller", {"retval": {"type": b"Z"}})
r(b"IKImageView", b"setAutohidesScrollers:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageView", b"setAutoresizes:", {"arguments": {2: {"type": b"Z"}}})
r(
b"IKImageView",
b"setDoubleClickOpensImageEditPanel:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"IKImageView", b"setEditable:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageView", b"setHasHorizontalScroller:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageView", b"setHasVerticalScroller:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageView", b"setSupportsDragAndDrop:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKImageView", b"supportsDragAndDrop", {"retval": {"type": b"Z"}})
r(
b"IKPictureTaker",
b"beginPictureTakerSheetForWindow:withDelegate:didEndSelector:contextInfo:",
{"arguments": {4: {"sel_of_type": b"v@:@q^v"}}},
)
r(
b"IKPictureTaker",
b"beginPictureTakerWithDelegate:didEndSelector:contextInfo:",
{"arguments": {3: {"sel_of_type": b"v@:@q^v"}}},
)
r(b"IKPictureTaker", b"mirroring", {"retval": {"type": b"Z"}})
r(
b"IKPictureTaker",
b"popUpRecentsMenuForView:withDelegate:didEndSelector:contextInfo:",
{"arguments": {4: {"sel_of_type": b"v@:@q^v"}}},
)
r(b"IKPictureTaker", b"setMirroring:", {"arguments": {2: {"type": b"Z"}}})
r(b"IKSaveOptions", b"rememberLastSetting", {"retval": {"type": b"Z"}})
r(b"IKSaveOptions", b"setRememberLastSetting:", {"arguments": {2: {"type": b"Z"}}})
r(
b"IKScannerDeviceView",
b"displaysDownloadsDirectoryControl",
{"retval": {"type": b"Z"}},
)
r(
b"IKScannerDeviceView",
b"displaysPostProcessApplicationControl",
{"retval": {"type": b"Z"}},
)
r(b"IKScannerDeviceView", b"hasDisplayModeAdvanced", {"retval": {"type": b"Z"}})
r(b"IKScannerDeviceView", b"hasDisplayModeSimple", {"retval": {"type": b"Z"}})
r(
b"IKScannerDeviceView",
b"setDisplaysDownloadsDirectoryControl:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKScannerDeviceView",
b"setDisplaysPostProcessApplicationControl:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKScannerDeviceView",
b"setHasDisplayModeAdvanced:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"IKScannerDeviceView",
b"setHasDisplayModeSimple:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"IKSlideshow", b"canExportToApplication:", {"retval": {"type": b"Z"}})
r(
b"NSObject",
b"cameraDeviceView:didDownloadFile:location:fileData:error:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"@"},
4: {"type": b"@"},
5: {"type": b"@"},
6: {"type": b"@"},
},
},
)
r(
b"NSObject",
b"cameraDeviceView:didEncounterError:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"cameraDeviceViewSelectionDidChange:",
{"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"canExportSlideshowItemAtIndex:toApplication:",
{
"required": False,
"retval": {"type": b"Z"},
"arguments": {2: {"type": b"Q"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"deviceBrowserView:didEncounterError:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"deviceBrowserView:selectionDidChange:",
{
"required": True,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(b"NSObject", b"hasAdjustMode", {"required": False, "retval": {"type": b"Z"}})
r(b"NSObject", b"hasDetailsMode", {"required": False, "retval": {"type": b"Z"}})
r(b"NSObject", b"hasEffectsMode", {"required": False, "retval": {"type": b"Z"}})
r(b"NSObject", b"image", {"required": True, "retval": {"type": b"^{CGImage=}"}})
r(
b"NSObject",
b"imageBrowser:backgroundWasRightClickedWithEvent:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}},
)
r(b"NSObject", b"imageBrowser:cellAtIndex:", {"arguments": {3: {"type": "L"}}})
r(
b"NSObject",
b"imageBrowser:cellWasDoubleClickedAtIndex:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"Q"}}},
)
r(
b"NSObject",
b"imageBrowser:cellWasRightClickedAtIndex:withEvent:",
{
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"Q"}, 4: {"type": b"@"}},
},
)
r(
b"NSObject",
b"imageBrowser:groupAtIndex:",
{"retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"Q"}}},
)
r(
b"NSObject",
b"imageBrowser:itemAtIndex:",
{"retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"Q"}}},
)
r(
b"NSObject",
b"imageBrowser:moveCellsAtIndexes:toIndex:",
{"retval": {"type": "Z"}, "arguments": {4: {"type": "L"}}},
)
r(
b"NSObject",
b"imageBrowser:moveItemsAtIndexes:toIndex:",
{
"retval": {"type": b"Z"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"Q"}},
},
)
r(
b"NSObject",
b"imageBrowser:removeItemsAtIndexes:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}},
)
r(
b"NSObject",
b"imageBrowser:writeItemsAtIndexes:toPasteboard:",
{
"retval": {"type": b"Q"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}},
},
)
r(
b"NSObject",
b"imageBrowserSelectionDidChange:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}},
)
r(b"NSObject", b"imageProperties", {"required": False, "retval": {"type": b"@"}})
r(b"NSObject", b"imageRepresentation", {"retval": {"type": b"@"}})
r(b"NSObject", b"imageRepresentationType", {"retval": {"type": b"@"}})
r(b"NSObject", b"imageSubtitle", {"retval": {"type": b"@"}})
r(b"NSObject", b"imageTitle", {"retval": {"type": b"@"}})
r(b"NSObject", b"imageUID", {"retval": {"type": b"@"}})
r(b"NSObject", b"imageVersion", {"retval": {"type": b"Q"}})
r(b"NSObject", b"isSelectable", {"retval": {"type": b"Z"}})
r(
b"NSObject",
b"nameOfSlideshowItemAtIndex:",
{"required": False, "retval": {"type": b"@"}, "arguments": {2: {"type": b"Q"}}},
)
r(b"NSObject", b"numberOfCellsInImageBrowser:", {"retval": {"type": "L"}})
r(
b"NSObject",
b"numberOfGroupsInImageBrowser:",
{"retval": {"type": b"Q"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"numberOfItemsInImageBrowser:",
{"retval": {"type": b"Q"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"numberOfSlideshowItems",
{"required": True, "retval": {"type": b"Q"}},
)
r(
b"NSObject",
b"provideViewForUIConfiguration:excludedKeys:",
{
"required": True,
"retval": {"type": b"@"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"saveOptions:shouldShowUTType:",
{"retval": {"type": b"Z"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}},
)
r(
b"NSObject",
b"scannerDeviceView:didEncounterError:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"scannerDeviceView:didScanToBandData:scanInfo:error:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"@"},
4: {"type": b"@"},
5: {"type": b"@"},
},
},
)
r(
b"NSObject",
b"scannerDeviceView:didScanToURL:error:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}},
},
)
r(
b"NSObject",
b"scannerDeviceView:didScanToURL:fileData:error:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"@"},
4: {"type": b"@"},
5: {"type": b"@"},
},
},
)
r(
b"NSObject",
b"setImage:imageProperties:",
{
"required": True,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"^{CGImage=}"}, 3: {"type": b"@"}},
},
)
r(
b"NSObject",
b"slideshowDidChangeCurrentIndex:",
{"required": False, "retval": {"type": b"v"}, "arguments": {2: {"type": b"Q"}}},
)
r(b"NSObject", b"slideshowDidStop", {"required": False, "retval": {"type": b"v"}})
r(
b"NSObject",
b"slideshowItemAtIndex:",
{"required": True, "retval": {"type": b"@"}, "arguments": {2: {"type": b"Q"}}},
)
r(b"NSObject", b"slideshowWillStart", {"required": False, "retval": {"type": b"v"}})
r(
b"NSObject",
b"thumbnailWithMaximumSize:",
{
"required": False,
"retval": {"type": b"^{CGImage=}"},
"arguments": {2: {"type": b"{CGSize=dd}"}},
},
)
finally:
objc._updatingMetadata(False)
objc.registerNewKeywordsFromSelector("IKFilterUIView", b"initWithFrame:filter:")
objc.registerNewKeywordsFromSelector("IKImageBrowserView", b"initWithFrame:")
objc.registerNewKeywordsFromSelector(
"IKSaveOptions", b"initWithImageProperties:imageUTType:"
)
protocols = {
"IKImageBrowserItem": objc.informal_protocol(
"IKImageBrowserItem",
[
objc.selector(None, b"imageTitle", b"@@:", isRequired=False),
objc.selector(None, b"imageSubtitle", b"@@:", isRequired=False),
objc.selector(None, b"imageRepresentationType", b"@@:", isRequired=False),
objc.selector(None, b"imageUID", b"@@:", isRequired=False),
objc.selector(None, b"isSelectable", b"Z@:", isRequired=False),
objc.selector(None, b"imageVersion", b"Q@:", isRequired=False),
objc.selector(None, b"imageRepresentation", b"@@:", isRequired=False),
],
),
"IKSaveOptionsDelegate": objc.informal_protocol(
"IKSaveOptionsDelegate",
[
objc.selector(
None, b"saveOptions:shouldShowUTType:", b"Z@:@@", isRequired=False
)
],
),
"IKImageBrowserDelegate": objc.informal_protocol(
"IKImageBrowserDelegate",
[
objc.selector(
None,
b"imageBrowser:cellWasRightClickedAtIndex:withEvent:",
b"v@:@Q@",
isRequired=False,
),
objc.selector(
None, b"imageBrowserSelectionDidChange:", b"v@:@", isRequired=False
),
objc.selector(
None,
b"imageBrowser:cellWasDoubleClickedAtIndex:",
b"v@:@Q",
isRequired=False,
),
objc.selector(
None,
b"imageBrowser:backgroundWasRightClickedWithEvent:",
b"v@:@@",
isRequired=False,
),
],
),
"IKImageBrowserDataSource": objc.informal_protocol(
"IKImageBrowserDataSource",
[
objc.selector(
None, b"imageBrowser:groupAtIndex:", b"@@:@Q", isRequired=False
),
objc.selector(
None, b"numberOfItemsInImageBrowser:", b"Q@:@", isRequired=False
),
objc.selector(
None,
b"imageBrowser:moveItemsAtIndexes:toIndex:",
b"Z@:@@Q",
isRequired=False,
),
objc.selector(
None, b"numberOfGroupsInImageBrowser:", b"Q@:@", isRequired=False
),
objc.selector(
None, b"imageBrowser:itemAtIndex:", b"@@:@Q", isRequired=False
),
objc.selector(
None, b"imageBrowser:removeItemsAtIndexes:", b"v@:@@", isRequired=False
),
objc.selector(
None,
b"imageBrowser:writeItemsAtIndexes:toPasteboard:",
b"Q@:@@@",
isRequired=False,
),
],
),
}
expressions = {}
# END OF FILE

View File

@@ -0,0 +1,45 @@
"""
Python mapping for the PDFKit framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import os
import AppKit
import objc
from . import _metadata, _PDFKit
frameworkPath = "/System/Library/Frameworks/PDFKit.framework"
frameworkIdentifier = "com.apple.PDFKit"
if not os.path.exists(frameworkPath):
frameworkPath = "/System/Library/Frameworks/Quartz.framework"
if objc.macos_available(13, 0):
frameworkIdentifier = "com.apple.Quartz"
else:
frameworkIdentifier = "com.apple.quartzframework"
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.PDFKit",
frameworkIdentifier=frameworkIdentifier,
frameworkPath=objc.pathForFramework(frameworkPath),
globals_dict=globals(),
inline_list=None,
parents=(
_PDFKit,
AppKit,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.PDFKit._metadata"]
globals().pop("_setup")()

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,45 @@
"""
Python mapping for the QuartzComposer framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import Foundation
from Quartz import CoreGraphics
import objc
from . import _metadata
if objc.macos_available(14, 0):
identifier = "com.apple.quartzframework"
elif objc.macos_available(13, 0):
identifier = "com.apple.Quartz"
else:
identifier = "com.apple.quartzframework"
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.QuartzComposer",
frameworkIdentifier=identifier,
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/Quartz.framework"
),
globals_dict=globals(),
inline_list=None,
parents=(
CoreGraphics,
Foundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
del sys.modules["Quartz.QuartzComposer._metadata"]
globals().pop("_setup")()

View File

@@ -0,0 +1,440 @@
# This file is generated by objective.metadata
#
# Last update: Wed Oct 15 17:16:10 2025
#
# flake8: noqa
import objc, sys
from typing import NewType
if sys.maxsize > 2**32:
def sel32or64(a, b):
return b
else:
def sel32or64(a, b):
return a
if objc.arch == "arm64":
def selAorI(a, b):
return a
else:
def selAorI(a, b):
return b
misc = {}
constants = """$QCCompositionAttributeBuiltInKey$QCCompositionAttributeCategoryKey$QCCompositionAttributeCopyrightKey$QCCompositionAttributeDescriptionKey$QCCompositionAttributeHasConsumersKey$QCCompositionAttributeIsTimeDependentKey$QCCompositionAttributeNameKey$QCCompositionCategoryDistortion$QCCompositionCategoryStylize$QCCompositionCategoryUtility$QCCompositionInputAudioPeakKey$QCCompositionInputAudioSpectrumKey$QCCompositionInputDestinationImageKey$QCCompositionInputImageKey$QCCompositionInputPaceKey$QCCompositionInputPreviewModeKey$QCCompositionInputPrimaryColorKey$QCCompositionInputRSSArticleDurationKey$QCCompositionInputRSSFeedURLKey$QCCompositionInputScreenImageKey$QCCompositionInputSecondaryColorKey$QCCompositionInputSourceImageKey$QCCompositionInputTrackInfoKey$QCCompositionInputTrackPositionKey$QCCompositionInputTrackSignalKey$QCCompositionInputXKey$QCCompositionInputYKey$QCCompositionOutputImageKey$QCCompositionOutputWebPageURLKey$QCCompositionPickerPanelDidSelectCompositionNotification$QCCompositionPickerViewDidSelectCompositionNotification$QCCompositionProtocolGraphicAnimation$QCCompositionProtocolGraphicTransition$QCCompositionProtocolImageFilter$QCCompositionProtocolMusicVisualizer$QCCompositionProtocolRSSVisualizer$QCCompositionProtocolScreenSaver$QCCompositionRepositoryDidUpdateNotification$QCPlugInAttributeCategoriesKey$QCPlugInAttributeCopyrightKey$QCPlugInAttributeDescriptionKey$QCPlugInAttributeExamplesKey$QCPlugInAttributeNameKey$QCPlugInExecutionArgumentEventKey$QCPlugInExecutionArgumentMouseLocationKey$QCPlugInPixelFormatARGB8$QCPlugInPixelFormatBGRA8$QCPlugInPixelFormatI8$QCPlugInPixelFormatIf$QCPlugInPixelFormatRGBAf$QCPortAttributeDefaultValueKey$QCPortAttributeMaximumValueKey$QCPortAttributeMenuItemsKey$QCPortAttributeMinimumValueKey$QCPortAttributeNameKey$QCPortAttributeTypeKey$QCPortTypeBoolean$QCPortTypeColor$QCPortTypeImage$QCPortTypeIndex$QCPortTypeNumber$QCPortTypeString$QCPortTypeStructure$QCRendererEventKey$QCRendererMouseLocationKey$QCViewDidStartRenderingNotification$QCViewDidStopRenderingNotification$"""
enums = """$kQCPlugInExecutionModeConsumer@3$kQCPlugInExecutionModeProcessor@2$kQCPlugInExecutionModeProvider@1$kQCPlugInTimeModeIdle@1$kQCPlugInTimeModeNone@0$kQCPlugInTimeModeTimeBase@2$"""
misc.update(
{
"QCPlugInExecutionMode": NewType("QCPlugInExecutionMode", int),
"QCPlugInTimeMode": NewType("QCPlugInTimeMode", int),
}
)
misc.update({})
misc.update({})
r = objc.registerMetaDataForSelector
objc._updatingMetadata(True)
try:
r(
b"NSObject",
b"CGLContextObj",
{"required": True, "retval": {"type": b"^{_CGLContextObject=}"}},
)
r(b"NSObject", b"attributes", {"required": True, "retval": {"type": b"@"}})
r(
b"NSObject",
b"bindTextureRepresentationToCGLContext:textureUnit:normalizeCoordinates:",
{
"required": True,
"retval": {"type": b"v"},
"arguments": {
2: {"type": b"^{_CGLContextObject=}"},
3: {"type": b"I"},
4: {"type": b"Z"},
},
},
)
r(
b"NSObject",
b"bounds",
{"required": True, "retval": {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"}},
)
r(b"NSObject", b"bufferBaseAddress", {"required": True, "retval": {"type": b"^v"}})
r(b"NSObject", b"bufferBytesPerRow", {"required": True, "retval": {"type": b"Q"}})
r(
b"NSObject",
b"bufferColorSpace",
{"required": True, "retval": {"type": b"^{CGColorSpace=}"}},
)
r(b"NSObject", b"bufferPixelFormat", {"required": True, "retval": {"type": b"@"}})
r(b"NSObject", b"bufferPixelsHigh", {"required": True, "retval": {"type": b"Q"}})
r(b"NSObject", b"bufferPixelsWide", {"required": True, "retval": {"type": b"Q"}})
r(
b"NSObject",
b"canRenderWithCGLContext:",
{
"required": False,
"retval": {"type": b"Z"},
"arguments": {2: {"type": b"^{_CGLContextObject=}"}},
},
)
r(
b"NSObject",
b"colorSpace",
{"required": True, "retval": {"type": b"^{CGColorSpace=}"}},
)
r(
b"NSObject",
b"compositionParameterView:didChangeParameterWithKey:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}},
)
r(
b"NSObject",
b"compositionParameterView:shouldDisplayParameterWithKey:attributes:",
{
"retval": {"type": b"Z"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}, 4: {"type": b"@"}},
},
)
r(
b"NSObject",
b"compositionPickerView:didSelectComposition:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}, 3: {"type": b"@"}}},
)
r(
b"NSObject",
b"compositionPickerViewDidStartAnimating:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"compositionPickerViewWillStopAnimating:",
{"retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}},
)
r(b"NSObject", b"compositionURL", {"required": True, "retval": {"type": b"@"}})
r(
b"NSObject",
b"copyRenderedTextureForCGLContext:pixelFormat:bounds:isFlipped:",
{
"required": False,
"retval": {"type": b"I"},
"arguments": {
2: {"type": b"^{_CGLContextObject=}"},
3: {"type": b"@"},
4: {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"},
5: {"type": b"^Z"},
},
},
)
r(
b"NSObject",
b"imageBounds",
{"required": True, "retval": {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"}},
)
r(
b"NSObject",
b"imageColorSpace",
{"required": True, "retval": {"type": b"^{CGColorSpace=}"}},
)
r(b"NSObject", b"inputKeys", {"required": True, "retval": {"type": b"@"}})
r(
b"NSObject",
b"lockBufferRepresentationWithPixelFormat:colorSpace:forBounds:",
{
"required": True,
"retval": {"type": b"Z"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"^{CGColorSpace=}"},
4: {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"},
},
},
)
r(
b"NSObject",
b"lockTextureRepresentationWithColorSpace:forBounds:",
{
"required": True,
"retval": {"type": b"Z"},
"arguments": {
2: {"type": b"^{CGColorSpace=}"},
3: {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"},
},
},
)
r(
b"NSObject",
b"logMessage:",
{
"required": True,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"@"}},
"variadic": True,
},
)
r(
b"NSObject",
b"outputImageProviderFromBufferWithPixelFormat:pixelsWide:pixelsHigh:baseAddress:bytesPerRow:releaseCallback:releaseContext:colorSpace:shouldColorMatch:",
{
"required": True,
"retval": {"type": b"@"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"Q"},
4: {"type": b"Q"},
5: {"type": b"^v"},
6: {"type": b"Q"},
7: {"type": b"^?"},
8: {"type": b"^v"},
9: {"type": b"^{CGColorSpace=}"},
10: {"type": b"Z"},
},
},
)
r(
b"NSObject",
b"outputImageProviderFromTextureWithPixelFormat:pixelsWide:pixelsHigh:name:flipped:releaseCallback:releaseContext:colorSpace:shouldColorMatch:",
{
"required": True,
"retval": {"type": b"@"},
"arguments": {
2: {"type": b"@"},
3: {"type": b"Q"},
4: {"type": b"Q"},
5: {"type": b"I"},
6: {"type": b"Z"},
7: {"type": b"^?"},
8: {"type": b"^v"},
9: {"type": b"^{CGColorSpace=}"},
10: {"type": b"Z"},
},
},
)
r(b"NSObject", b"outputKeys", {"required": True, "retval": {"type": b"@"}})
r(
b"NSObject",
b"propertyListFromInputValues",
{"required": True, "retval": {"type": b"@"}},
)
r(
b"NSObject",
b"releaseRenderedTexture:forCGLContext:",
{
"required": False,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"I"}, 3: {"type": b"^{_CGLContextObject=}"}},
},
)
r(
b"NSObject",
b"renderToBuffer:withBytesPerRow:pixelFormat:forBounds:",
{
"required": False,
"retval": {"type": b"Z"},
"arguments": {
2: {"type": b"^v"},
3: {"type": b"Q"},
4: {"type": b"@"},
5: {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"},
},
},
)
r(
b"NSObject",
b"renderWithCGLContext:forBounds:",
{
"required": False,
"retval": {"type": b"Z"},
"arguments": {
2: {"type": b"^{_CGLContextObject=}"},
3: {"type": b"{CGRect={CGPoint=dd}{CGSize=dd}}"},
},
},
)
r(
b"NSObject",
b"setInputValuesWithPropertyList:",
{"required": True, "retval": {"type": b"v"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"setValue:forInputKey:",
{
"required": True,
"retval": {"type": b"Z"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(b"NSObject", b"shouldColorMatch", {"required": False, "retval": {"type": b"Z"}})
r(
b"NSObject",
b"supportedBufferPixelFormats",
{"required": False, "retval": {"type": b"@"}},
)
r(
b"NSObject",
b"supportedRenderedTexturePixelFormats",
{"required": False, "retval": {"type": b"@"}},
)
r(
b"NSObject",
b"textureColorSpace",
{"required": True, "retval": {"type": b"^{CGColorSpace=}"}},
)
r(b"NSObject", b"textureFlipped", {"required": True, "retval": {"type": b"Z"}})
r(b"NSObject", b"textureMatrix", {"required": True, "retval": {"type": b"^f"}})
r(b"NSObject", b"textureName", {"required": True, "retval": {"type": b"I"}})
r(b"NSObject", b"texturePixelsHigh", {"required": True, "retval": {"type": b"Q"}})
r(b"NSObject", b"texturePixelsWide", {"required": True, "retval": {"type": b"Q"}})
r(b"NSObject", b"textureTarget", {"required": True, "retval": {"type": b"I"}})
r(
b"NSObject",
b"unbindTextureRepresentationFromCGLContext:textureUnit:",
{
"required": True,
"retval": {"type": b"v"},
"arguments": {2: {"type": b"^{_CGLContextObject=}"}, 3: {"type": b"I"}},
},
)
r(
b"NSObject",
b"unlockBufferRepresentation",
{"required": True, "retval": {"type": b"v"}},
)
r(
b"NSObject",
b"unlockTextureRepresentation",
{"required": True, "retval": {"type": b"v"}},
)
r(b"NSObject", b"userInfo", {"required": True, "retval": {"type": b"@"}})
r(
b"NSObject",
b"valueForInputKey:",
{"required": True, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"valueForOutputKey:",
{"required": True, "retval": {"type": b"@"}, "arguments": {2: {"type": b"@"}}},
)
r(
b"NSObject",
b"valueForOutputKey:ofType:",
{
"required": True,
"retval": {"type": b"@"},
"arguments": {2: {"type": b"@"}, 3: {"type": b"@"}},
},
)
r(b"QCCompositionParameterView", b"drawsBackground", {"retval": {"type": b"Z"}})
r(b"QCCompositionParameterView", b"hasParameters", {"retval": {"type": b"Z"}})
r(
b"QCCompositionParameterView",
b"setDrawsBackground:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"QCCompositionPickerView", b"allowsEmptySelection", {"retval": {"type": b"Z"}})
r(b"QCCompositionPickerView", b"drawsBackground", {"retval": {"type": b"Z"}})
r(b"QCCompositionPickerView", b"isAnimating", {"retval": {"type": b"Z"}})
r(
b"QCCompositionPickerView",
b"setAllowsEmptySelection:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"QCCompositionPickerView",
b"setDrawsBackground:",
{"arguments": {2: {"type": b"Z"}}},
)
r(
b"QCCompositionPickerView",
b"setShowsCompositionNames:",
{"arguments": {2: {"type": b"Z"}}},
)
r(b"QCCompositionPickerView", b"showsCompositionNames", {"retval": {"type": b"Z"}})
r(b"QCPlugIn", b"createViewController", {"retval": {"already_retained": True}})
r(b"QCPlugIn", b"didValueForInputKeyChange:", {"retval": {"type": b"Z"}})
r(b"QCPlugIn", b"execute:atTime:withArguments:", {"retval": {"type": b"Z"}})
r(b"QCPlugIn", b"loadPlugInAtPath:", {"retval": {"type": b"Z"}})
r(b"QCPlugIn", b"setValue:forOutputKey:", {"retval": {"type": b"Z"}})
r(b"QCPlugIn", b"startExecution:", {"retval": {"type": b"Z"}})
r(b"QCRenderer", b"renderAtTime:arguments:", {"retval": {"type": b"Z"}})
r(b"QCView", b"autostartsRendering", {"retval": {"type": b"Z"}})
r(b"QCView", b"isPausedRendering", {"retval": {"type": b"Z"}})
r(b"QCView", b"isRendering", {"retval": {"type": b"Z"}})
r(b"QCView", b"loadComposition:", {"retval": {"type": b"Z"}})
r(b"QCView", b"loadCompositionFromFile:", {"retval": {"type": b"Z"}})
r(b"QCView", b"renderAtTime:arguments:", {"retval": {"type": b"Z"}})
r(b"QCView", b"setAutostartsRendering:", {"arguments": {2: {"type": b"Z"}}})
r(b"QCView", b"startRendering", {"retval": {"type": b"Z"}})
finally:
objc._updatingMetadata(False)
objc.registerNewKeywordsFromSelector("QCCompositionLayer", b"initWithComposition:")
objc.registerNewKeywordsFromSelector("QCCompositionLayer", b"initWithFile:")
objc.registerNewKeywordsFromSelector(
"QCPlugInViewController", b"initWithPlugIn:viewNibName:"
)
objc.registerNewKeywordsFromSelector(
"QCRenderer", b"initOffScreenWithSize:colorSpace:composition:"
)
objc.registerNewKeywordsFromSelector(
"QCRenderer", b"initWithCGLContext:pixelFormat:colorSpace:composition:"
)
objc.registerNewKeywordsFromSelector("QCRenderer", b"initWithComposition:colorSpace:")
objc.registerNewKeywordsFromSelector(
"QCRenderer", b"initWithOpenGLContext:pixelFormat:file:"
)
protocols = {
"QCCompositionPickerViewDelegate": objc.informal_protocol(
"QCCompositionPickerViewDelegate",
[
objc.selector(
None,
b"compositionPickerView:didSelectComposition:",
b"v@:@@",
isRequired=False,
),
objc.selector(
None,
b"compositionPickerViewWillStopAnimating:",
b"v@:@",
isRequired=False,
),
objc.selector(
None,
b"compositionPickerViewDidStartAnimating:",
b"v@:@",
isRequired=False,
),
],
),
"QCCompositionParameterViewDelegate": objc.informal_protocol(
"QCCompositionParameterViewDelegate",
[
objc.selector(
None,
b"compositionParameterView:didChangeParameterWithKey:",
b"v@:@@",
isRequired=False,
),
objc.selector(
None,
b"compositionParameterView:shouldDisplayParameterWithKey:attributes:",
b"Z@:@@@",
isRequired=False,
),
],
),
}
expressions = {}
# END OF FILE

View File

@@ -0,0 +1,81 @@
"""
Python mapping for the QuartzCore framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
def _setup():
import sys
import Foundation
import objc
from . import _metadata, _quartzcore
dir_func, getattr_func = objc.createFrameworkDirAndGetattr(
name="Quartz.QuartzCore",
frameworkIdentifier="com.apple.QuartzCore",
frameworkPath=objc.pathForFramework(
"/System/Library/Frameworks/QuartzCore.framework"
),
globals_dict=globals(),
inline_list=None,
parents=(
_quartzcore,
Foundation,
),
metadict=_metadata.__dict__,
)
globals()["__dir__"] = dir_func
globals()["__getattr__"] = getattr_func
for cls, sel in (("CAEDRMetadata", b"init"),):
objc.registerUnavailableMethod(cls, sel)
del sys.modules["Quartz.QuartzCore._metadata"]
def CIVector__getitem__(self, idx):
if isinstance(idx, slice):
start, stop, step = idx.indices(self.count())
return [self[i] for i in range(start, stop, step)]
if idx < 0:
new = self.count() + idx
if new < 0:
raise IndexError(idx)
idx = new
return self.valueAtIndex_(idx)
objc.addConvenienceForClass(
"CIVector",
(("__len__", lambda self: self.count()), ("__getitem__", CIVector__getitem__)),
)
objc.addConvenienceForClass(
"CIContext",
(
("__getitem__", lambda self, key: self.objectForKey_(key)),
(
"__setitem__",
lambda self, key, value: self.setObject_forKey_(value, key),
),
),
)
objc.addConvenienceForClass(
"CIContextImpl",
(
("__getitem__", lambda self, key: self.objectForKey_(key)),
(
"__setitem__",
lambda self, key, value: self.setObject_forKey_(value, key),
),
),
)
objc.addConvenienceForBasicSequence("QCStructure", True)
globals().pop("_setup")()

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More