Merge remote-tracking branch 'origin/master' into 1804

This commit is contained in:
LordGrey 2024-12-08 20:40:38 +01:00
commit 2dff7db7fc
26 changed files with 981 additions and 551 deletions

View File

@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- Support for ftdi chip based LED-devices with ws2812, sk6812 apa102 LED types (Many thanks to @nurikk) (#1746) - Support for ftdi chip based LED-devices with ws2812, sk6812 apa102 LED types (Many thanks to @nurikk) (#1746)
- Support for Skydimo devices (being an Adalight variant) - Support for Skydimo devices
- Support gaps on Matrix Layout (#1696) - Support gaps on Matrix Layout (#1696)
- Windows: Added a new grabber that uses the DXGI DDA (Desktop Duplication API). This has much better performance than the DX grabber as it does more of its work on the GPU. - Windows: Added a new grabber that uses the DXGI DDA (Desktop Duplication API). This has much better performance than the DX grabber as it does more of its work on the GPU.
@ -41,6 +41,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixed: Philip Hue APIv2 support without Entertainment group defined (#1742) - Fixed: Philip Hue APIv2 support without Entertainment group defined (#1742)
- Refactored: Database access layer - Refactored: Database access layer
- Refactored: Hyperion's configuration database is validated before start-up (and migrated, if required) - Refactored: Hyperion's configuration database is validated before start-up (and migrated, if required)
- Refactored: Python to enable parallel effect processing under Python 3.12
- Fixed: Python 3.12 crashes (#1747)
- osX Grabber: Use ScreenCaptureKit under macOS 15 and above
**JSON-API** **JSON-API**
- Refactored JSON-API to ensure consistent authorization behaviour across sessions and single requests with token authorization. - Refactored JSON-API to ensure consistent authorization behaviour across sessions and single requests with token authorization.

View File

@ -51,7 +51,6 @@
"name": "hyperion-bare-minimum", "name": "hyperion-bare-minimum",
"hidden": true, "hidden": true,
"cacheVariables": { "cacheVariables": {
// Disable Grabbers
"ENABLE_AMLOGIC": "OFF", "ENABLE_AMLOGIC": "OFF",
"ENABLE_DDA": "OFF", "ENABLE_DDA": "OFF",
"ENABLE_DISPMANX": "OFF", "ENABLE_DISPMANX": "OFF",
@ -64,8 +63,6 @@
"ENABLE_X11": "OFF", "ENABLE_X11": "OFF",
"ENABLE_XCB": "OFF", "ENABLE_XCB": "OFF",
"ENABLE_AUDIO": "OFF", "ENABLE_AUDIO": "OFF",
// LED-Devices
"ENABLE_DEV_FTDI": "OFF", "ENABLE_DEV_FTDI": "OFF",
"ENABLE_DEV_NETWORK": "OFF", "ENABLE_DEV_NETWORK": "OFF",
"ENABLE_DEV_SERIAL": "ON", "ENABLE_DEV_SERIAL": "ON",
@ -73,23 +70,16 @@
"ENABLE_DEV_TINKERFORGE": "OFF", "ENABLE_DEV_TINKERFORGE": "OFF",
"ENABLE_DEV_USB_HID": "OFF", "ENABLE_DEV_USB_HID": "OFF",
"ENABLE_DEV_WS281XPWM": "OFF", "ENABLE_DEV_WS281XPWM": "OFF",
// Disable Input Servers
"ENABLE_BOBLIGHT_SERVER": "OFF", "ENABLE_BOBLIGHT_SERVER": "OFF",
"ENABLE_CEC": "OFF", "ENABLE_CEC": "OFF",
"ENABLE_FLATBUF_SERVER": "OFF", "ENABLE_FLATBUF_SERVER": "OFF",
"ENABLE_PROTOBUF_SERVER": "OFF", "ENABLE_PROTOBUF_SERVER": "OFF",
// Disable Output Connectors
"ENABLE_FORWARDER": "OFF", "ENABLE_FORWARDER": "OFF",
"ENABLE_FLATBUF_CONNECT": "OFF", "ENABLE_FLATBUF_CONNECT": "OFF",
// Disable Services
"ENABLE_EXPERIMENTAL": "OFF", "ENABLE_EXPERIMENTAL": "OFF",
"ENABLE_MDNS": "OFF", "ENABLE_MDNS": "OFF",
"ENABLE_REMOTE_CTL": "OFF", "ENABLE_REMOTE_CTL": "OFF",
"ENABLE_EFFECTENGINE": "OFF", "ENABLE_EFFECTENGINE": "OFF",
"ENABLE_JSONCHECKS": "ON", "ENABLE_JSONCHECKS": "ON",
"ENABLE_DEPLOY_DEPENDENCIES": "ON" "ENABLE_DEPLOY_DEPENDENCIES": "ON"
} }

View File

@ -12,11 +12,12 @@ macro(DeployMacOS TARGET)
install(CODE "set(TARGET_FILE \"${TARGET_FILE}\")" COMPONENT "Hyperion") install(CODE "set(TARGET_FILE \"${TARGET_FILE}\")" COMPONENT "Hyperion")
install(CODE "set(TARGET_BUNDLE_NAME \"${TARGET}.app\")" COMPONENT "Hyperion") install(CODE "set(TARGET_BUNDLE_NAME \"${TARGET}.app\")" COMPONENT "Hyperion")
install(CODE "set(PLUGIN_DIR \"${QT_PLUGIN_DIR}\")" COMPONENT "Hyperion") install(CODE "set(PLUGIN_DIR \"${QT_PLUGIN_DIR}\")" COMPONENT "Hyperion")
install(CODE "set(BUILD_DIR \"${CMAKE_BINARY_DIR}\")" COMPONENT "Hyperion")
install(CODE "set(ENABLE_EFFECTENGINE \"${ENABLE_EFFECTENGINE}\")" COMPONENT "Hyperion") install(CODE "set(ENABLE_EFFECTENGINE \"${ENABLE_EFFECTENGINE}\")" COMPONENT "Hyperion")
install(CODE [[ install(CODE [[
set(BUNDLE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}")
file(GET_RUNTIME_DEPENDENCIES file(GET_RUNTIME_DEPENDENCIES
EXECUTABLES ${TARGET_FILE} EXECUTABLES ${TARGET_FILE}
RESOLVED_DEPENDENCIES_VAR resolved_deps RESOLVED_DEPENDENCIES_VAR resolved_deps
@ -28,13 +29,13 @@ macro(DeployMacOS TARGET)
if (${_index} GREATER -1) if (${_index} GREATER -1)
file(INSTALL file(INSTALL
FILES "${dependency}" FILES "${dependency}"
DESTINATION "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/Frameworks" DESTINATION "${BUNDLE_INSTALL_DIR}/Contents/Frameworks"
TYPE SHARED_LIBRARY TYPE SHARED_LIBRARY
) )
else() else()
file(INSTALL file(INSTALL
FILES "${dependency}" FILES "${dependency}"
DESTINATION "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/lib" DESTINATION "${BUNDLE_INSTALL_DIR}/Contents/lib"
TYPE SHARED_LIBRARY TYPE SHARED_LIBRARY
FOLLOW_SYMLINK_CHAIN FOLLOW_SYMLINK_CHAIN
) )
@ -58,7 +59,7 @@ macro(DeployMacOS TARGET)
foreach(DEPENDENCY ${PLUGINS}) foreach(DEPENDENCY ${PLUGINS})
file(INSTALL file(INSTALL
DESTINATION "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/lib" DESTINATION "${BUNDLE_INSTALL_DIR}/Contents/lib"
TYPE SHARED_LIBRARY TYPE SHARED_LIBRARY
FILES ${DEPENDENCY} FILES ${DEPENDENCY}
FOLLOW_SYMLINK_CHAIN FOLLOW_SYMLINK_CHAIN
@ -66,10 +67,10 @@ macro(DeployMacOS TARGET)
endforeach() endforeach()
get_filename_component(singleQtLib ${file} NAME) get_filename_component(singleQtLib ${file} NAME)
list(APPEND QT_PLUGINS "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/plugins/${PLUGIN}/${singleQtLib}") list(APPEND QT_PLUGINS "${BUNDLE_INSTALL_DIR}/Contents/plugins/${PLUGIN}/${singleQtLib}")
file(INSTALL file(INSTALL
FILES ${file} FILES ${file}
DESTINATION "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/plugins/${PLUGIN}" DESTINATION "${BUNDLE_INSTALL_DIR}/Contents/plugins/${PLUGIN}"
TYPE SHARED_LIBRARY TYPE SHARED_LIBRARY
) )
@ -78,10 +79,10 @@ macro(DeployMacOS TARGET)
endforeach() endforeach()
include(BundleUtilities) include(BundleUtilities)
fixup_bundle("${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}" "${QT_PLUGINS}" "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/lib" IGNORE_ITEM "python;python3;Python;Python3;.Python;.Python3") fixup_bundle("${BUNDLE_INSTALL_DIR}" "${QT_PLUGINS}" "${BUNDLE_INSTALL_DIR}/Contents/lib" IGNORE_ITEM "python;python3;Python;Python3;.Python;.Python3")
file(REMOVE_RECURSE "${BUNDLE_INSTALL_DIR}/Contents/lib")
if(ENABLE_EFFECTENGINE) if(ENABLE_EFFECTENGINE)
# Detect the Python version and modules directory # Detect the Python version and modules directory
if(NOT CMAKE_VERSION VERSION_LESS "3.12") if(NOT CMAKE_VERSION VERSION_LESS "3.12")
find_package(Python3 COMPONENTS Interpreter Development REQUIRED) find_package(Python3 COMPONENTS Interpreter Development REQUIRED)
@ -98,24 +99,37 @@ macro(DeployMacOS TARGET)
# Copy Python modules to '/../Frameworks/Python.framework/Versions/Current/lib/PythonMAJOR.MINOR' and ignore the unnecessary stuff listed below # Copy Python modules to '/../Frameworks/Python.framework/Versions/Current/lib/PythonMAJOR.MINOR' and ignore the unnecessary stuff listed below
if (PYTHON_MODULES_DIR) if (PYTHON_MODULES_DIR)
set(PYTHON_FRAMEWORK "${BUNDLE_INSTALL_DIR}/Contents/Frameworks/Python.framework")
file( file(
COPY ${PYTHON_MODULES_DIR}/ COPY ${PYTHON_MODULES_DIR}/
DESTINATION "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/Frameworks/Python.framework/Versions/Current/lib/python${PYTHON_VERSION_MAJOR_MINOR}" DESTINATION "${PYTHON_FRAMEWORK}/Versions/Current/lib/python${PYTHON_VERSION_MAJOR_MINOR}"
PATTERN "*.pyc" EXCLUDE # compiled bytecodes PATTERN "*.pyc" EXCLUDE # compiled bytecodes
PATTERN "__pycache__" EXCLUDE # any cache PATTERN "__pycache__" EXCLUDE # any cache
PATTERN "config-${PYTHON_VERSION_MAJOR_MINOR}*" EXCLUDE # static libs PATTERN "config-${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}*" EXCLUDE # static libs
PATTERN "lib2to3" EXCLUDE # automated Python 2 to 3 code translation PATTERN "lib2to3" EXCLUDE # automated Python 2 to 3 code translation
PATTERN "tkinter" EXCLUDE # Tk interface PATTERN "tkinter" EXCLUDE # Tk interface
PATTERN "turtledemo" EXCLUDE # Tk demo folder PATTERN "lib-dynload/_tkinter.*" EXCLUDE
PATTERN "turtle.py" EXCLUDE # Tk demo file PATTERN "idlelib" EXCLUDE
PATTERN "turtle.py" EXCLUDE # Tk demo
PATTERN "test" EXCLUDE # unittest module PATTERN "test" EXCLUDE # unittest module
PATTERN "sitecustomize.py" EXCLUDE # site-specific configs PATTERN "sitecustomize.py" EXCLUDE # site-specific configs
) )
endif(PYTHON_MODULES_DIR) endif(PYTHON_MODULES_DIR)
endif(ENABLE_EFFECTENGINE) endif(ENABLE_EFFECTENGINE)
file(REMOVE_RECURSE "${CMAKE_INSTALL_PREFIX}/${TARGET_BUNDLE_NAME}/Contents/lib") file(GLOB_RECURSE LIBS FOLLOW_SYMLINKS "${BUNDLE_INSTALL_DIR}/*.dylib")
file(REMOVE_RECURSE "${CMAKE_INSTALL_PREFIX}/share") file(GLOB FRAMEWORKS FOLLOW_SYMLINKS LIST_DIRECTORIES ON "${BUNDLE_INSTALL_DIR}/Contents/Frameworks/*")
foreach(item ${LIBS} ${FRAMEWORKS} ${PYTHON_FRAMEWORK} ${BUNDLE_INSTALL_DIR})
set(cmd codesign --deep --force --sign - "${item}")
execute_process(
COMMAND ${cmd}
RESULT_VARIABLE codesign_result
)
if(NOT codesign_result EQUAL 0)
message(WARNING "macOS signing failed; ${cmd} returned ${codesign_result}")
endif()
endforeach()
]] COMPONENT "Hyperion") ]] COMPONENT "Hyperion")

View File

@ -49,11 +49,6 @@ on run argv
delay 1 delay 1
close close
-- one last open and close so you can see everything looks correct
open
delay 5
close
end tell end tell
delay 1 delay 1

View File

@ -26,6 +26,8 @@
<string>APPL</string> <string>APPL</string>
<key>LSUIElement</key> <key>LSUIElement</key>
<string>1</string> <string>1</string>
<key>NSCameraUsageDescription</key>
<string>Hyperion uses this access to record screencasts</string>
<key>NSHumanReadableCopyright</key> <key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string> <string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>Source Code</key> <key>Source Code</key>

View File

@ -1,5 +1,3 @@
# Two projectiles are sent from random positions and collide with each other
# Template from https://github.com/nickpesce/lit/blob/master/lit/effects/collision.py
import hyperion, time, colorsys, random import hyperion, time, colorsys, random
# Get parameters # Get parameters
@ -7,6 +5,11 @@ sleepTime = max(0.02, float(hyperion.args.get('speed', 100))/1000.0)
trailLength = max(3, int(hyperion.args.get('trailLength', 5))) trailLength = max(3, int(hyperion.args.get('trailLength', 5)))
explodeRadius = int(hyperion.args.get('explodeRadius', 8)) explodeRadius = int(hyperion.args.get('explodeRadius', 8))
# Ensure that the range for pixel indices stays within bounds
maxPixelIndex = hyperion.ledCount - 1
if trailLength > maxPixelIndex or explodeRadius > maxPixelIndex:
exit(f"Error: Color length ({trailLength}) and detonation range ({explodeRadius}) must be less than number of LEDs configured ({hyperion.ledCount})")
# Create additional variables # Create additional variables
increment = None increment = None
projectiles = [] projectiles = []
@ -18,38 +21,55 @@ for i in range(hyperion.ledCount):
# Start the write data loop # Start the write data loop
while not hyperion.abort(): while not hyperion.abort():
if (len(projectiles) != 2): if len(projectiles) != 2:
projectiles = [ [0, 1, random.uniform(0.0, 1.0)], [hyperion.ledCount-1, -1, random.uniform(0.0, 1.0)] ] projectiles = [
[0, 1, random.uniform(0.0, 1.0)], # Start positions of projectiles
[hyperion.ledCount-1, -1, random.uniform(0.0, 1.0)]
]
increment = -random.randint(0, hyperion.ledCount-1) if random.choice([True, False]) else random.randint(0, hyperion.ledCount-1) increment = -random.randint(0, hyperion.ledCount-1) if random.choice([True, False]) else random.randint(0, hyperion.ledCount-1)
# Backup the LED data
ledDataBuf = ledData[:] ledDataBuf = ledData[:]
for i, v in enumerate(projectiles): for i, v in enumerate(projectiles):
projectiles[i][0] = projectiles[i][0]+projectiles[i][1] # Update projectile positions
projectiles[i][0] = projectiles[i][0] + projectiles[i][1]
for t in range(0, trailLength): for t in range(0, trailLength):
pixel = v[0] - v[1]*t # Calculate pixel index for the trail
if pixel + 2 < 0: pixel = v[0] - v[1] * t
if pixel < 0:
pixel += hyperion.ledCount pixel += hyperion.ledCount
if pixel + 2 > hyperion.ledCount-1: if pixel >= hyperion.ledCount:
pixel -= hyperion.ledCount-1 pixel -= hyperion.ledCount
rgb = colorsys.hsv_to_rgb(v[2], 1, (trailLength - 1.0*t)/trailLength)
ledDataBuf[3*pixel ] = int(255*rgb[0]) # Make sure pixel is within bounds
ledDataBuf[3*pixel + 1] = int(255*rgb[1]) if pixel < 0 or pixel >= hyperion.ledCount:
ledDataBuf[3*pixel + 2] = int(255*rgb[2]) continue
rgb = colorsys.hsv_to_rgb(v[2], 1, (trailLength - 1.0 * t) / trailLength)
ledDataBuf[3*pixel] = int(255 * rgb[0])
ledDataBuf[3*pixel + 1] = int(255 * rgb[1])
ledDataBuf[3*pixel + 2] = int(255 * rgb[2])
hyperion.setColor(ledDataBuf[-increment:] + ledDataBuf[:-increment]) hyperion.setColor(ledDataBuf[-increment:] + ledDataBuf[:-increment])
# Check for collision and handle explosion
for i1, p1 in enumerate(projectiles): for i1, p1 in enumerate(projectiles):
for i2, p2 in enumerate(projectiles): for i2, p2 in enumerate(projectiles):
if (p1 is not p2): if p1 is not p2:
prev1 = p1[0] - p1[1] prev1 = p1[0] - p1[1]
prev2 = p2[0] - p2[1] prev2 = p2[0] - p2[1]
if (prev1 - prev2 < 0) != (p1[0] - p2[0] < 0): if (prev1 - prev2 < 0) != (p1[0] - p2[0] < 0):
for d in range(0, explodeRadius): for d in range(0, explodeRadius):
for pixel in range(p1[0] - d, p1[0] + d): for pixel in range(p1[0] - d, p1[0] + d):
# Check if pixel is out of bounds
if pixel < 0 or pixel >= hyperion.ledCount:
continue
rgb = colorsys.hsv_to_rgb(random.choice([p1[2], p2[2]]), 1, (1.0 * explodeRadius - d) / explodeRadius) rgb = colorsys.hsv_to_rgb(random.choice([p1[2], p2[2]]), 1, (1.0 * explodeRadius - d) / explodeRadius)
ledDataBuf[3*pixel ] = int(255*rgb[0]) ledDataBuf[3 * pixel] = int(255 * rgb[0])
ledDataBuf[3*pixel + 1] = int(255*rgb[1]) ledDataBuf[3 * pixel + 1] = int(255 * rgb[1])
ledDataBuf[3*pixel + 2] = int(255*rgb[2]) ledDataBuf[3 * pixel + 2] = int(255 * rgb[2])
hyperion.setColor(ledDataBuf[-increment:] + ledDataBuf[:-increment]) hyperion.setColor(ledDataBuf[-increment:] + ledDataBuf[:-increment])
time.sleep(sleepTime) time.sleep(sleepTime)

View File

@ -24,13 +24,13 @@ public:
friend class EffectModule; friend class EffectModule;
Effect(Hyperion *hyperion Effect(Hyperion* hyperion
, int priority , int priority
, int timeout , int timeout
, const QString &script , const QString& script
, const QString &name , const QString& name
, const QJsonObject &args = QJsonObject() , const QJsonObject& args = QJsonObject()
, const QString &imageData = "" , const QString& imageData = ""
); );
~Effect() override; ~Effect() override;
@ -64,20 +64,20 @@ public:
QString getScript() const { return _script; } QString getScript() const { return _script; }
QString getName() const { return _name; } QString getName() const { return _name; }
int getTimeout() const {return _timeout; } int getTimeout() const { return _timeout; }
bool isEndless() const { return _isEndless; } bool isEndless() const { return _isEndless; }
QJsonObject getArgs() const { return _args; } QJsonObject getArgs() const { return _args; }
signals: signals:
void setInput(int priority, const std::vector<ColorRgb> &ledColors, int timeout_ms, bool clearEffect); void setInput(int priority, const std::vector<ColorRgb>& ledColors, int timeout_ms, bool clearEffect);
void setInputImage(int priority, const Image<ColorRgb> &image, int timeout_ms, bool clearEffect); void setInputImage(int priority, const Image<ColorRgb>& image, int timeout_ms, bool clearEffect);
private: private:
void setModuleParameters(); bool setModuleParameters();
void addImage(); void addImage();
Hyperion *_hyperion; Hyperion* _hyperion;
const int _priority; const int _priority;
@ -95,13 +95,13 @@ private:
/// Buffer for colorData /// Buffer for colorData
QVector<ColorRgb> _colors; QVector<ColorRgb> _colors;
Logger *_log; Logger* _log;
// Reflects whenever this effects should interrupt (timeout or external request) // Reflects whenever this effects should interrupt (timeout or external request)
std::atomic<bool> _interupt {}; std::atomic<bool> _interupt{};
QSize _imageSize; QSize _imageSize;
QImage _image; QImage _image;
QPainter *_painter; QPainter* _painter;
QVector<QImage> _imageStack; QVector<QImage> _imageStack;
double _lowestUpdateIntervalInSeconds; double _lowestUpdateIntervalInSeconds;

View File

@ -8,22 +8,16 @@
class Effect; class Effect;
class EffectModule: public QObject class EffectModule : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
// Python 3 module def
static struct PyModuleDef moduleDef;
// Init module
static PyObject* PyInit_hyperion();
// Register module once // Register module once
static void registerHyperionExtensionModule(); static void registerHyperionExtensionModule();
// json 2 python // json 2 python
static PyObject * json2python(const QJsonValue & jsonData); static PyObject* json2python(const QJsonValue& jsonData);
// Wrapper methods for Python interpreter extra buildin methods // Wrapper methods for Python interpreter extra buildin methods
static PyMethodDef effectMethods[]; static PyMethodDef effectMethods[];

View File

@ -71,5 +71,7 @@ private:
quint16 _port; quint16 _port;
const QJsonDocument _config; const QJsonDocument _config;
int _pixelDecimation;
QVector<FlatBufferClient*> _openConnections; QVector<FlatBufferClient*> _openConnections;
}; };

View File

@ -1,6 +1,6 @@
#pragma once #pragma once
// OSX includes // CoreGraphics
#include <CoreGraphics/CoreGraphics.h> #include <CoreGraphics/CoreGraphics.h>
// Utils includes // Utils includes

View File

@ -1,5 +1,9 @@
#pragma once #pragma once
#undef slots
#include <Python.h>
#define slots Q_SLOTS
/// ///
/// @brief Handle the PythonInit, module registers and DeInit /// @brief Handle the PythonInit, module registers and DeInit
/// ///
@ -10,4 +14,8 @@ private:
PythonInit(); PythonInit();
~PythonInit(); ~PythonInit();
#if (PY_VERSION_HEX >= 0x03080000)
void handlePythonError(PyStatus status, PyConfig& config);
#endif
}; };

View File

@ -9,6 +9,8 @@
#include "Python.h" #include "Python.h"
#define slots #define slots
#include <python/PythonUtils.h>
class Logger; class Logger;
class PythonProgram class PythonProgram
@ -17,9 +19,15 @@ public:
PythonProgram(const QString & name, Logger * log); PythonProgram(const QString & name, Logger * log);
~PythonProgram(); ~PythonProgram();
operator PyThreadState* ()
{
return _tstate;
}
void execute(const QByteArray &python_code); void execute(const QByteArray &python_code);
private: private:
QString _name; QString _name;
Logger* _log; Logger* _log;
PyThreadState* _tstate; PyThreadState* _tstate;

View File

@ -13,6 +13,7 @@ public:
void setHorizontalPixelDecimation(int decimator) { _horizontalDecimation = decimator; } void setHorizontalPixelDecimation(int decimator) { _horizontalDecimation = decimator; }
void setVerticalPixelDecimation(int decimator) { _verticalDecimation = decimator; } void setVerticalPixelDecimation(int decimator) { _verticalDecimation = decimator; }
void setPixelDecimation(int decimator) { _horizontalDecimation = decimator; _verticalDecimation = decimator;}
void setCropping(int cropLeft, int cropRight, int cropTop, int cropBottom); void setCropping(int cropLeft, int cropRight, int cropTop, int cropBottom);
void setVideoMode(VideoMode mode) { _videoMode = mode; } void setVideoMode(VideoMode mode) { _videoMode = mode; }
void setFlipMode(FlipMode mode) { _flipMode = mode; } void setFlipMode(FlipMode mode) { _flipMode = mode; }

View File

@ -13,6 +13,7 @@
// python utils // python utils
#include <python/PythonProgram.h> #include <python/PythonProgram.h>
// Constants // Constants
namespace { namespace {
int DEFAULT_MAX_UPDATE_RATE_HZ { 200 }; int DEFAULT_MAX_UPDATE_RATE_HZ { 200 };
@ -67,41 +68,81 @@ int Effect::getRemaining() const
if (timeout >= 0) if (timeout >= 0)
{ {
timeout = static_cast<int>( _endTime - QDateTime::currentMSecsSinceEpoch()); timeout = static_cast<int>(_endTime - QDateTime::currentMSecsSinceEpoch());
} }
return timeout; return timeout;
} }
void Effect::setModuleParameters() bool Effect::setModuleParameters()
{ {
// import the buildtin Hyperion module // import the buildtin Hyperion module
PyObject * module = PyImport_ImportModule("hyperion"); PyObject* module = PyImport_ImportModule("hyperion");
// add a capsule containing 'this' to the module to be able to retrieve the effect from the callback function if (module == nullptr) {
PyModule_AddObject(module, "__effectObj", PyCapsule_New((void*)this, "hyperion.__effectObj", nullptr)); PyErr_Print(); // Print error if module import fails
return false;
}
// add ledCount variable to the interpreter // Add a capsule containing 'this' to the module for callback access
PyObject* capsule = PyCapsule_New((void*)this, "hyperion.__effectObj", nullptr);
if (capsule == nullptr || PyModule_AddObject(module, "__effectObj", capsule) < 0) {
PyErr_Print(); // Print error if adding capsule fails
Py_XDECREF(module); // Clean up if capsule addition fails
Py_XDECREF(capsule);
return false;
}
// Add ledCount variable to the interpreter
int ledCount = 0; int ledCount = 0;
QMetaObject::invokeMethod(_hyperion, "getLedCount", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, ledCount)); QMetaObject::invokeMethod(_hyperion, "getLedCount", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, ledCount));
PyObject_SetAttrString(module, "ledCount", Py_BuildValue("i", ledCount)); PyObject* ledCountObj = Py_BuildValue("i", ledCount);
if (PyObject_SetAttrString(module, "ledCount", ledCountObj) < 0) {
PyErr_Print(); // Print error if setting attribute fails
}
Py_XDECREF(ledCountObj);
// add minimumWriteTime variable to the interpreter // Add minimumWriteTime variable to the interpreter
int latchTime = 0; int latchTime = 0;
QMetaObject::invokeMethod(_hyperion, "getLatchTime", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, latchTime)); QMetaObject::invokeMethod(_hyperion, "getLatchTime", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, latchTime));
PyObject_SetAttrString(module, "latchTime", Py_BuildValue("i", latchTime)); PyObject* latchTimeObj = Py_BuildValue("i", latchTime);
if (PyObject_SetAttrString(module, "latchTime", latchTimeObj) < 0) {
PyErr_Print(); // Print error if setting attribute fails
}
Py_XDECREF(latchTimeObj);
// add a args variable to the interpreter // Add args variable to the interpreter
PyObject_SetAttrString(module, "args", EffectModule::json2python(_args)); PyObject* argsObj = EffectModule::json2python(_args);
if (PyObject_SetAttrString(module, "args", argsObj) < 0) {
PyErr_Print(); // Print error if setting attribute fails
}
Py_XDECREF(argsObj);
// decref the module // Decrement module reference
Py_XDECREF(module); Py_XDECREF(module);
return true;
} }
void Effect::run() void Effect::run()
{ {
PythonProgram program(_name, _log); PythonProgram program(_name, _log);
setModuleParameters(); #if (PY_VERSION_HEX < 0x030C0000)
PyThreadState* prev_thread_state = PyThreadState_Swap(program);
#endif
if (!setModuleParameters())
{
Error(_log, "Failed to set Module parameters. Effect will not be executed.");
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(prev_thread_state);
#endif
return;
}
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(prev_thread_state);
#endif
// Set the end time if applicable // Set the end time if applicable
if (_timeout > 0) if (_timeout > 0)
@ -110,7 +151,7 @@ void Effect::run()
} }
// Run the effect script // Run the effect script
QFile file (_script); QFile file(_script);
if (file.open(QIODevice::ReadOnly)) if (file.open(QIODevice::ReadOnly))
{ {
program.execute(file.readAll()); program.execute(file.readAll());

View File

@ -17,25 +17,63 @@
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QEventLoop> #include <QEventLoop>
// Define a struct for per-interpreter state
typedef struct {
} hyperion_module_state;
// Macro to access the module state
#define GET_HYPERION_STATE(module) ((hyperion_module_state*)PyModule_GetState(module))
// Get the effect from the capsule // Get the effect from the capsule
#define getEffect() static_cast<Effect*>((Effect*)PyCapsule_Import("hyperion.__effectObj", 0)) #define getEffect() static_cast<Effect*>((Effect*)PyCapsule_Import("hyperion.__effectObj", 0))
// create the hyperion module // Module execution function for multi-phase init
struct PyModuleDef EffectModule::moduleDef = { static int hyperion_exec(PyObject* module) {
PyModuleDef_HEAD_INIT, // Initialize per-interpreter state
"hyperion", /* m_name */ hyperion_module_state* state = GET_HYPERION_STATE(module);
"Hyperion module", /* m_doc */ if (state == NULL)
-1, /* m_size */ {
EffectModule::effectMethods, /* m_methods */ return -1;
NULL, /* m_reload */ }
NULL, /* m_traverse */ return 0;
NULL, /* m_clear */ }
NULL, /* m_free */
// Module deallocation function to clean up per-interpreter state
static void hyperion_free(void* /* module */)
{
// No specific cleanup required in this example
}
static PyModuleDef_Slot hyperion_slots[] = {
{Py_mod_exec, reinterpret_cast<void*>(hyperion_exec)},
#if (PY_VERSION_HEX >= 0x030C0000)
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
#endif
{0, NULL}
}; };
PyObject* EffectModule::PyInit_hyperion() // Module definition with multi-phase and per-interpreter state
static struct PyModuleDef hyperion_module = {
PyModuleDef_HEAD_INIT,
"hyperion", // Module name
"Hyperion module", // Module docstring
sizeof(hyperion_module_state), // Size of per-interpreter state
EffectModule::effectMethods, // Methods array
NULL, // Slots array (will be added in PyInit_hyperion)
NULL, // Traverse function (optional)
NULL, // Clear function (optional)
hyperion_free // Free function
};
// initialize function for the hyperion module
PyMODINIT_FUNC PyInit_hyperion(void)
{ {
return PyModule_Create(&moduleDef);
// assign slots to the module definition
hyperion_module.m_slots = hyperion_slots;
// return a new module definition instance
return PyModuleDef_Init(&hyperion_module);
} }
void EffectModule::registerHyperionExtensionModule() void EffectModule::registerHyperionExtensionModule()
@ -43,54 +81,77 @@ void EffectModule::registerHyperionExtensionModule()
PyImport_AppendInittab("hyperion", &PyInit_hyperion); PyImport_AppendInittab("hyperion", &PyInit_hyperion);
} }
PyObject *EffectModule::json2python(const QJsonValue &jsonData) PyObject* EffectModule::json2python(const QJsonValue& jsonData)
{ {
switch (jsonData.type()) switch (jsonData.type())
{ {
case QJsonValue::Null: case QJsonValue::Null:
Py_RETURN_NONE; Py_RETURN_NONE;
case QJsonValue::Undefined: case QJsonValue::Undefined:
Py_RETURN_NOTIMPLEMENTED; Py_RETURN_NOTIMPLEMENTED;
case QJsonValue::Double: case QJsonValue::Double:
{ {
double doubleIntegratlPart; double value = jsonData.toDouble();
double doubleFractionalPart = std::modf(jsonData.toDouble(), &doubleIntegratlPart); if (value == static_cast<int>(value)) // If no fractional part, value is equal to its integer representation
if (doubleFractionalPart > std::numeric_limits<double>::epsilon())
{ {
return Py_BuildValue("d", jsonData.toDouble()); return Py_BuildValue("i", static_cast<int>(value));
} }
return Py_BuildValue("i", jsonData.toInt()); return Py_BuildValue("d", value);
} }
case QJsonValue::Bool: case QJsonValue::Bool:
return Py_BuildValue("i", jsonData.toBool() ? 1 : 0); return PyBool_FromLong(jsonData.toBool() ? 1 : 0);
case QJsonValue::String: case QJsonValue::String:
return Py_BuildValue("s", jsonData.toString().toUtf8().constData()); return PyUnicode_FromString(jsonData.toString().toUtf8().constData());
case QJsonValue::Object:
{
PyObject * dict= PyDict_New();
QJsonObject objectData = jsonData.toObject();
for (QJsonObject::iterator i = objectData.begin(); i != objectData.end(); ++i)
{
PyObject * obj = json2python(*i);
PyDict_SetItemString(dict, i.key().toStdString().c_str(), obj);
Py_XDECREF(obj);
}
return dict;
}
case QJsonValue::Array: case QJsonValue::Array:
{ {
QJsonArray arrayData = jsonData.toArray(); QJsonArray arrayData = jsonData.toArray();
PyObject * list = PyList_New(arrayData.size()); PyObject* list = PyList_New(arrayData.size());
int index = 0; int index = 0;
for (QJsonArray::iterator i = arrayData.begin(); i != arrayData.end(); ++i, ++index) for (QJsonArray::iterator i = arrayData.begin(); i != arrayData.end(); ++i, ++index)
{ {
PyObject * obj = json2python(*i); PyObject* obj = json2python(*i);
Py_INCREF(obj); Py_INCREF(obj);
PyList_SetItem(list, index, obj); PyList_SetItem(list, index, obj);
Py_XDECREF(obj); Py_XDECREF(obj);
} }
return list; return list;
} }
case QJsonValue::Object: {
// Python's dict
QJsonObject jsonObject = jsonData.toObject();
PyObject* pyDict = PyDict_New();
for (auto it = jsonObject.begin(); it != jsonObject.end(); ++it) {
// Convert key
PyObject* pyKey = PyUnicode_FromString(it.key().toUtf8().constData());
if (!pyKey) {
Py_XDECREF(pyDict);
return nullptr; // Error occurred, return null
}
// Convert value
PyObject* pyValue = json2python(it.value());
if (!pyValue) {
Py_XDECREF(pyKey);
Py_XDECREF(pyDict);
return nullptr; // Error occurred, return null
}
// Add to dictionary
PyDict_SetItem(pyDict, pyKey, pyValue);
Py_XDECREF(pyKey);
Py_XDECREF(pyValue);
}
return pyDict;
}
default:
// Unsupported type
PyErr_SetString(PyExc_TypeError, "Unsupported QJsonValue type.");
return nullptr;
} }
assert(false); assert(false);
@ -127,7 +188,7 @@ PyMethodDef EffectModule::effectMethods[] = {
{NULL, NULL, 0, NULL} {NULL, NULL, 0, NULL}
}; };
PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args) PyObject* EffectModule::wrapSetColor(PyObject* self, PyObject* args)
{ {
// check the number of arguments // check the number of arguments
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
@ -139,7 +200,7 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args)
{ {
getEffect()->_colors.fill(color); getEffect()->_colors.fill(color);
QVector<ColorRgb> _cQV = getEffect()->_colors; QVector<ColorRgb> _cQV = getEffect()->_colors;
emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>( _cQV.begin(), _cQV.end() ), getEffect()->getRemaining(), false); emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>(_cQV.begin(), _cQV.end()), getEffect()->getRemaining(), false);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
return nullptr; return nullptr;
@ -147,7 +208,7 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args)
else if (argCount == 1) else if (argCount == 1)
{ {
// bytearray of values // bytearray of values
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
if (PyArg_ParseTuple(args, "O", &bytearray)) if (PyArg_ParseTuple(args, "O", &bytearray))
{ {
if (PyByteArray_Check(bytearray)) if (PyByteArray_Check(bytearray))
@ -155,10 +216,10 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args)
size_t length = PyByteArray_Size(bytearray); size_t length = PyByteArray_Size(bytearray);
if (length == 3 * static_cast<size_t>(getEffect()->_hyperion->getLedCount())) if (length == 3 * static_cast<size_t>(getEffect()->_hyperion->getLedCount()))
{ {
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
memcpy(getEffect()->_colors.data(), data, length); memcpy(getEffect()->_colors.data(), data, length);
QVector<ColorRgb> _cQV = getEffect()->_colors; QVector<ColorRgb> _cQV = getEffect()->_colors;
emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>( _cQV.begin(), _cQV.end() ), getEffect()->getRemaining(), false); emit getEffect()->setInput(getEffect()->_priority, std::vector<ColorRgb>(_cQV.begin(), _cQV.end()), getEffect()->getRemaining(), false);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
else else
@ -185,12 +246,12 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args)
} }
} }
PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args) PyObject* EffectModule::wrapSetImage(PyObject* self, PyObject* args)
{ {
// bytearray of values // bytearray of values
int width = 0; int width = 0;
int height = 0; int height = 0;
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray)) if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray))
{ {
if (PyByteArray_Check(bytearray)) if (PyByteArray_Check(bytearray))
@ -199,7 +260,7 @@ PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args)
if (length == 3 * width * height) if (length == 3 * width * height)
{ {
Image<ColorRgb> image(width, height); Image<ColorRgb> image(width, height);
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
memcpy(image.memptr(), data, length); memcpy(image.memptr(), data, length);
emit getEffect()->setInputImage(getEffect()->_priority, image, getEffect()->getRemaining(), false); emit getEffect()->setInputImage(getEffect()->_priority, image, getEffect()->getRemaining(), false);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -226,11 +287,11 @@ PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args) PyObject* EffectModule::wrapGetImage(PyObject* self, PyObject* args)
{ {
QBuffer buffer; QBuffer buffer;
QImageReader reader; QImageReader reader;
char *source; char* source;
int cropLeft = 0, cropTop = 0, cropRight = 0, cropBottom = 0; int cropLeft = 0, cropTop = 0, cropRight = 0, cropBottom = 0;
int grayscale = false; int grayscale = false;
@ -238,7 +299,7 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
{ {
Q_INIT_RESOURCE(EffectEngine); Q_INIT_RESOURCE(EffectEngine);
if(!PyArg_ParseTuple(args, "s|iiiip", &source, &cropLeft, &cropTop, &cropRight, &cropBottom, &grayscale)) if (!PyArg_ParseTuple(args, "s|iiiip", &source, &cropLeft, &cropTop, &cropRight, &cropBottom, &grayscale))
{ {
PyErr_SetString(PyExc_TypeError, "String required"); PyErr_SetString(PyExc_TypeError, "String required");
return nullptr; return nullptr;
@ -247,8 +308,8 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
const QUrl url = QUrl(source); const QUrl url = QUrl(source);
if (url.isValid()) if (url.isValid())
{ {
QNetworkAccessManager *networkManager = new QNetworkAccessManager(); QNetworkAccessManager* networkManager = new QNetworkAccessManager();
QNetworkReply * networkReply = networkManager->get(QNetworkRequest(url)); QNetworkReply* networkReply = networkManager->get(QNetworkRequest(url));
QEventLoop eventLoop; QEventLoop eventLoop;
connect(networkReply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit); connect(networkReply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
@ -270,7 +331,7 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
QString file = QString::fromUtf8(source); QString file = QString::fromUtf8(source);
if (file.mid(0, 1) == ":") if (file.mid(0, 1) == ":")
file = ":/effects/"+file.mid(1); file = ":/effects/" + file.mid(1);
reader.setDecideFormatFromContent(true); reader.setDecideFormatFromContent(true);
reader.setFileName(file); reader.setFileName(file);
@ -287,7 +348,7 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
if (reader.canRead()) if (reader.canRead())
{ {
PyObject *result = PyList_New(reader.imageCount()); PyObject* result = PyList_New(reader.imageCount());
for (int i = 0; i < reader.imageCount(); ++i) for (int i = 0; i < reader.imageCount(); ++i)
{ {
@ -313,18 +374,18 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
} }
QByteArray binaryImage; QByteArray binaryImage;
for (int i = 0; i<height; i++) for (int i = 0; i < height; i++)
{ {
const QRgb *scanline = reinterpret_cast<const QRgb *>(qimage.scanLine(i)); const QRgb* scanline = reinterpret_cast<const QRgb*>(qimage.scanLine(i));
const QRgb *end = scanline + qimage.width(); const QRgb* end = scanline + qimage.width();
for (; scanline != end; scanline++) for (; scanline != end; scanline++)
{ {
binaryImage.append(!grayscale ? (char) qRed(scanline[0]) : (char) qGray(scanline[0])); binaryImage.append(!grayscale ? (char)qRed(scanline[0]) : (char)qGray(scanline[0]));
binaryImage.append(!grayscale ? (char) qGreen(scanline[1]) : (char) qGray(scanline[1])); binaryImage.append(!grayscale ? (char)qGreen(scanline[1]) : (char)qGray(scanline[1]));
binaryImage.append(!grayscale ? (char) qBlue(scanline[2]) : (char) qGray(scanline[2])); binaryImage.append(!grayscale ? (char)qBlue(scanline[2]) : (char)qGray(scanline[2]));
} }
} }
PyList_SET_ITEM(result, i, Py_BuildValue("{s:i,s:i,s:O}", "imageWidth", width, "imageHeight", height, "imageData", PyByteArray_FromStringAndSize(binaryImage.constData(),binaryImage.size()))); PyList_SET_ITEM(result, i, Py_BuildValue("{s:i,s:i,s:O}", "imageWidth", width, "imageHeight", height, "imageData", PyByteArray_FromStringAndSize(binaryImage.constData(), binaryImage.size())));
} }
else else
{ {
@ -342,13 +403,13 @@ PyObject* EffectModule::wrapGetImage(PyObject *self, PyObject *args)
} }
} }
PyObject* EffectModule::wrapAbort(PyObject *self, PyObject *) PyObject* EffectModule::wrapAbort(PyObject* self, PyObject*)
{ {
return Py_BuildValue("i", getEffect()->isInterruptionRequested() ? 1 : 0); return Py_BuildValue("i", getEffect()->isInterruptionRequested() ? 1 : 0);
} }
PyObject* EffectModule::wrapImageShow(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageShow(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int imgId = -1; int imgId = -1;
@ -358,27 +419,27 @@ PyObject* EffectModule::wrapImageShow(PyObject *self, PyObject *args)
argsOk = true; argsOk = true;
} }
if ( ! argsOk || (imgId>-1 && imgId >= getEffect()->_imageStack.size())) if (!argsOk || (imgId > -1 && imgId >= getEffect()->_imageStack.size()))
{ {
return nullptr; return nullptr;
} }
QImage * qimage = (imgId<0) ? &(getEffect()->_image) : &(getEffect()->_imageStack[imgId]); QImage* qimage = (imgId < 0) ? &(getEffect()->_image) : &(getEffect()->_imageStack[imgId]);
int width = qimage->width(); int width = qimage->width();
int height = qimage->height(); int height = qimage->height();
Image<ColorRgb> image(width, height); Image<ColorRgb> image(width, height);
QByteArray binaryImage; QByteArray binaryImage;
for (int i = 0; i<height; ++i) for (int i = 0; i < height; ++i)
{ {
const QRgb * scanline = reinterpret_cast<const QRgb *>(qimage->scanLine(i)); const QRgb* scanline = reinterpret_cast<const QRgb*>(qimage->scanLine(i));
for (int j = 0; j< width; ++j) for (int j = 0; j < width; ++j)
{ {
binaryImage.append((char) qRed(scanline[j])); binaryImage.append((char)qRed(scanline[j]));
binaryImage.append((char) qGreen(scanline[j])); binaryImage.append((char)qGreen(scanline[j]));
binaryImage.append((char) qBlue(scanline[j])); binaryImage.append((char)qBlue(scanline[j]));
} }
} }
@ -388,27 +449,27 @@ PyObject* EffectModule::wrapImageShow(PyObject *self, PyObject *args)
return Py_BuildValue(""); return Py_BuildValue("");
} }
PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageLinearGradient(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
int startRX = 0; int startRX = 0;
int startRY = 0; int startRY = 0;
int startX = 0; int startX = 0;
int startY = 0; int startY = 0;
int width = getEffect()->_imageSize.width(); int width = getEffect()->_imageSize.width();
int endX {width}; int endX{ width };
int height = getEffect()->_imageSize.height(); int height = getEffect()->_imageSize.height();
int endY {height}; int endY{ height };
int spread = 0; int spread = 0;
bool argsOK = false; bool argsOK = false;
if ( argCount == 10 && PyArg_ParseTuple(args, "iiiiiiiiOi", &startRX, &startRY, &width, &height, &startX, &startY, &endX, &endY, &bytearray, &spread) ) if (argCount == 10 && PyArg_ParseTuple(args, "iiiiiiiiOi", &startRX, &startRY, &width, &height, &startX, &startY, &endX, &endY, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 6 && PyArg_ParseTuple(args, "iiiiOi", &startX, &startY, &endX, &endY, &bytearray, &spread) ) if (argCount == 6 && PyArg_ParseTuple(args, "iiiiOi", &startX, &startY, &endX, &endY, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
} }
@ -421,19 +482,19 @@ PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args)
const unsigned arrayItemLength = 5; const unsigned arrayItemLength = 5;
if (length % arrayItemLength == 0) if (length % arrayItemLength == 0)
{ {
QRect myQRect(startRX,startRY,width,height); QRect myQRect(startRX, startRY, width, height);
QLinearGradient gradient(QPoint(startX,startY), QPoint(endX,endY)); QLinearGradient gradient(QPoint(startX, startY), QPoint(endX, endY));
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
for (int idx=0; idx<length; idx+=arrayItemLength) for (int idx = 0; idx < length; idx += arrayItemLength)
{ {
gradient.setColorAt( gradient.setColorAt(
((uint8_t)data[idx])/255.0, ((uint8_t)data[idx]) / 255.0,
QColor( QColor(
(uint8_t)(data[idx+1]), (uint8_t)(data[idx + 1]),
(uint8_t)(data[idx+2]), (uint8_t)(data[idx + 2]),
(uint8_t)(data[idx+3]), (uint8_t)(data[idx + 3]),
(uint8_t)(data[idx+4]) (uint8_t)(data[idx + 4])
)); ));
} }
@ -457,10 +518,10 @@ PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageConicalGradient(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
int centerX = 0; int centerX = 0;
int centerY = 0; int centerY = 0;
int angle = 0; int angle = 0;
@ -471,15 +532,15 @@ PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiiO", &startX, &startY, &width, &height, &centerX, &centerY, &angle, &bytearray) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiiO", &startX, &startY, &width, &height, &centerX, &centerY, &angle, &bytearray))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 4 && PyArg_ParseTuple(args, "iiiO", &centerX, &centerY, &angle, &bytearray) ) if (argCount == 4 && PyArg_ParseTuple(args, "iiiO", &centerX, &centerY, &angle, &bytearray))
{ {
argsOK = true; argsOK = true;
} }
angle = qMax(qMin(angle,360),0); angle = qMax(qMin(angle, 360), 0);
if (argsOK) if (argsOK)
{ {
@ -489,19 +550,19 @@ PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args)
const unsigned arrayItemLength = 5; const unsigned arrayItemLength = 5;
if (length % arrayItemLength == 0) if (length % arrayItemLength == 0)
{ {
QRect myQRect(startX,startY,width,height); QRect myQRect(startX, startY, width, height);
QConicalGradient gradient(QPoint(centerX,centerY), angle ); QConicalGradient gradient(QPoint(centerX, centerY), angle);
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
for (int idx=0; idx<length; idx+=arrayItemLength) for (int idx = 0; idx < length; idx += arrayItemLength)
{ {
gradient.setColorAt( gradient.setColorAt(
((uint8_t)data[idx])/255.0, ((uint8_t)data[idx]) / 255.0,
QColor( QColor(
(uint8_t)(data[idx+1]), (uint8_t)(data[idx + 1]),
(uint8_t)(data[idx+2]), (uint8_t)(data[idx + 2]),
(uint8_t)(data[idx+3]), (uint8_t)(data[idx + 3]),
(uint8_t)(data[idx+4]) (uint8_t)(data[idx + 4])
)); ));
} }
@ -525,16 +586,16 @@ PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args)
} }
PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageRadialGradient(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
int centerX = 0; int centerX = 0;
int centerY = 0; int centerY = 0;
int radius = 0; int radius = 0;
int focalX = 0; int focalX = 0;
int focalY = 0; int focalY = 0;
int focalRadius =0; int focalRadius = 0;
int spread = 0; int spread = 0;
int startX = 0; int startX = 0;
int startY = 0; int startY = 0;
@ -543,22 +604,22 @@ PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 12 && PyArg_ParseTuple(args, "iiiiiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread) ) if (argCount == 12 && PyArg_ParseTuple(args, "iiiiiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &bytearray, &spread) ) if (argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiOi", &startX, &startY, &width, &height, &centerX, &centerY, &radius, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
focalX = centerX; focalX = centerX;
focalY = centerY; focalY = centerY;
focalRadius = radius; focalRadius = radius;
} }
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiOi", &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiOi", &centerX, &centerY, &radius, &focalX, &focalY, &focalRadius, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 5 && PyArg_ParseTuple(args, "iiiOi", &centerX, &centerY, &radius, &bytearray, &spread) ) if (argCount == 5 && PyArg_ParseTuple(args, "iiiOi", &centerX, &centerY, &radius, &bytearray, &spread))
{ {
argsOK = true; argsOK = true;
focalX = centerX; focalX = centerX;
@ -574,18 +635,18 @@ PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args)
if (length % 4 == 0) if (length % 4 == 0)
{ {
QRect myQRect(startX,startY,width,height); QRect myQRect(startX, startY, width, height);
QRadialGradient gradient(QPoint(centerX,centerY), qMax(radius,0) ); QRadialGradient gradient(QPoint(centerX, centerY), qMax(radius, 0));
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
for (int idx=0; idx<length; idx+=4) for (int idx = 0; idx < length; idx += 4)
{ {
gradient.setColorAt( gradient.setColorAt(
((uint8_t)data[idx])/255.0, ((uint8_t)data[idx]) / 255.0,
QColor( QColor(
(uint8_t)(data[idx+1]), (uint8_t)(data[idx + 1]),
(uint8_t)(data[idx+2]), (uint8_t)(data[idx + 2]),
(uint8_t)(data[idx+3]) (uint8_t)(data[idx + 3])
)); ));
} }
@ -609,9 +670,9 @@ PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawPolygon(PyObject* self, PyObject* args)
{ {
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -621,11 +682,11 @@ PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 5 && PyArg_ParseTuple(args, "Oiiii", &bytearray, &r, &g, &b, &a) ) if (argCount == 5 && PyArg_ParseTuple(args, "Oiiii", &bytearray, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 4 && PyArg_ParseTuple(args, "Oiii", &bytearray, &r, &g, &b) ) if (argCount == 4 && PyArg_ParseTuple(args, "Oiii", &bytearray, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
@ -638,18 +699,18 @@ PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args)
if (length % 2 == 0) if (length % 2 == 0)
{ {
QVector <QPoint> points; QVector <QPoint> points;
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
for (int idx=0; idx<length; idx+=2) for (int idx = 0; idx < length; idx += 2)
{ {
points.append(QPoint((int)(data[idx]),(int)(data[idx+1]))); points.append(QPoint((int)(data[idx]), (int)(data[idx + 1])));
} }
QPainter * painter = getEffect()->_painter; QPainter* painter = getEffect()->_painter;
QPen oldPen = painter->pen(); QPen oldPen = painter->pen();
QPen newPen(QColor(r,g,b,a)); QPen newPen(QColor(r, g, b, a));
painter->setPen(newPen); painter->setPen(newPen);
painter->setBrush(QBrush(QColor(r,g,b,a), Qt::SolidPattern)); painter->setBrush(QBrush(QColor(r, g, b, a), Qt::SolidPattern));
painter->drawPolygon(points); painter->drawPolygon(points);
painter->setPen(oldPen); painter->setPen(oldPen);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -669,9 +730,9 @@ PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawPie(PyObject* self, PyObject* args)
{ {
PyObject * bytearray = nullptr; PyObject* bytearray = nullptr;
QString brush; QString brush;
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
@ -687,30 +748,30 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b, &a) ) if (argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &centerX, &centerY, &radius, &startAngle, &spanAngle, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiisO", &centerX, &centerY, &radius, &startAngle, &spanAngle, &brush, &bytearray) ) if (argCount == 7 && PyArg_ParseTuple(args, "iiiiisO", &centerX, &centerY, &radius, &startAngle, &spanAngle, &brush, &bytearray))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 5 && PyArg_ParseTuple(args, "iiisO", &centerX, &centerY, &radius, &brush, &bytearray) ) if (argCount == 5 && PyArg_ParseTuple(args, "iiisO", &centerX, &centerY, &radius, &brush, &bytearray))
{ {
argsOK = true; argsOK = true;
} }
if (argsOK) if (argsOK)
{ {
QPainter * painter = getEffect()->_painter; QPainter* painter = getEffect()->_painter;
startAngle = qMax(qMin(startAngle,360),0); startAngle = qMax(qMin(startAngle, 360), 0);
spanAngle = qMax(qMin(spanAngle,360),-360); spanAngle = qMax(qMin(spanAngle, 360), -360);
if( argCount == 7 || argCount == 5 ) if (argCount == 7 || argCount == 5)
{ {
a = 0; a = 0;
if (PyByteArray_Check(bytearray)) if (PyByteArray_Check(bytearray))
@ -719,20 +780,20 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
if (length % 5 == 0) if (length % 5 == 0)
{ {
QConicalGradient gradient(QPoint(centerX,centerY), startAngle); QConicalGradient gradient(QPoint(centerX, centerY), startAngle);
char * data = PyByteArray_AS_STRING(bytearray); char* data = PyByteArray_AS_STRING(bytearray);
for (int idx=0; idx<length; idx+=5) for (int idx = 0; idx < length; idx += 5)
{ {
gradient.setColorAt( gradient.setColorAt(
((uint8_t)data[idx])/255.0, ((uint8_t)data[idx]) / 255.0,
QColor( QColor(
(uint8_t)(data[idx+1]), (uint8_t)(data[idx + 1]),
(uint8_t)(data[idx+2]), (uint8_t)(data[idx + 2]),
(uint8_t)(data[idx+3]), (uint8_t)(data[idx + 3]),
(uint8_t)(data[idx+4]) (uint8_t)(data[idx + 4])
)); ));
} }
painter->setBrush(gradient); painter->setBrush(gradient);
@ -753,10 +814,10 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
} }
else else
{ {
painter->setBrush(QBrush(QColor(r,g,b,a), Qt::SolidPattern)); painter->setBrush(QBrush(QColor(r, g, b, a), Qt::SolidPattern));
} }
QPen oldPen = painter->pen(); QPen oldPen = painter->pen();
QPen newPen(QColor(r,g,b,a)); QPen newPen(QColor(r, g, b, a));
painter->setPen(newPen); painter->setPen(newPen);
painter->drawPie(centerX - radius, centerY - radius, centerX + radius, centerY + radius, startAngle * 16, spanAngle * 16); painter->drawPie(centerX - radius, centerY - radius, centerX + radius, centerY + radius, startAngle * 16, spanAngle * 16);
painter->setPen(oldPen); painter->setPen(oldPen);
@ -765,7 +826,7 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageSolidFill(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -779,34 +840,34 @@ PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &r, &g, &b, &a) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &startX, &startY, &width, &height, &r, &g, &b) ) if (argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &startX, &startY, &width, &height, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 4 && PyArg_ParseTuple(args, "iiii",&r, &g, &b, &a) ) if (argCount == 4 && PyArg_ParseTuple(args, "iiii", &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 3 && PyArg_ParseTuple(args, "iii",&r, &g, &b) ) if (argCount == 3 && PyArg_ParseTuple(args, "iii", &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if (argsOK) if (argsOK)
{ {
QRect myQRect(startX,startY,width,height); QRect myQRect(startX, startY, width, height);
getEffect()->_painter->fillRect(myQRect, QColor(r,g,b,a)); getEffect()->_painter->fillRect(myQRect, QColor(r, g, b, a));
Py_RETURN_NONE; Py_RETURN_NONE;
} }
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawLine(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -821,21 +882,21 @@ PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b, &a) ) if (argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &endX, &endY, &thick, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if (argsOK) if (argsOK)
{ {
QPainter * painter = getEffect()->_painter; QPainter* painter = getEffect()->_painter;
QRect myQRect(startX, startY, endX, endY); QRect myQRect(startX, startY, endX, endY);
QPen oldPen = painter->pen(); QPen oldPen = painter->pen();
QPen newPen(QColor(r,g,b,a)); QPen newPen(QColor(r, g, b, a));
newPen.setWidth(thick); newPen.setWidth(thick);
painter->setPen(newPen); painter->setPen(newPen);
painter->drawLine(startX, startY, endX, endY); painter->drawLine(startX, startY, endX, endY);
@ -846,7 +907,7 @@ PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawPoint(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -859,20 +920,20 @@ PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &x, &y, &thick, &r, &g, &b, &a) ) if (argCount == 7 && PyArg_ParseTuple(args, "iiiiiii", &x, &y, &thick, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 6 && PyArg_ParseTuple(args, "iiiiii", &x, &y, &thick, &r, &g, &b) ) if (argCount == 6 && PyArg_ParseTuple(args, "iiiiii", &x, &y, &thick, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if (argsOK) if (argsOK)
{ {
QPainter * painter = getEffect()->_painter; QPainter* painter = getEffect()->_painter;
QPen oldPen = painter->pen(); QPen oldPen = painter->pen();
QPen newPen(QColor(r,g,b,a)); QPen newPen(QColor(r, g, b, a));
newPen.setWidth(thick); newPen.setWidth(thick);
painter->setPen(newPen); painter->setPen(newPen);
painter->drawPoint(x, y); painter->drawPoint(x, y);
@ -883,7 +944,7 @@ PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawRect(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -898,21 +959,21 @@ PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args)
bool argsOK = false; bool argsOK = false;
if ( argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b, &a) ) if (argCount == 9 && PyArg_ParseTuple(args, "iiiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b, &a))
{ {
argsOK = true; argsOK = true;
} }
if ( argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b) ) if (argCount == 8 && PyArg_ParseTuple(args, "iiiiiiii", &startX, &startY, &width, &height, &thick, &r, &g, &b))
{ {
argsOK = true; argsOK = true;
} }
if (argsOK) if (argsOK)
{ {
QPainter * painter = getEffect()->_painter; QPainter* painter = getEffect()->_painter;
QRect myQRect(startX,startY,width,height); QRect myQRect(startX, startY, width, height);
QPen oldPen = painter->pen(); QPen oldPen = painter->pen();
QPen newPen(QColor(r,g,b,a)); QPen newPen(QColor(r, g, b, a));
newPen.setWidth(thick); newPen.setWidth(thick);
painter->setPen(newPen); painter->setPen(newPen);
painter->drawRect(startX, startY, width, height); painter->drawRect(startX, startY, width, height);
@ -924,7 +985,7 @@ PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args)
} }
PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageSetPixel(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int r = 0; int r = 0;
@ -933,9 +994,9 @@ PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args)
int x = 0; int x = 0;
int y = 0; int y = 0;
if ( argCount == 5 && PyArg_ParseTuple(args, "iiiii", &x, &y, &r, &g, &b ) ) if (argCount == 5 && PyArg_ParseTuple(args, "iiiii", &x, &y, &r, &g, &b))
{ {
getEffect()->_image.setPixel(x,y,qRgb(r,g,b)); getEffect()->_image.setPixel(x, y, qRgb(r, g, b));
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -943,29 +1004,29 @@ PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args)
} }
PyObject* EffectModule::wrapImageGetPixel(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageGetPixel(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int x = 0; int x = 0;
int y = 0; int y = 0;
if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &x, &y) ) if (argCount == 2 && PyArg_ParseTuple(args, "ii", &x, &y))
{ {
QRgb rgb = getEffect()->_image.pixel(x,y); QRgb rgb = getEffect()->_image.pixel(x, y);
return Py_BuildValue("iii",qRed(rgb),qGreen(rgb),qBlue(rgb)); return Py_BuildValue("iii", qRed(rgb), qGreen(rgb), qBlue(rgb));
} }
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageSave(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageSave(PyObject* self, PyObject* args)
{ {
QImage img(getEffect()->_image.copy()); QImage img(getEffect()->_image.copy());
getEffect()->_imageStack.append(img); getEffect()->_imageStack.append(img);
return Py_BuildValue("i", getEffect()->_imageStack.size()-1); return Py_BuildValue("i", getEffect()->_imageStack.size() - 1);
} }
PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageMinSize(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int w = 0; int w = 0;
@ -973,13 +1034,13 @@ PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args)
int width = getEffect()->_imageSize.width(); int width = getEffect()->_imageSize.width();
int height = getEffect()->_imageSize.height(); int height = getEffect()->_imageSize.height();
if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &w, &h) ) if (argCount == 2 && PyArg_ParseTuple(args, "ii", &w, &h))
{ {
if (width<w || height<h) if (width < w || height < h)
{ {
delete getEffect()->_painter; delete getEffect()->_painter;
getEffect()->_image = getEffect()->_image.scaled(qMax(width,w),qMax(height,h), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); getEffect()->_image = getEffect()->_image.scaled(qMax(width, w), qMax(height, h), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
getEffect()->_imageSize = getEffect()->_image.size(); getEffect()->_imageSize = getEffect()->_image.size();
getEffect()->_painter = new QPainter(&(getEffect()->_image)); getEffect()->_painter = new QPainter(&(getEffect()->_image));
} }
@ -988,60 +1049,60 @@ PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args)
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageWidth(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageWidth(PyObject* self, PyObject* args)
{ {
return Py_BuildValue("i", getEffect()->_imageSize.width()); return Py_BuildValue("i", getEffect()->_imageSize.width());
} }
PyObject* EffectModule::wrapImageHeight(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageHeight(PyObject* self, PyObject* args)
{ {
return Py_BuildValue("i", getEffect()->_imageSize.height()); return Py_BuildValue("i", getEffect()->_imageSize.height());
} }
PyObject* EffectModule::wrapImageCRotate(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageCRotate(PyObject* self, PyObject* args)
{ {
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
int angle; int angle;
if ( argCount == 1 && PyArg_ParseTuple(args, "i", &angle ) ) if (argCount == 1 && PyArg_ParseTuple(args, "i", &angle))
{ {
angle = qMax(qMin(angle,360),0); angle = qMax(qMin(angle, 360), 0);
getEffect()->_painter->rotate(angle); getEffect()->_painter->rotate(angle);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageCOffset(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageCOffset(PyObject* self, PyObject* args)
{ {
int offsetX = 0; int offsetX = 0;
int offsetY = 0; int offsetY = 0;
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
if ( argCount == 2 ) if (argCount == 2)
{ {
PyArg_ParseTuple(args, "ii", &offsetX, &offsetY ); PyArg_ParseTuple(args, "ii", &offsetX, &offsetY);
} }
getEffect()->_painter->translate(QPoint(offsetX,offsetY)); getEffect()->_painter->translate(QPoint(offsetX, offsetY));
Py_RETURN_NONE; Py_RETURN_NONE;
} }
PyObject* EffectModule::wrapImageCShear(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageCShear(PyObject* self, PyObject* args)
{ {
int sh = 0; int sh = 0;
int sv = 0; int sv = 0;
int argCount = PyTuple_Size(args); int argCount = PyTuple_Size(args);
if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &sh, &sv )) if (argCount == 2 && PyArg_ParseTuple(args, "ii", &sh, &sv))
{ {
getEffect()->_painter->shear(sh,sv); getEffect()->_painter->shear(sh, sv);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
return nullptr; return nullptr;
} }
PyObject* EffectModule::wrapImageResetT(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageResetT(PyObject* self, PyObject* args)
{ {
getEffect()->_painter->resetTransform(); getEffect()->_painter->resetTransform();
Py_RETURN_NONE; Py_RETURN_NONE;

View File

@ -1,4 +1,5 @@
#include "FlatBufferClient.h" #include "FlatBufferClient.h"
#include <utils/PixelFormat.h>
// qt // qt
#include <QTcpSocket> #include <QTcpSocket>
@ -15,6 +16,8 @@ FlatBufferClient::FlatBufferClient(QTcpSocket* socket, int timeout, QObject *par
, _timeout(timeout * 1000) , _timeout(timeout * 1000)
, _priority() , _priority()
{ {
_imageResampler.setPixelDecimation(1);
// timer setup // timer setup
_timeoutTimer->setSingleShot(true); _timeoutTimer->setSingleShot(true);
_timeoutTimer->setInterval(_timeout); _timeoutTimer->setInterval(_timeout);
@ -25,6 +28,11 @@ FlatBufferClient::FlatBufferClient(QTcpSocket* socket, int timeout, QObject *par
connect(_socket, &QTcpSocket::disconnected, this, &FlatBufferClient::disconnected); connect(_socket, &QTcpSocket::disconnected, this, &FlatBufferClient::disconnected);
} }
void FlatBufferClient::setPixelDecimation(int decimator)
{
_imageResampler.setPixelDecimation(decimator);
}
void FlatBufferClient::readyRead() void FlatBufferClient::readyRead()
{ {
_timeoutTimer->start(); _timeoutTimer->start();
@ -141,55 +149,71 @@ void FlatBufferClient::handleRegisterCommand(const hyperionnet::Register *regReq
void FlatBufferClient::handleImageCommand(const hyperionnet::Image *image) void FlatBufferClient::handleImageCommand(const hyperionnet::Image *image)
{ {
Image<ColorRgb> imageRGB;
// extract parameters // extract parameters
int duration = image->duration(); int duration = image->duration();
const void* reqPtr; const void* reqPtr;
if ((reqPtr = image->data_as_RawImage()) != nullptr) if ((reqPtr = image->data_as_RawImage()) != nullptr)
{ {
const auto *img = static_cast<const hyperionnet::RawImage*>(reqPtr); const auto* img = static_cast<const hyperionnet::RawImage*>(reqPtr);
const auto & imageData = img->data();
const int width = img->width();
const int height = img->height();
if (width <= 0 || height <= 0) hyperionnet::RawImageT rawImageNative;
img->UnPackTo(&rawImageNative);
const int width = rawImageNative.width;
const int height = rawImageNative.height;
if (width <= 0 || height <= 0 || rawImageNative.data.empty())
{ {
sendErrorReply("Size of image data does not match with the width and height"); sendErrorReply("Invalid width and/or height or no raw image data provided");
return; return;
} }
// check consistency of the size of the received data // check consistency of the size of the received data
int channelCount = (int)imageData->size()/(width*height); int bytesPerPixel = rawImageNative.data.size() / (width * height);
if (channelCount != 3 && channelCount != 4) if (bytesPerPixel != 3 && bytesPerPixel != 4)
{ {
sendErrorReply("Size of image data does not match with the width and height"); sendErrorReply("Size of image data does not match with the width and height");
return; return;
} }
// create ImageRgb imageRGB.resize(width, height);
Image<ColorRgb> imageRGB(width, height); processRawImage(rawImageNative, bytesPerPixel, _imageResampler, imageRGB);
if (channelCount == 3) }
else if ((reqPtr = image->data_as_NV12Image()) != nullptr)
{ {
memmove(imageRGB.memptr(), imageData->data(), imageData->size()); const auto* img = static_cast<const hyperionnet::NV12Image*>(reqPtr);
hyperionnet::NV12ImageT nv12ImageNative;
img->UnPackTo(&nv12ImageNative);
const int width = nv12ImageNative.width;
const int height = nv12ImageNative.height;
if (width <= 0 || height <= 0 || nv12ImageNative.data_y.empty() || nv12ImageNative.data_uv.empty())
{
sendErrorReply("Invalid width and/or height or no complete NV12 image data provided");
return;
} }
if (channelCount == 4) imageRGB.resize(width, height);
{ processNV12Image(nv12ImageNative, _imageResampler, imageRGB);
for (int source=0, destination=0; source < width * height * static_cast<int>(sizeof(ColorRgb)); source+=sizeof(ColorRgb), destination+=sizeof(ColorRgba))
{
memmove((uint8_t*)imageRGB.memptr() + source, imageData->data() + destination, sizeof(ColorRgb));
} }
else
{
sendErrorReply("No or unknown image data provided");
return;
} }
emit setGlobalInputImage(_priority, imageRGB, duration); emit setGlobalInputImage(_priority, imageRGB, duration);
emit setBufferImage("FlatBuffer", imageRGB); emit setBufferImage("FlatBuffer", imageRGB);
}
// send reply // send reply
sendSuccessReply(); sendSuccessReply();
} }
void FlatBufferClient::handleClearCommand(const hyperionnet::Clear *clear) void FlatBufferClient::handleClearCommand(const hyperionnet::Clear *clear)
{ {
// extract parameters // extract parameters
@ -242,3 +266,50 @@ void FlatBufferClient::sendErrorReply(const std::string &error)
_builder.Clear(); _builder.Clear();
} }
inline void FlatBufferClient::processRawImage(const hyperionnet::RawImageT& raw_image, int bytesPerPixel, ImageResampler& resampler, Image<ColorRgb>& outputImage) {
int width = raw_image.width;
int height = raw_image.height;
int lineLength = width * bytesPerPixel;
PixelFormat pixelFormat = (bytesPerPixel == 4) ? PixelFormat::RGB32 : PixelFormat::RGB24;
// Process the image
resampler.processImage(
raw_image.data.data(), // Raw RGB/RGBA buffer
width, // Image width
height, // Image height
lineLength, // Line length
pixelFormat, // Pixel format (RGB24/RGB32)
outputImage // Output image
);
}
inline void FlatBufferClient::processNV12Image(const hyperionnet::NV12ImageT& nv12_image, ImageResampler& resampler, Image<ColorRgb>& outputImage) {
// Combine data_y and data_uv into a single buffer
int width = nv12_image.width;
int height = nv12_image.height;
size_t y_size = nv12_image.data_y.size();
size_t uv_size = nv12_image.data_uv.size();
std::vector<uint8_t> combined_buffer(y_size + uv_size);
std::memcpy(combined_buffer.data(), nv12_image.data_y.data(), y_size);
std::memcpy(combined_buffer.data() + y_size, nv12_image.data_uv.data(), uv_size);
// Determine line length (stride_y)
int lineLength = nv12_image.stride_y > 0 ? nv12_image.stride_y : width;
PixelFormat pixelFormat = PixelFormat::NV12;
// Process the image
resampler.processImage(
combined_buffer.data(), // Combined NV12 buffer
width, // Image width
height, // Image height
lineLength, // Line length for Y plane
pixelFormat, // Pixel format (NV12)
outputImage // Output image
);
}

View File

@ -6,6 +6,7 @@
#include <utils/ColorRgb.h> #include <utils/ColorRgb.h>
#include <utils/ColorRgba.h> #include <utils/ColorRgba.h>
#include <utils/Components.h> #include <utils/Components.h>
#include "utils/ImageResampler.h"
// flatbuffer FBS // flatbuffer FBS
#include "hyperion_reply_generated.h" #include "hyperion_reply_generated.h"
@ -33,6 +34,8 @@ public:
/// ///
explicit FlatBufferClient(QTcpSocket* socket, int timeout, QObject *parent = nullptr); explicit FlatBufferClient(QTcpSocket* socket, int timeout, QObject *parent = nullptr);
void setPixelDecimation(int decimator);
signals: signals:
/// ///
/// @brief forward register data to HyperionDaemon /// @brief forward register data to HyperionDaemon
@ -138,6 +141,9 @@ private:
/// ///
void sendErrorReply(const std::string & error); void sendErrorReply(const std::string & error);
void processRawImage(const hyperionnet::RawImageT& raw_image, int bytesPerPixel, ImageResampler& resampler, Image<ColorRgb>& outputImage);
void processNV12Image(const hyperionnet::NV12ImageT& nv12_image, ImageResampler& resampler, Image<ColorRgb>& outputImage);
private: private:
Logger *_log; Logger *_log;
QTcpSocket *_socket; QTcpSocket *_socket;
@ -148,6 +154,8 @@ private:
QByteArray _receiveBuffer; QByteArray _receiveBuffer;
ImageResampler _imageResampler;
// Flatbuffers builder // Flatbuffers builder
flatbuffers::FlatBufferBuilder _builder; flatbuffers::FlatBufferBuilder _builder;
}; };

View File

@ -62,6 +62,12 @@ void FlatBufferServer::handleSettingsUpdate(settings::type type, const QJsonDocu
_timeout = obj["timeout"].toInt(5000); _timeout = obj["timeout"].toInt(5000);
// enable check // enable check
obj["enable"].toBool(true) ? startServer() : stopServer(); obj["enable"].toBool(true) ? startServer() : stopServer();
_pixelDecimation = obj["pixelDecimation"].toInt(1);
for (const auto& client : _openConnections)
{
client->setPixelDecimation(_pixelDecimation);
}
} }
} }
@ -75,6 +81,9 @@ void FlatBufferServer::newConnection()
{ {
Debug(_log, "New connection from %s", QSTRING_CSTR(socket->peerAddress().toString())); Debug(_log, "New connection from %s", QSTRING_CSTR(socket->peerAddress().toString()));
FlatBufferClient *client = new FlatBufferClient(socket, _timeout, this); FlatBufferClient *client = new FlatBufferClient(socket, _timeout, this);
client->setPixelDecimation(_pixelDecimation);
// internal // internal
connect(client, &FlatBufferClient::clientDisconnected, this, &FlatBufferServer::clientDisconnected); connect(client, &FlatBufferClient::clientDisconnected, this, &FlatBufferServer::clientDisconnected);
connect(client, &FlatBufferClient::registerGlobalInput, GlobalSignals::getInstance(), &GlobalSignals::registerGlobalInput); connect(client, &FlatBufferClient::registerGlobalInput, GlobalSignals::getInstance(), &GlobalSignals::registerGlobalInput);

View File

@ -12,9 +12,17 @@ table RawImage {
height:int = -1; height:int = -1;
} }
union ImageType {RawImage} table NV12Image {
data_y:[ubyte];
data_uv:[ubyte];
width:int;
height:int;
stride_y:int = 0;
stride_uv:int = 0;
}
union ImageType {RawImage, NV12Image}
// Either RGB or RGBA data can be transferred
table Image { table Image {
data:ImageType (required); data:ImageType (required);
duration:int = -1; duration:int = -1;

View File

@ -1,10 +1,28 @@
add_library(osx-grabber add_library(osx-grabber
${CMAKE_SOURCE_DIR}/include/grabber/osx/OsxFrameGrabber.h ${CMAKE_SOURCE_DIR}/include/grabber/osx/OsxFrameGrabber.h
${CMAKE_SOURCE_DIR}/include/grabber/osx/OsxWrapper.h ${CMAKE_SOURCE_DIR}/include/grabber/osx/OsxWrapper.h
${CMAKE_SOURCE_DIR}/libsrc/grabber/osx/OsxFrameGrabber.cpp ${CMAKE_SOURCE_DIR}/libsrc/grabber/osx/OsxFrameGrabber.mm
${CMAKE_SOURCE_DIR}/libsrc/grabber/osx/OsxWrapper.cpp ${CMAKE_SOURCE_DIR}/libsrc/grabber/osx/OsxWrapper.cpp
) )
target_link_libraries(osx-grabber target_link_libraries(osx-grabber
hyperion hyperion
"$<LINK_LIBRARY:FRAMEWORK,CoreGraphics.framework>"
) )
file(WRITE ${CMAKE_BINARY_DIR}/tmp/SDK15Available.c
"#include <AvailabilityMacros.h>
#if __MAC_OS_X_VERSION_MAX_ALLOWED < 150000
#error __MAC_OS_X_VERSION_MAX_ALLOWED < 150000
#endif
int main(int argc, char** argv)
{
return 0;
}"
)
try_compile(SDK_15_AVAILABLE ${CMAKE_BINARY_DIR} SOURCES ${CMAKE_BINARY_DIR}/tmp/SDK15Available.c)
if(SDK_15_AVAILABLE)
target_compile_definitions(osx-grabber PRIVATE SDK_15_AVAILABLE)
target_link_libraries(osx-grabber "$<LINK_LIBRARY:WEAK_FRAMEWORK,ScreenCaptureKit.framework>")
endif()

View File

@ -1,10 +1,16 @@
// STL includes // STL includes
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <mutex>
// Local includes // Header
#include <grabber/osx/OsxFrameGrabber.h> #include <grabber/osx/OsxFrameGrabber.h>
// ScreenCaptureKit
#if defined(SDK_15_AVAILABLE)
#include <ScreenCaptureKit/ScreenCaptureKit.h>
#endif
//Qt //Qt
#include <QJsonObject> #include <QJsonObject>
#include <QJsonArray> #include <QJsonArray>
@ -15,6 +21,67 @@ namespace {
const bool verbose = false; const bool verbose = false;
} //End of constants } //End of constants
#if defined(SDK_15_AVAILABLE)
static CGImageRef capture15(CGDirectDisplayID id, CGRect diIntersectDisplayLocal)
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block CGImageRef image1 = nil;
[SCShareableContent getShareableContentWithCompletionHandler:^(SCShareableContent* content, NSError* error)
{
@autoreleasepool
{
if (error || !content)
{
dispatch_semaphore_signal(semaphore);
return;
}
SCDisplay* target = nil;
for (SCDisplay *display in content.displays)
{
if (display.displayID == id)
{
target = display;
break;
}
}
if (!target)
{
dispatch_semaphore_signal(semaphore);
return;
}
SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:target excludingWindows:@[]];
SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init];
config.queueDepth = 5;
config.sourceRect = diIntersectDisplayLocal;
config.scalesToFit = false;
config.captureResolution = SCCaptureResolutionBest;
CGDisplayModeRef modeRef = CGDisplayCopyDisplayMode(id);
double sysScale = CGDisplayModeGetPixelWidth(modeRef) / CGDisplayModeGetWidth(modeRef);
config.width = diIntersectDisplayLocal.size.width * sysScale;
config.height = diIntersectDisplayLocal.size.height * sysScale;
[SCScreenshotManager captureImageWithFilter:filter
configuration:config
completionHandler:^(CGImageRef img, NSError* error)
{
if (!error)
{
image1 = CGImageCreateCopyWithColorSpace(img, CGColorSpaceCreateDeviceRGB());
}
dispatch_semaphore_signal(semaphore);
}];
}
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
return image1;
}
#endif
OsxFrameGrabber::OsxFrameGrabber(int display) OsxFrameGrabber::OsxFrameGrabber(int display)
: Grabber("GRABBER-OSX") : Grabber("GRABBER-OSX")
, _screenIndex(display) , _screenIndex(display)
@ -31,6 +98,15 @@ bool OsxFrameGrabber::setupDisplay()
{ {
bool rc (false); bool rc (false);
#if defined(SDK_15_AVAILABLE)
if (!CGPreflightScreenCaptureAccess())
{
if(!CGRequestScreenCaptureAccess())
Error(_log, "Screen capture permission required to start the grabber");
return false;
}
#endif
rc = setDisplayIndex(_screenIndex); rc = setDisplayIndex(_screenIndex);
return rc; return rc;
@ -41,39 +117,38 @@ int OsxFrameGrabber::grabFrame(Image<ColorRgb> & image)
int rc = 0; int rc = 0;
if (_isEnabled && !_isDeviceInError) if (_isEnabled && !_isDeviceInError)
{ {
CGImageRef dispImage; CGImageRef dispImage;
CFDataRef imgData;
unsigned char * pImgData;
unsigned dspWidth;
unsigned dspHeight;
dispImage = CGDisplayCreateImage(_display); #if defined(SDK_15_AVAILABLE)
dispImage = capture15(_display, CGDisplayBounds(_display));
#else
dispImage = CGDisplayCreateImageForRect(_display, CGDisplayBounds(_display));
#endif
// display lost, use main // display lost, use main
if (dispImage == nullptr && _display != 0) if (dispImage == nullptr && _display != 0)
{ {
dispImage = CGDisplayCreateImage(kCGDirectMainDisplay); #if defined(SDK_15_AVAILABLE)
dispImage = capture15(kCGDirectMainDisplay, CGDisplayBounds(kCGDirectMainDisplay));
#else
dispImage = CGDisplayCreateImageForRect(kCGDirectMainDisplay, CGDisplayBounds(kCGDirectMainDisplay));
#endif
}
// no displays connected, return // no displays connected, return
if (dispImage == nullptr) if (dispImage == nullptr)
{ {
Error(_log, "No display connected..."); Error(_log, "No display connected...");
return -1; return -1;
} }
}
imgData = CGDataProviderCopyData(CGImageGetDataProvider(dispImage));
pImgData = (unsigned char*) CFDataGetBytePtr(imgData);
dspWidth = CGImageGetWidth(dispImage);
dspHeight = CGImageGetHeight(dispImage);
_imageResampler.processImage( pImgData,
static_cast<int>(dspWidth),
static_cast<int>(dspHeight),
static_cast<int>(CGImageGetBytesPerRow(dispImage)),
PixelFormat::BGR32,
image);
CFDataRef imgData = CGDataProviderCopyData(CGImageGetDataProvider(dispImage));
if (imgData != nullptr)
{
_imageResampler.processImage((uint8_t *)CFDataGetBytePtr(imgData), static_cast<int>(CGImageGetWidth(dispImage)), static_cast<int>(CGImageGetHeight(dispImage)), static_cast<int>(CGImageGetBytesPerRow(dispImage)), PixelFormat::BGR32, image);
CFRelease(imgData); CFRelease(imgData);
}
CGImageRelease(dispImage); CGImageRelease(dispImage);
} }
@ -108,7 +183,12 @@ bool OsxFrameGrabber::setDisplayIndex(int index)
{ {
_display = activeDspys[_screenIndex]; _display = activeDspys[_screenIndex];
image = CGDisplayCreateImage(_display); #if defined(SDK_15_AVAILABLE)
image = capture15(_display, CGDisplayBounds(_display));
#else
image = CGDisplayCreateImageForRect(_display, CGDisplayBounds(_display));
#endif
if(image == nullptr) if(image == nullptr)
{ {
setEnabled(false); setEnabled(false);

View File

@ -1,35 +1,41 @@
{ {
"type" : "object", "type" : "object",
"title" : "edt_conf_fbs_heading_title", "title" : "edt_conf_fbs_heading_title",
"properties" : "properties": {
{ "enable": {
"enable" : "type": "boolean",
{ "required": true,
"type" : "boolean", "title": "edt_conf_general_enable_title",
"required" : true, "default": true,
"title" : "edt_conf_general_enable_title", "propertyOrder": 1
"default" : true,
"propertyOrder" : 1
}, },
"port" : "port": {
{ "type": "integer",
"type" : "integer", "required": true,
"required" : true, "title": "edt_conf_general_port_title",
"title" : "edt_conf_general_port_title", "minimum": 1024,
"minimum" : 1024, "maximum": 65535,
"maximum" : 65535, "default": 19400,
"default" : 19400, "propertyOrder": 2
"propertyOrder" : 2
}, },
"timeout" : "timeout": {
{ "type": "integer",
"type" : "integer", "required": true,
"required" : true, "title": "edt_conf_fbs_timeout_title",
"title" : "edt_conf_fbs_timeout_title", "append": "edt_append_s",
"append" : "edt_append_s", "minimum": 1,
"minimum" : 1, "default": 5,
"default" : 5, "propertyOrder": 3
"propertyOrder" : 3 },
"pixelDecimation": {
"type": "integer",
"title": "edt_conf_fg_pixelDecimation_title",
"minimum": 1,
"maximum": 30,
"default": 1,
"required": false,
"access": "advanced",
"propertyOrder": 4
} }
}, },
"additionalProperties" : false "additionalProperties" : false

View File

@ -115,7 +115,11 @@ if(ENABLE_DEV_NETWORK)
if(NOT DEFAULT_USE_SYSTEM_MBEDTLS_LIBS) if(NOT DEFAULT_USE_SYSTEM_MBEDTLS_LIBS)
if(MBEDTLS_LIBRARIES) if(MBEDTLS_LIBRARIES)
include_directories(${MBEDTLS_INCLUDE_DIR}) include_directories(${MBEDTLS_INCLUDE_DIR})
target_link_libraries(leddevice ${MBEDTLS_LIBRARIES}) target_link_libraries(
leddevice
${MBEDTLS_LIBRARIES}
$<$<BOOL:${WIN32}>:bcrypt.lib>
)
target_include_directories(leddevice PRIVATE ${MBEDTLS_INCLUDE_DIR}) target_include_directories(leddevice PRIVATE ${MBEDTLS_INCLUDE_DIR})
endif (MBEDTLS_LIBRARIES) endif (MBEDTLS_LIBRARIES)
endif() endif()

View File

@ -64,5 +64,9 @@ int LedDeviceSkydimo::write(const std::vector<ColorRgb> & ledValues)
return 0; return 0;
} }
assert(HEADER_SIZE + ledValues.size() * sizeof(ColorRgb) <= _ledBuffer.size());
memcpy(HEADER_SIZE + _ledBuffer.data(), ledValues.data(), ledValues.size() * sizeof(ColorRgb));
return writeBytes(_bufferLength, _ledBuffer.data()); return writeBytes(_bufferLength, _ledBuffer.data());
} }

View File

@ -18,7 +18,7 @@
#include <HyperionConfig.h> #include <HyperionConfig.h>
#ifdef _WIN32 #ifdef _WIN32
#include <stdexcept> #include <stdexcept>
#endif #endif
#define STRINGIFY2(x) #x #define STRINGIFY2(x) #x
@ -44,14 +44,14 @@ PythonInit::PythonInit()
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
status = PyConfig_SetString(&config, &config.program_name, programName); status = PyConfig_SetString(&config, &config.program_name, programName);
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
else
#else #else
Py_SetProgramName(programName); Py_SetProgramName(programName);
#endif #endif
{ {
// set Python module path when exists // set Python module path when it exists
QString py_path = QDir::cleanPath(qApp->applicationDirPath() + "/../lib/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + "." + STRINGIFY(PYTHON_VERSION_MINOR)); QString py_path = QDir::cleanPath(qApp->applicationDirPath() + "/../lib/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + "." + STRINGIFY(PYTHON_VERSION_MINOR));
QString py_file = QDir::cleanPath(qApp->applicationDirPath() + "/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + STRINGIFY(PYTHON_VERSION_MINOR) + ".zip"); QString py_file = QDir::cleanPath(qApp->applicationDirPath() + "/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + STRINGIFY(PYTHON_VERSION_MINOR) + ".zip");
QString py_framework = QDir::cleanPath(qApp->applicationDirPath() + "/../Frameworks/Python.framework/Versions/Current/lib/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + "." + STRINGIFY(PYTHON_VERSION_MINOR)); QString py_framework = QDir::cleanPath(qApp->applicationDirPath() + "/../Frameworks/Python.framework/Versions/Current/lib/python" + STRINGIFY(PYTHON_VERSION_MAJOR) + "." + STRINGIFY(PYTHON_VERSION_MINOR));
@ -68,12 +68,14 @@ PythonInit::PythonInit()
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(py_file)); status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(py_file));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
config.module_search_paths_set = 1; config.module_search_paths_set = 1;
status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(py_file.toStdWString().c_str())); status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(py_file.toStdWString().c_str()));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
#else #else
Py_SetPythonHome(Py_DecodeLocale(py_file.toLatin1().data(), nullptr)); Py_SetPythonHome(Py_DecodeLocale(py_file.toLatin1().data(), nullptr));
@ -85,18 +87,21 @@ PythonInit::PythonInit()
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(QDir::cleanPath(qApp->applicationDirPath() + "/../"))); status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(QDir::cleanPath(qApp->applicationDirPath() + "/../")));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
config.module_search_paths_set = 1; config.module_search_paths_set = 1;
status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_path).absolutePath().toStdWString().c_str())); status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_path).absolutePath().toStdWString().c_str()));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_path + "/lib-dynload").absolutePath().toStdWString().c_str())); status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_path + "/lib-dynload").absolutePath().toStdWString().c_str()));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
#else #else
QStringList python_paths; QStringList python_paths;
@ -114,18 +119,21 @@ PythonInit::PythonInit()
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(QDir::cleanPath(qApp->applicationDirPath() + "/../Frameworks/Python.framework/Versions/Current"))); status = PyConfig_SetBytesString(&config, &config.home, QSTRING_CSTR(QDir::cleanPath(qApp->applicationDirPath() + "/../Frameworks/Python.framework/Versions/Current")));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
config.module_search_paths_set = 1; config.module_search_paths_set = 1;
status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_framework).absolutePath().toStdWString().c_str())); status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_framework).absolutePath().toStdWString().c_str()));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_framework + "/lib-dynload").absolutePath().toStdWString().c_str())); status = PyWideStringList_Append(&config.module_search_paths, const_cast<wchar_t*>(QDir(py_framework + "/lib-dynload").absolutePath().toStdWString().c_str()));
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
#else #else
QStringList python_paths; QStringList python_paths;
@ -146,7 +154,8 @@ PythonInit::PythonInit()
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
status = Py_InitializeFromConfig(&config); status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) { if (PyStatus_Exception(status)) {
goto exception; handlePythonError(status, config);
return;
} }
PyConfig_Clear(&config); PyConfig_Clear(&config);
#endif #endif
@ -154,7 +163,8 @@ PythonInit::PythonInit()
// init Python // init Python
Debug(Logger::getInstance("DAEMON"), "Initializing Python interpreter"); Debug(Logger::getInstance("DAEMON"), "Initializing Python interpreter");
Py_InitializeEx(0); Py_InitializeEx(0);
if ( !Py_IsInitialized() )
if (!Py_IsInitialized())
{ {
throw std::runtime_error("Initializing Python failed!"); throw std::runtime_error("Initializing Python failed!");
} }
@ -165,20 +175,28 @@ PythonInit::PythonInit()
#endif #endif
mainThreadState = PyEval_SaveThread(); mainThreadState = PyEval_SaveThread();
return; }
// Error handling function to replace goto exception
#if (PY_VERSION_HEX >= 0x03080000) #if (PY_VERSION_HEX >= 0x03080000)
exception: void PythonInit::handlePythonError(PyStatus status, PyConfig& config)
{
Error(Logger::getInstance("DAEMON"), "Initializing Python config failed with error [%s]", status.err_msg); Error(Logger::getInstance("DAEMON"), "Initializing Python config failed with error [%s]", status.err_msg);
PyConfig_Clear(&config); PyConfig_Clear(&config);
throw std::runtime_error("Initializing Python failed!"); throw std::runtime_error("Initializing Python failed!");
#endif
} }
#endif
PythonInit::~PythonInit() PythonInit::~PythonInit()
{ {
Debug(Logger::getInstance("DAEMON"), "Cleaning up Python interpreter"); Debug(Logger::getInstance("DAEMON"), "Cleaning up Python interpreter");
#if (PY_VERSION_HEX < 0x030C0000)
PyEval_RestoreThread(mainThreadState); PyEval_RestoreThread(mainThreadState);
Py_Finalize(); #else
PyThreadState_Swap(mainThreadState);
#endif
int rc = Py_FinalizeEx();
Debug(Logger::getInstance("DAEMON"), "Cleaning up Python interpreter %s", rc == 0 ? "succeeded" : "failed");
} }

View File

@ -1,173 +1,238 @@
#include <python/PythonProgram.h> #include <python/PythonProgram.h>
#include <python/PythonUtils.h> #include <python/PythonUtils.h>
#include <utils/Logger.h> #include <utils/Logger.h>
#include <QThread> #include <QThread>
PyThreadState* mainThreadState; PyThreadState* mainThreadState;
PythonProgram::PythonProgram(const QString & name, Logger * log) : PythonProgram::PythonProgram(const QString& name, Logger* log) :
_name(name), _log(log), _tstate(nullptr) _name(name)
, _log(log)
, _tstate(nullptr)
{ {
// we probably need to wait until mainThreadState is available // we probably need to wait until mainThreadState is available
while(mainThreadState == nullptr){}; QThread::msleep(10);
while (mainThreadState == nullptr)
{
QThread::msleep(10); // Wait with delay to avoid busy waiting
}
// Create a new subinterpreter for this thread
#if (PY_VERSION_HEX < 0x030C0000)
// get global lock // get global lock
PyEval_RestoreThread(mainThreadState); PyEval_RestoreThread(mainThreadState);
// Initialize a new thread state
_tstate = Py_NewInterpreter(); _tstate = Py_NewInterpreter();
if(_tstate == nullptr)
{
#if (PY_VERSION_HEX >= 0x03020000)
PyThreadState_Swap(mainThreadState);
PyEval_SaveThread();
#else #else
PyEval_ReleaseLock(); PyThreadState* prev = PyThreadState_Swap(NULL);
// Create a new interpreter configuration object
PyInterpreterConfig config{};
// Set configuration options
config.use_main_obmalloc = 0;
config.allow_fork = 0;
config.allow_exec = 0;
config.allow_threads = 1;
config.allow_daemon_threads = 0;
config.check_multi_interp_extensions = 1;
config.gil = PyInterpreterConfig_OWN_GIL;
Py_NewInterpreterFromConfig(&_tstate, &config);
#endif #endif
Error(_log, "Failed to get thread state for %s",QSTRING_CSTR(_name));
if (_tstate == nullptr)
{
PyThreadState_Swap(mainThreadState);
#if (PY_VERSION_HEX < 0x030C0000)
PyEval_SaveThread();
#endif
Error(_log, "Failed to get thread state for %s", QSTRING_CSTR(_name));
return; return;
} }
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(_tstate); PyThreadState_Swap(_tstate);
#endif
} }
PythonProgram::~PythonProgram() PythonProgram::~PythonProgram()
{ {
if (!_tstate) if (!_tstate)
{
return; return;
// stop sub threads if needed
for (PyThreadState* s = PyInterpreterState_ThreadHead(_tstate->interp), *old = nullptr; s;)
{
if (s == _tstate)
{
s = s->next;
continue;
}
if (old != s)
{
Debug(_log,"ID %s: Waiting on thread %u", QSTRING_CSTR(_name), s->thread_id);
old = s;
} }
Py_BEGIN_ALLOW_THREADS; #if (PY_VERSION_HEX < 0x030C0000)
QThread::msleep(100); PyThreadState* prev_thread_state = PyThreadState_Swap(_tstate);
Py_END_ALLOW_THREADS; #endif
s = PyInterpreterState_ThreadHead(_tstate->interp);
}
// Clean up the thread state // Clean up the thread state
Py_EndInterpreter(_tstate); Py_EndInterpreter(_tstate);
#if (PY_VERSION_HEX >= 0x03020000)
PyThreadState_Swap(mainThreadState); #if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(prev_thread_state);
PyEval_SaveThread(); PyEval_SaveThread();
#else
PyEval_ReleaseLock();
#endif #endif
} }
void PythonProgram::execute(const QByteArray & python_code) void PythonProgram::execute(const QByteArray& python_code)
{ {
if (!_tstate) if (!_tstate)
{
return; return;
}
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(_tstate);
#else
PyThreadState* prev_thread_state = PyThreadState_Swap(_tstate);
#endif
PyObject* main_module = PyImport_ImportModule("__main__");
if (!main_module)
{
// Restore the previous thread state
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(mainThreadState);
#else
PyThreadState_Swap(prev_thread_state);
#endif
return;
}
PyObject *main_module = PyImport_ImportModule("__main__"); // New Reference PyObject* main_dict = PyModule_GetDict(main_module); // Borrowed reference to globals
PyObject *main_dict = PyModule_GetDict(main_module); // Borrowed reference PyObject* result = PyRun_String(python_code.constData(), Py_file_input, main_dict, main_dict);
Py_INCREF(main_dict); // Incref "main_dict" to use it in PyRun_String(), because PyModule_GetDict() has decref "main_dict"
Py_DECREF(main_module); // // release "main_module" when done
PyObject *result = PyRun_String(python_code.constData(), Py_file_input, main_dict, main_dict); // New Reference
if (!result) if (!result)
{ {
if (PyErr_Occurred()) // Nothing needs to be done for a borrowed reference if (PyErr_Occurred())
{ {
Error(_log,"###### PYTHON EXCEPTION ######"); PyObject* errorType = NULL, * errorValue = NULL, * errorTraceback = NULL;
Error(_log,"## In effect '%s'", QSTRING_CSTR(_name));
/* Objects all initialized to NULL for Py_XDECREF */
PyObject *errorType = NULL, *errorValue = NULL, *errorTraceback = NULL;
PyErr_Fetch(&errorType, &errorValue, &errorTraceback); // New Reference or NULL PyErr_Fetch(&errorType, &errorValue, &errorTraceback);
PyErr_NormalizeException(&errorType, &errorValue, &errorTraceback); PyErr_NormalizeException(&errorType, &errorValue, &errorTraceback);
// Extract exception message from "errorValue" // Check if the exception is a SystemExit
if(errorValue) PyObject* systemExitType = PyExc_SystemExit;
{ bool isSystemExit = PyObject_IsInstance(errorValue, systemExitType);
QString message;
if(PyObject_HasAttrString(errorValue, "__class__"))
{
PyObject *classPtr = PyObject_GetAttrString(errorValue, "__class__"); // New Reference
PyObject *class_name = NULL; /* Object "class_name" initialized to NULL for Py_XDECREF */
class_name = PyObject_GetAttrString(classPtr, "__name__"); // New Reference or NULL
if(class_name && PyUnicode_Check(class_name)) if (isSystemExit)
{
// Extract the exit argument
PyObject* exitArg = PyObject_GetAttrString(errorValue, "code");
if (exitArg)
{
QString logErrorText;
if (PyTuple_Check(exitArg)) {
PyObject* errorMessage = PyTuple_GetItem(exitArg, 0); // Borrowed reference
PyObject* exitCode = PyTuple_GetItem(exitArg, 1); // Borrowed reference
if (exitCode && PyLong_Check(exitCode))
{
logErrorText = QString("[%1]: ").arg(PyLong_AsLong(exitCode));
}
if (errorMessage && PyUnicode_Check(errorMessage)) {
logErrorText.append(PyUnicode_AsUTF8(errorMessage));
}
}
else if (PyUnicode_Check(exitArg)) {
// If the code is just a string, treat it as an error message
logErrorText.append(PyUnicode_AsUTF8(exitArg));
}
else if (PyLong_Check(exitArg)) {
// If the code is just an integer, treat it as an exit code
logErrorText = QString("[%1]").arg(PyLong_AsLong(exitArg));
}
Error(_log, "Effect '%s' failed with error %s", QSTRING_CSTR(_name), QSTRING_CSTR(logErrorText));
Py_DECREF(exitArg); // Release the reference
}
else
{
Debug(_log, "No 'code' attribute found on SystemExit exception.");
}
// Clear the error so it won't propagate
PyErr_Clear();
Py_DECREF(systemExitType);
return;
}
Py_DECREF(systemExitType);
if (errorValue)
{
Error(_log, "###### PYTHON EXCEPTION ######");
Error(_log, "## In effect '%s'", QSTRING_CSTR(_name));
QString message;
if (PyObject_HasAttrString(errorValue, "__class__"))
{
PyObject* classPtr = PyObject_GetAttrString(errorValue, "__class__");
PyObject* class_name = classPtr ? PyObject_GetAttrString(classPtr, "__name__") : NULL;
if (class_name && PyUnicode_Check(class_name))
message.append(PyUnicode_AsUTF8(class_name)); message.append(PyUnicode_AsUTF8(class_name));
Py_DECREF(classPtr); // release "classPtr" when done Py_XDECREF(class_name);
Py_XDECREF(class_name); // Use Py_XDECREF() to ignore NULL references Py_DECREF(classPtr);
} }
// Object "class_name" initialized to NULL for Py_XDECREF PyObject* valueString = PyObject_Str(errorValue);
PyObject *valueString = NULL;
valueString = PyObject_Str(errorValue); // New Reference or NULL
if(valueString && PyUnicode_Check(valueString)) if (valueString && PyUnicode_Check(valueString))
{ {
if(!message.isEmpty()) if (!message.isEmpty())
message.append(": "); message.append(": ");
message.append(PyUnicode_AsUTF8(valueString)); message.append(PyUnicode_AsUTF8(valueString));
} }
Py_XDECREF(valueString); // Use Py_XDECREF() to ignore NULL references Py_XDECREF(valueString);
Error(_log, "## %s", QSTRING_CSTR(message)); Error(_log, "## %s", QSTRING_CSTR(message));
} }
// Extract exception message from "errorTraceback" if (errorTraceback)
if(errorTraceback)
{ {
// Object "tracebackList" initialized to NULL for Py_XDECREF PyObject* tracebackModule = PyImport_ImportModule("traceback");
PyObject *tracebackModule = NULL, *methodName = NULL, *tracebackList = NULL; PyObject* methodName = PyUnicode_FromString("format_exception");
QString tracebackMsg; PyObject* tracebackList = tracebackModule && methodName
? PyObject_CallMethodObjArgs(tracebackModule, methodName, errorType, errorValue, errorTraceback, NULL)
: NULL;
tracebackModule = PyImport_ImportModule("traceback"); // New Reference or NULL if (tracebackList)
methodName = PyUnicode_FromString("format_exception"); // New Reference or NULL
tracebackList = PyObject_CallMethodObjArgs(tracebackModule, methodName, errorType, errorValue, errorTraceback, NULL); // New Reference or NULL
if(tracebackList)
{ {
PyObject* iterator = PyObject_GetIter(tracebackList); // New Reference PyObject* iterator = PyObject_GetIter(tracebackList);
PyObject* item; PyObject* item;
while( (item = PyIter_Next(iterator)) ) // New Reference while ((item = PyIter_Next(iterator)))
{ {
Error(_log, "## %s",QSTRING_CSTR(QString(PyUnicode_AsUTF8(item)).trimmed())); Error(_log, "## %s", QSTRING_CSTR(QString(PyUnicode_AsUTF8(item)).trimmed()));
Py_DECREF(item); // release "item" when done Py_DECREF(item);
} }
Py_DECREF(iterator); // release "iterator" when done Py_DECREF(iterator);
} }
// Use Py_XDECREF() to ignore NULL references
Py_XDECREF(tracebackModule); Py_XDECREF(tracebackModule);
Py_XDECREF(methodName); Py_XDECREF(methodName);
Py_XDECREF(tracebackList); Py_XDECREF(tracebackList);
// Give the exception back to python and print it to stderr in case anyone else wants it.
Py_XINCREF(errorType);
Py_XINCREF(errorValue);
Py_XINCREF(errorTraceback);
PyErr_Restore(errorType, errorValue, errorTraceback); PyErr_Restore(errorType, errorValue, errorTraceback);
//PyErr_PrintEx(0); // Remove this line to switch off stderr output
} }
Error(_log,"###### EXCEPTION END ######"); Error(_log, "###### EXCEPTION END ######");
} }
// Clear the error so it won't propagate
PyErr_Clear();
} }
else else
{ {
Py_DECREF(result); // release "result" when done Py_DECREF(result); // Release result when done
} }
Py_DECREF(main_dict); // release "main_dict" when done Py_DECREF(main_module);
// Restore the previous thread state
#if (PY_VERSION_HEX < 0x030C0000)
PyThreadState_Swap(mainThreadState);
#else
PyThreadState_Swap(prev_thread_state);
#endif
} }