diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..218fa61 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +__history +*.local +*.dcu +*.exe +*.identcache +Docs/_build/ +*.sublime-workspace diff --git a/Docs/G940LEDControl.Docs.sublime-project b/Docs/G940LEDControl.Docs.sublime-project new file mode 100644 index 0000000..80af61d --- /dev/null +++ b/Docs/G940LEDControl.Docs.sublime-project @@ -0,0 +1,10 @@ +{ + "folders": + [ + { + "path": ".", + "file_exclude_patterns": ["*.sublime-project"], + "folder_exclude_patterns": ["_build"] + } + ] +} diff --git a/Docs/Makefile b/Docs/Makefile new file mode 100644 index 0000000..8408bf6 --- /dev/null +++ b/Docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = G940LEDControl +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/Docs/autoPilotAirspeedStates.png b/Docs/autoPilotAirspeedStates.png new file mode 100644 index 0000000..3cbedfb Binary files /dev/null and b/Docs/autoPilotAirspeedStates.png differ diff --git a/Docs/conf.py b/Docs/conf.py new file mode 100644 index 0000000..30a8065 --- /dev/null +++ b/Docs/conf.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# +# G940LEDControl documentation build configuration file, created by +# sphinx-quickstart on Sat Feb 11 13:02:50 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'G940LEDControl' +author = u'Mark van Renswoude' +html_show_copyright = False + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'' +# The full version, including alpha/beta/rc tags. +release = u'' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +import sphinx_rtd_theme +html_theme = 'sphinx_rtd_theme' +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'G940LEDControldoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'G940LEDControl.tex', u'G940LEDControl Documentation', + u'Mark van Renswoude', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'G940LEDControl', u'G940LEDControl Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'G940LEDControl', u'G940LEDControl Documentation', + author, 'G940LEDControl', 'Getting the most out of your Logitech G940 Flight System', + 'Miscellaneous'), +] + + +highlight_language = 'lua' \ No newline at end of file diff --git a/Docs/index.rst b/Docs/index.rst new file mode 100644 index 0000000..55418ba --- /dev/null +++ b/Docs/index.rst @@ -0,0 +1,10 @@ +G940LEDControl documentation +============================ + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + introduction + scripting + scriptingreference \ No newline at end of file diff --git a/Docs/introduction.rst b/Docs/introduction.rst new file mode 100644 index 0000000..7a26836 --- /dev/null +++ b/Docs/introduction.rst @@ -0,0 +1,22 @@ +Introduction +============ + +G940LEDControl allows you to bind functions to the throttle's buttons which control the LEDs. Each function may contains several states, each of which can be configured for a certain colour and/of flashing pattern. + +Since version 2.0 all functions are implemented using Lua scripts. This means it is fairly easy to create customized versions of the standard functions, or even add a completely new function. For more information, see the page on :doc:`scripting` or dive straight into the :doc:`scriptingreference`. + +Source code +----------- + +Since version 2.0, G940LEDControl is released as open-source under the GNU General Public License v3.0. The main Git repository is located at ``_ with a clone being kept up to date at ``_. + +G940LEDControl is compiled using Delphi XE2. The following additional libraries are required: + +* `OmniThreadLibrary `_ (1.0.4) +* `VirtualTreeView `_ (5.3.0) +* `X2Log `_ +* `X2Utils `_ + +Newer versions Delphi and/or of the libraries might work as well, though have not been tested yet. + +A copy of `DelphiLua `_ is included in the G940LEDControl repository. \ No newline at end of file diff --git a/Docs/make.bat b/Docs/make.bat new file mode 100644 index 0000000..ac34ccd --- /dev/null +++ b/Docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=Tapeti + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/Docs/scripting.rst b/Docs/scripting.rst new file mode 100644 index 0000000..10b92b9 --- /dev/null +++ b/Docs/scripting.rst @@ -0,0 +1,117 @@ +Scripting +========= + +All functionality introduced by G940LEDControl is described in the :doc:`scriptingreference`. For more information about Lua in general, please refer to the `Lua 5.2 Reference Manual `_. + +This guide will walk through how Lua scripting works in G940LEDControl. To avoid confusion when talking about functions in this context they will be referred to as 'button functions' and 'Lua functions'. + + +Script locations +---------------- +The default scripts included with G940LEDControl can be found in the folder selected during installation, for example "C:\\Program Files (x86)\\G940 LED Control". In there you will find a Scripts\\FSX folder containing the Lua files. + +In addition scripts are loaded from your user data path. This folder is automatically created by G940LEDControl. To open the folder, type or paste "%APPDATA%\\G940LEDControl\\Scripts\\FSX" into a Windows Explorer address bar and press Enter. Scripts in this folder will not be overwritten when installing a new version. + + +Anatomy of a button function +---------------------------- +Let's take the Autopilot airspeed button function as an example, which at the time of writing looks like this: + +:: + + local strings = require './lib/strings' + + RegisterFunction( + { + uid = 'autoPilotAirspeed', + category = strings.Category.FSX.AutoPilot, + displayName = 'Autopilot airspeed', + states = { + on = { displayName = 'On', default = LEDColor.Green }, + off = { displayName = 'Off', default = LEDColor.Red }, + notAvailable = { displayName = 'Not available', default = LEDColor.Off } + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + autoPilotAvailable = { variable = 'AUTOPILOT AVAILABLE', type = SimConnectDataType.Bool }, + autoPilotAirspeed = { variable = 'AUTOPILOT AIRSPEED HOLD', type = SimConnectDataType.Bool } + }, + function(context, data) + if data.autoPilotAvailable then + if data.autoPilotAirspeed then + SetState(context, 'on') + else + SetState(context, 'off') + end + else + SetState(context, 'notAvailable') + end + end) + end + ) + +Using anonymous functions like this to implement the various callbacks results in compact code, which can arguably be more difficult to read. For clarity let's expand it first. The following example works exactly the same: + +:: + + local strings = require './lib/strings' + + local function variablesChanged(context, data) + if data.autoPilotAvailable then + if data.autoPilotAirspeed then + SetState(context, 'on') + else + SetState(context, 'off') + end + else + SetState(context, 'notAvailable') + end + end + + local function setup(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + autoPilotAvailable = { variable = 'AUTOPILOT AVAILABLE', type = SimConnectDataType.Bool }, + autoPilotAirspeed = { variable = 'AUTOPILOT AIRSPEED HOLD', type = SimConnectDataType.Bool } + }, + variablesChanged) + end + + + RegisterFunction( + { + uid = 'autoPilotAirspeed', + category = strings.Category.FSX.AutoPilot, + displayName = 'Autopilot airspeed', + states = { + on = { displayName = 'On', default = LEDColor.Green }, + off = { displayName = 'Off', default = LEDColor.Red }, + notAvailable = { displayName = 'Not available', default = LEDColor.Off } + } + }, + setup) + + +So what's happening? When the script is loaded it is automatically run. At this time you should call :ref:`ref-registerfunction` for each button function you want to be visible in G940LEDControl. :ref:`ref-registerfunction` accepts two parameters: a table which describes the button function you want to add, and a Lua function to be called when the button function is assigned to a button. + +Every button function must have a unique 'uid'. It is used to save and load profiles and should therefore not be changed once in use. The category and displayName are only used in the main and button function selection screens and can be freely changed. + +A button function must also have one or more states. Each state has a key which, like the 'uid', is used to save and load profiles and should also not be changed once in use. A default :ref:`LED color ` can also be set, which sets the initial value in the selection screen when assigning it to a button: + +.. image:: autoPilotAirspeedStates.png + + +Setup function +~~~~~~~~~~~~~~ + +As soon as the button function is attached to one of the buttons the setup function passed to :ref:`ref-registerfunction` is called. It receives a 'context' parameter, the contents of which are not useable by the script directly, but which you need to pass along to for example :ref:`ref-setstate` later on so that it knows which button function's state needs to be changed. + +In the above example the first thing we do is to set the default state using :ref:`ref-setstate`. The second parameter is a string containing the key of one of the states as defined in the :ref:`ref-registerfunction` call. + +After that you will normally call one of the built-in Lua functions to be notified of certain events. At the time of writing you can either call :ref:`ref-ontimer` to perform checks on a regular interval or, more common in the case of FSX, :ref:`ref-onsimconnect` to be notified when one or more of the `simulation variables `_ change. \ No newline at end of file diff --git a/Docs/scriptingreference.rst b/Docs/scriptingreference.rst new file mode 100644 index 0000000..487f709 --- /dev/null +++ b/Docs/scriptingreference.rst @@ -0,0 +1,329 @@ +Scripting reference +=================== + +G940LEDControl uses Lua 5.2. Please refer to the `Lua 5.2 Reference Manual `_ for more information. + +.. contents:: + :local: + +Global functions +---------------- + +.. _ref-log: + +Log functions +~~~~~~~~~~~~~ + +:: + + Log.Verbose(msg, ...) + Log.Info(msg, ...) + Log.Warning(msg, ...) + Log.Error(msg, ...) + +Writes a message to the application log. If you pass more than one parameter, they will be concatenated in the log message separated by spaces. The parameters do not need to be strings, other simple types will be converted and tables will be output as '{ key = value, ... }'. + +The application log can be opened on the Configuration tab of the main screen. + +.. _ref-registerfunction: + +RegisterFunction +~~~~~~~~~~~~~~~~ +:: + + RegisterFunction(info, setupCallback) + +Registers a button function. + +**Parameters** + +| **info**: table +| A Lua table describing the function. The following keys are recognized: +| +| **uid**: string +| *Required.* A unique ID for this function. Used to save and load profiles. +| +| **category**: string +| The category under which this function is grouped in the button function selection screen. +| +| **displayName**: string +| The name of the function which is shown in the main screen and button function selection screen. +| +| **states**: table +| A table of states supported by this function. +| Each state has it's own unique key and a table describing the state. The following keys are recognized for the table: +| +| **displayName**: string +| The name of the state which is shown in the button function selection screen. +| +| **default**: string +| The default color and/or animation assigned to the state when it is first selected. See :ref:`ref-ledcolor` for a list of valid values. +| +| **order**: number (optional) +| Specifies the order in which the state is shown in the button function selection screen. If not specified, defaults to 0. States with an equal order are sorted alphabetically. +| +| **setupCallback**: function +| A Lua function which is called when the button function is configured. Please note that if a button function is linked to multiple G940 throttle buttons, setupCallback is called multiple times, so be careful with variables which are outside of the setupCallback's scope (global or script-local)! +| +| setupCallback is passed a single parameter 'context'. +| + +**Example** +:: + + RegisterFunction( + { + uid = 'autoPilotAirspeed', + category = strings.Category.FSX.AutoPilot, + displayName = 'Autopilot airspeed', + states = { + on = { displayName = 'On', default = LEDColor.Green }, + off = { displayName = 'Off', default = LEDColor.Red }, + notAvailable = { displayName = 'Not available', default = LEDColor.Off } + } + }, + function(context) + -- implementation of setupCallback + end) + +.. _ref-setstate: + +SetState +~~~~~~~~ +:: + + SetState(context, newState) + +Sets the current state of a button function. + +**Parameters** + +| **context** +| The context parameter as passed to setupCallback which determines the button function to be updated. +| +| **newState**: string +| The new state. Must be the name of a state key as passed to :ref:`ref-registerfunction`. +| + +**Example** +:: + + SetState(context, 'on') + + +.. _ref-onsimconnect: + +OnSimConnect +~~~~~~~~~~~~ +:: + + OnSimConnect(context, variables, variablesChangedCallback) + +Registers a Lua function to be called when the specified SimConnect variable(s) change. For a list of variables please refer to `Simulation variables `_. + +**Parameters** + +| **context** +| The context parameter as passed to setupCallback. +| +| **variables**: table +| A table containing information about the simulation variables you want to monitor. Each key will be reflected in the 'data' table passed to the variablesChangedCallback. Each value is a Lua table describing the variable. +| +| **variable**: string +| The name of the variable as described in `Simulation variables `_. +| +| **type**: string +| One of the :ref:`ref-simconnectdatatype` values. +| +| **units**: string +| If relevant to the variable, one of the `Units of Measurement `_ supported by SimConnect. For example, 'percent'. If type is SimConnectDataType.Bool, this will be automatically set to 'bool'. +| +| **variablesChangedCallback**: function +| A Lua function which is called when the variable's value changes. It receives 2 parameters: 'context' and 'data'. The data parameter is a Lua table where each key corresponds to a variable defined in the 'variables' parameter and it's value is the current value of the simulation variable. +| + +**Example** + +:: + + OnSimConnect(context, + { + autoPilotAvailable = { variable = 'AUTOPILOT AVAILABLE', type = SimConnectDataType.Bool }, + autoPilotAirspeed = { variable = 'AUTOPILOT AIRSPEED HOLD', type = SimConnectDataType.Bool } + }, + function(context, data) + if data.autoPilotAvailable then + if data.autoPilotAirspeed then + SetState(context, 'on') + else + SetState(context, 'off') + end + else + SetState(context, 'notAvailable') + end + end) + + +.. _ref-ontimer: + +OnTimer +~~~~~~~ +:: + + OnTimer(context, interval, timerCallback) + +Registers a Lua function to be called when the specified interval elapses. + +**Parameters** + +| **context** +| The context parameter as passed to setupCallback. +| +| **interval** +| The interval between calls to timerCallback in milliseconds. At the time of writing the minimum value is 100 milliseconds. +| +| **timerCallback** +| A Lua function which is called when the interval elapses. It is passed a single parameter 'context'. +| + +**Example** + +:: + + OnTimer(context, 1000, + function(context) + if FSXWindowVisible('ATC Menu') then + SetState(context, 'visible') + else + SetState(context, 'hidden') + end + end) + + + +.. _ref-windowvisible: + +WindowVisible +~~~~~~~~~~~~~ + +Checks if a window is currently visible. This is a thin wrapper around the FindWindow/FindWindowEx/IsWindowVisible Windows API. In the context of FSX panels you are probably looking for :ref:`ref-fsxwindowvisible`. + +All parameters are optional, but at least one parameter is required. To skip a parameter simply pass nil instead. + +To get a window's class name, use a tool like `Greatis Windowse `_. + +**Parameters** + +| **className** +| The window class name of the window +| +| **title** +| The title / caption / text of the window +| +| **parentClassName** +| The parent window's class name. If specified, the first two parameters are considered to be a child window of this parent. +| +| **parentTitle** +| The parent window's title / caption / text. If specified, the first two parameters are considered to be a child window of this parent. +| + +.. _ref-fsxwindowvisible: + +FSXWindowVisible +~~~~~~~~~~~~~~~~ + +Checks if an FSX window is currently visible. Uses WindowVisible as a workaround because SimConnect does not expose this information directly. + +**Parameters** + +| **title** +| The title of the panel. +| + +Checks for both docked and undocked windows. Equal to: + +:: + + WindowVisible('FS98CHILD', title, 'FS98MAIN') or WindowVisible('FS98FLOAT', title) + + + +Global variables +---------------- + +.. _ref-ledcolor: + +LEDColor +~~~~~~~~ + +**Keys** + +- Off +- Green +- Amber +- Red +- FlashingGreenFast +- FlashingGreenNormal +- FlashingAmberFast +- FlashingAmberNormal +- FlashingRedFast +- FlashingRedNormal + +The 'Fast' flashing versions stay on and off for half a second, the 'Normal' version for 1 second. + +**Example** + +:: + + { default = LEDColor.Green } + + +.. _ref-simconnectdatatype: + +SimConnectDataType +~~~~~~~~~~~~~~~~~~ + +**Keys** + +- Float64 +- Float32 +- Int64 +- Int32 +- String +- Bool +- XYZ +- LatLonAlt +- Waypoint + +The XYZ, LatLonAlt and Waypoint data types will return a table in the 'data' parameter for the OnSimConnect callback with the following keys: + +**XYZ** + +- X +- Y +- Z + +**LatLonAlt** + +- Latitude +- Longitude +- Altitude + +**Waypoint** + +- Latitude +- Longitude +- Altitude +- KtsSpeed +- PercentThrottle +- Flags + +The Flags value is a table containing the following keys, where each is a boolean: + +- SpeedRequested +- ThrottleRequested +- ComputeVerticalSpeed +- IsAGL +- OnGround +- Reverse +- WrapToFirst \ No newline at end of file diff --git a/G940LEDControl/Bin/lua52.dll b/G940LEDControl/Bin/lua52.dll new file mode 100644 index 0000000..d5c63a5 Binary files /dev/null and b/G940LEDControl/Bin/lua52.dll differ diff --git a/G940LEDControl/DelphiLua/Lua.API.pas b/G940LEDControl/DelphiLua/Lua.API.pas new file mode 100644 index 0000000..d10642a --- /dev/null +++ b/G940LEDControl/DelphiLua/Lua.API.pas @@ -0,0 +1,767 @@ +{ + Header for Lua 5.2.1 Binaries DLL + http://luabinaries.sourceforge.net/ + + Delphi conversion by M. van Renswoude, April 2014: + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +} +unit Lua.API; + +interface +uses + System.SysUtils; + + +const + LUA_VERSION_MAJOR = '5'; + LUA_VERSION_MINOR = '2'; + LUA_VERSION_NUM = 502; + LUA_VERSION_RELEASE = '1'; + + LUA_VERSION_ = 'Lua ' + LUA_VERSION_MAJOR + '.' + LUA_VERSION_MINOR; + LUA_RELEASE = LUA_VERSION_ + '.' + LUA_VERSION_RELEASE; + LUA_COPYRIGHT = LUA_RELEASE + ' Copyright (C) 1994-2012 Lua.org, PUC-Rio'; + LUA_AUTHORS = 'R. Ierusalimschy, L. H. de Figueiredo, W. Celes'; + + + { mark for precompiled code ('Lua') } + LUA_SIGNATURE = #33'Lua'; + + { option for multiple returns in 'lua_pcall' and 'lua_call' } + LUA_MULTRET = -1; + + { reserve some space for error handling } + LUAI_MAXSTACK = 1000000; + LUAI_FIRSTPSEUDOIDX = (-LUAI_MAXSTACK - 1000); + + { pseudo-indices } + LUA_REGISTRYINDEX = LUAI_FIRSTPSEUDOIDX; + + function lua_upvalueindex(idx: Integer): Integer; inline; + +const + { thread status } + LUA_OK = 0; + LUA_YIELD_ = 1; + LUA_ERRRUN = 2; + LUA_ERRSYNTAX = 3; + LUA_ERRMEM = 4; + LUA_ERRGCMM = 5; + LUA_ERRERR = 6; + + +type + size_t = NativeUint; + psize_t = ^size_t; + + lua_State = type Pointer; + lua_CFunction = function(L: lua_State): Integer; cdecl; + + { functions that read/write blocks when loading/dumping Lua chunks } + lua_Reader = function(L: lua_State; ud: Pointer; var sz: size_t): PAnsiChar; cdecl; + lua_Writer = function(L: lua_State; p: Pointer; sz: size_t; ud: Pointer): Integer; cdecl; + + { prototype for memory-allocation functions } + lua_Alloc = function(ud, ptr: Pointer; osize, nsize: size_t): Pointer; cdecl; + +const + { basic types } + LUA_TNONE = (-1); + + LUA_TNIL = 0; + LUA_TBOOLEAN = 1; + LUA_TLIGHTUSERDATA = 2; + LUA_TNUMBER = 3; + LUA_TSTRING = 4; + LUA_TTABLE = 5; + LUA_TFUNCTION = 6; + LUA_TUSERDATA = 7; + LUA_TTHREAD = 8; + + LUA_NUMTAGS = 9; + + { minimum Lua stack available to a C function } + LUA_MINSTACK = 20; + + + { predefined values in the registry } + LUA_RIDX_MAINTHREAD = 1; + LUA_RIDX_GLOBALS = 2; + LUA_RIDX_LAST = LUA_RIDX_GLOBALS; + + +type + { type of numbers in Lua } + lua_Number = type Double; + + { type for integer functions } + lua_Integer = type Integer; + + { unsigned integer type } + lua_Unsigned = type Cardinal; + + +var + { state manipulation } + lua_newstate: function(f: lua_Alloc; ud: Pointer): lua_State; cdecl; + lua_close: procedure(L: lua_State); cdecl; + lua_newthread: function(L: lua_State): lua_State; cdecl; + + lua_atpanic: function(L: lua_State; panicf: lua_CFunction): lua_CFunction; cdecl; + lua_version: function(L: lua_State): lua_Number; cdecl; + + { basic stack manipulation } + lua_absindex: function(L: lua_State; idx: Integer): Integer; cdecl; + lua_gettop: function(L: lua_State): Integer; cdecl; + + lua_settop: procedure(L: lua_State; idx: Integer); cdecl; + lua_pushvalue: procedure(L: lua_State; idx: Integer); cdecl; + lua_remove: procedure(L: lua_State; idx: Integer); cdecl; + lua_insert: procedure(L: lua_State; idx: Integer); cdecl; + lua_replace: procedure(L: lua_State; idx: Integer); cdecl; + lua_copy: procedure(L: lua_State; fromidx, toidx: Integer); cdecl; + lua_checkstack: function(L: lua_State; sz: Integer): Integer; cdecl; + + lua_xmove: procedure(from: lua_State; _to: lua_State; n: Integer); cdecl; + + { access functions (stack -> C) } + lua_isnumber: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_isstring: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_iscfunction: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_isuserdata: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_type: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_typename: function (L: lua_State; tp: Integer): PAnsiChar; cdecl; + lua_tonumberx: function (L: lua_State; idx: Integer; isnum: PInteger): lua_Number; cdecl; + lua_tointegerx: function (L: lua_State; idx: Integer; isnum: PInteger): lua_Integer; cdecl; + lua_tounsignedx: function (L: lua_State; idx: Integer; isnum: PInteger): lua_Unsigned; cdecl; + lua_toboolean: function (L: lua_State; idx: Integer): Integer; cdecl; + lua_tolstring: function(L: lua_State; idx: Integer; len: psize_t): PAnsiChar; cdecl; + lua_rawlen: function (L: lua_State; idx: Integer): size_t; cdecl; + lua_tocfunction: function (L: lua_State; idx: Integer): lua_CFunction; cdecl; + lua_touserdata: function (L: lua_State; idx: Integer): Pointer; cdecl; + lua_tothread: function (L: lua_State; idx: Integer): lua_State; cdecl; + lua_topointer: function (L: lua_State; idx: Integer): Pointer; cdecl; + + +const + { Comparison and arithmetic functions } + LUA_OPADD = 0; { ORDER TM } + LUA_OPSUB = 1; + LUA_OPMUL = 2; + LUA_OPDIV = 3; + LUA_OPMOD = 4; + LUA_OPPOW = 5; + LUA_OPUNM = 6; + + +var + lua_arith: procedure(L: lua_State; op: Integer); cdecl; + + +const + LUA_OPEQ = 0; + LUA_OPLT = 1; + LUA_OPLE = 2; + + +var + lua_rawequal: function(L: lua_State; idx1, idx2: Integer): Integer; cdecl; + lua_compare: function(L: lua_State; idx1, idx2, op: Integer): Integer; cdecl; + + + { push functions (C -> stack) } + lua_pushnil: procedure(L: lua_State); cdecl; + lua_pushnumber: procedure(L: lua_State; n: lua_Number); cdecl; + lua_pushinteger: procedure(L: lua_State; n: lua_Integer); cdecl; + lua_pushunsigned: procedure(L: lua_State; n: lua_Unsigned); cdecl; + lua_pushlstring: function (L: lua_State; s: PAnsiChar; l_: size_t): PAnsiChar; cdecl; + lua_pushstring: function (L: lua_State; s: PAnsiChar): PAnsiChar; cdecl; + lua_pushvfstring: function (L: lua_State; fmt: PAnsiChar; argp: Pointer): PAnsiChar; cdecl; + lua_pushfstring: function (L: lua_State; fmt: PAnsiChar; argp: Pointer): PAnsiChar; cdecl; + lua_pushcclosure: procedure(L: lua_State; fn: lua_CFunction; n: Integer); cdecl; + lua_pushboolean: procedure(L: lua_State; b: Integer); cdecl; + lua_pushlightuserdata: procedure(L: lua_State; p: Pointer); cdecl; + lua_pushthread: function (L: lua_State): Integer; cdecl; + + { get functions (Lua -> stack) } + lua_getglobal: procedure(L: lua_State; value: PAnsiChar); cdecl; + lua_gettable: procedure(L: lua_State; idx: Integer); cdecl; + lua_getfield: procedure(L: lua_State; idx: Integer; k: PAnsiChar); cdecl; + lua_rawget: procedure(L: lua_State; idx: Integer); cdecl; + lua_rawgeti: procedure(L: lua_State; idx, n: Integer); cdecl; + lua_rawgetp: procedure(L: lua_State; idx: Integer; p: Pointer); cdecl; + lua_createtable: procedure(L: lua_State; narr: Integer; nrec: Integer); cdecl; + lua_newuserdata: procedure(L: lua_State; sz: size_t); cdecl; + lua_getmetatable: function(L: lua_State; objindex: Integer): Integer; cdecl; + lua_getuservalue: procedure(L: lua_State; idx: Integer); cdecl; + + { set functions (stack -> Lua) } + lua_setglobal: procedure(L: lua_State; value: PAnsiChar); cdecl; + lua_settable: procedure(L: lua_State; idx: Integer); cdecl; + lua_setfield: procedure(L: lua_State; idx: Integer; k: PAnsiChar); cdecl; + lua_rawset: procedure(L: lua_State; idx: Integer); cdecl; + lua_rawseti: procedure(L: lua_State; idx, n: Integer); cdecl; + lua_rawsetp: procedure(L: lua_State; idx: Integer; p: Pointer); cdecl; + lua_setmetatable: function(L: lua_State; objindex: Integer): Integer; cdecl; + lua_setuservalue: procedure(L: lua_State; idx: Integer); cdecl; + + + { 'load' and 'call' functions (load and run Lua code) } + lua_callk: procedure(L: lua_State; nargs, nresults, ctx: Integer; k: lua_CFunction); cdecl; + lua_getctx: function(L: lua_State; var ctx: Integer): Integer; cdecl; + lua_pcallk: function(L: lua_State; nargs, nresults, errfunc, ctx: Integer; k: lua_CFunction): Integer; cdecl; + + lua_load: function(L: lua_State; reader: lua_Reader; dt: Pointer; chunkname, mode: PAnsiChar): Integer; cdecl; + lua_dump: function(L: lua_State; writer: lua_Writer; data: Pointer): Integer; cdecl; + + + procedure lua_call(L: lua_State; nargs, nresults: Integer); inline; + function lua_pcall(L: lua_State; nargs, nresults, errfunc: Integer): Integer; inline; + + +var + { coroutine functions } + lua_yieldk: function(L: lua_State; nresults, ctx: Integer; k: lua_CFunction): Integer; cdecl; + lua_resume: function(L, from: lua_State; nargs: Integer): Integer; cdecl; + lua_status: function(L: lua_State): Integer; cdecl; + + function lua_yield(L: lua_State; nresults: Integer): Integer; inline; + + +const + { garbage-collection function and options } + LUA_GCSTOP = 0; + LUA_GCRESTART = 1; + LUA_GCCOLLECT = 2; + LUA_GCCOUNT = 3; + LUA_GCCOUNTB = 4; + LUA_GCSTEP = 5; + LUA_GCSETPAUSE = 6; + LUA_GCSETSTEPMU = 7; + LUA_GCSETMAJORIN = 8; + LUA_GCISRUNNING = 9; + LUA_GCGEN = 0; + LUA_GCINC = 1; + +var + lua_gc: function(L: lua_State; what, data: Integer): Integer; cdecl; + + +var + { miscellaneous functions } + lua_error: function(L: lua_State): Integer; cdecl; + lua_next: function(L: lua_State; idx: Integer): Integer; cdecl; + + lua_concat: procedure(L: lua_State; n: Integer); cdecl; + lua_len: procedure(L: lua_State; idx: Integer); cdecl; + + lua_getallocf: function(L: lua_State; ud: Pointer): lua_Alloc; cdecl; + lua_setallocf: procedure(L: lua_State; f: lua_Alloc; ud: Pointer); cdecl; + + + { some useful macros } + function lua_tonumber(L: lua_State; idx: Integer): lua_Number; inline; + function lua_tointeger(L: lua_State; idx: Integer): lua_Integer; inline; + function lua_tounsigned(L: lua_State; idx: Integer): lua_Unsigned; inline; + + procedure lua_pop(L: lua_State; n: Integer); inline; + procedure lua_newtable(L: lua_State); inline; + procedure lua_register(L: lua_State; name: PAnsiChar; f: lua_CFunction); inline; + procedure lua_pushcfunction(L: lua_State; f: lua_CFunction); inline; + + function lua_isfunction(L: lua_State; n: Integer): Boolean; inline; + function lua_istable(L: lua_State; n: Integer): Boolean; inline; + function lua_islightuserdata(L: lua_State; n: Integer): Boolean; inline; + function lua_isnil(L: lua_State; n: Integer): Boolean; inline; + function lua_isboolean(L: lua_State; n: Integer): Boolean; inline; + function lua_isthread(L: lua_State; n: Integer): Boolean; inline; + function lua_isnone(L: lua_State; n: Integer): Boolean; inline; + function lua_isnoneornil(L: lua_State; n: Integer): Boolean; inline; + function lua_pushliteral(L: lua_State; const s: AnsiString): PAnsiChar; inline; + + procedure lua_pushglobaltable(L: lua_State); inline; + function lua_tostring(L: lua_State; idx: Integer): PAnsiChar; inline; + + +const + {====================================================================== + Debug API + =======================================================================} + + { Event codes } + LUA_HOOKCALL = 0; + LUA_HOOKRET = 1; + LUA_HOOKLINE = 2; + LUA_HOOKCOUNT = 3; + LUA_HOOKTAILCALL = 4; + + + { Event masks } + LUA_MASKCALL = (1 shl LUA_HOOKCALL); + LUA_MASKRET = (1 shl LUA_HOOKRET); + LUA_MASKLINE = (1 shl LUA_HOOKLINE); + LUA_MASKCOUNT = (1 shl LUA_HOOKCOUNT); + + +const + LUA_IDSIZE = 60; + + +type + lua_Debug = record + event: Integer; + name: PAnsiChar; + namewhat: PAnsiChar; // 'global', 'local', 'field', 'method' + what: PAnsiChar; // 'Lua', 'C', 'main', 'tail' + source: PAnsiChar; + currentline: Integer; + linedefined: Integer; + lastlinedefined: Integer; + nups: Byte; + nparams: Byte; + isvararg: Byte; + istailcall: Byte; + short_src: array[0..LUA_IDSIZE - 1] of AnsiChar; + i_ci: Integer; + end; + + { Functions to be called by the debugger in specific events } + lua_Hook = procedure(L: lua_State; var ar: lua_Debug); cdecl; + + +var + lua_getstack: function(L: lua_State; level: Integer; var ar: lua_Debug): Integer; cdecl; + lua_getinfo: function(L: lua_State; what: PAnsiChar; var ar: lua_Debug): Integer; cdecl; + + lua_getlocal: function(L: lua_State; var ar: lua_Debug; n: Integer): PAnsiChar; cdecl; + lua_setlocal: function(L: lua_State; var ar: lua_Debug; n: Integer): PAnsiChar; cdecl; + lua_getupvalue: function(L: lua_State; funcindex, n: Integer): PAnsiChar; cdecl; + lua_setupvalue: function(L: lua_State; funcindex, n: Integer): PAnsiChar; cdecl; + + lua_upvalueid: function(L: lua_State; fidx, n: Integer): Pointer; cdecl; + lua_upvaluejoin: procedure(L: lua_State; fidx1, n1, fidx2, n2: Integer); + + lua_sethook: function(L: lua_State; func: lua_Hook; mask, count: Integer): Integer; cdecl; + lua_gethook: function(L: lua_State): lua_Hook; cdecl; + lua_gethookmask: function(L: lua_State): Integer; cdecl; + lua_gethookcount: function(L: lua_State): Integer; cdecl; + + {====================================================================== } + + +const + LUA_COLIBNAME = 'coroutine'; + LUA_TABLIBNAME = 'table'; + LUA_IOLIBNAME = 'io'; + LUA_OSLIBNAME = 'os'; + LUA_STRLIBNAME = 'string'; + LUA_BITLIBNAME = 'bit32'; + LUA_MATHLIBNAME = 'math'; + LUA_DBLIBNAME = 'debug'; + LUA_LOADLIBNAME = 'package'; + + +var + { lualib } + luaopen_base: function(L: lua_State): Integer; cdecl; + luaopen_coroutine: function(L: lua_State): Integer; cdecl; + luaopen_table: function(L: lua_State): Integer; cdecl; + luaopen_io: function(L: lua_State): Integer; cdecl; + luaopen_os: function(L: lua_State): Integer; cdecl; + luaopen_string: function(L: lua_State): Integer; cdecl; + luaopen_bit32: function(L: lua_State): Integer; cdecl; + luaopen_math: function(L: lua_State): Integer; cdecl; + luaopen_debug: function(L: lua_State): Integer; cdecl; + luaopen_package: function(L: lua_State): Integer; cdecl; + + { open all previous libraries } + luaL_openlibs: procedure(L: lua_State); cdecl; + luaL_requiref: procedure(L: lua_State; modname: PAnsiChar; openf: lua_CFunction; glb: Integer); cdecl; + + + +type + luaL_Reg = record + name: PAnsiChar; + func: lua_CFunction; + end; + PluaL_Reg = ^luaL_Reg; + +var + luaL_setfuncs: procedure(L: lua_State; luaL_Reg: PluaL_Reg; nup: Integer); cdecl; + + procedure luaL_where(L: lua_State; level: Integer); + function luaL_error(L: lua_State; fmt: PAnsiChar; argp: Pointer): Integer; + + + +const + DefaultLuaLibName = 'lua' + LUA_VERSION_MAJOR + LUA_VERSION_MINOR + '.dll'; + + procedure LoadLuaLib(const AFileName: string = DefaultLuaLibName); + procedure UnloadLuaLib; + + function LuaLibLoaded: Boolean; + + function DefaultLuaAlloc(ud, ptr: Pointer; osize, nsize: size_t): Pointer; cdecl; + + +implementation +uses + System.Generics.Collections, + Winapi.Windows; + +var + LuaLibHandle: THandle; + LuaFunctions: TList; + + +function DefaultLuaAlloc(ud, ptr: Pointer; osize, nsize: size_t): Pointer; +begin + if (nsize = 0) then + begin + FreeMemory(ptr); + Result := nil; + end else + Result := ReallocMemory(ptr, nsize); +end; + + +procedure LoadLuaLib(const AFileName: string = DefaultLuaLibName); + + procedure Load(var AVariable: Pointer; const AName: string); + begin + AVariable := GetProcAddress(LuaLibHandle, PChar(AName)); + LuaFunctions.Add(@AVariable); + end; + + +begin + UnloadLuaLib; + + LuaLibHandle := SafeLoadLibrary(AFileName); + if LuaLibHandle = 0 then + RaiseLastOSError; + + if not Assigned(LuaFunctions) then + LuaFunctions := TList.Create(); + + Load(@lua_newstate, 'lua_newstate'); + Load(@lua_close, 'lua_close'); + Load(@lua_newthread, 'lua_newthread'); + + Load(@lua_atpanic, 'lua_atpanic'); + Load(@lua_version, 'lua_version'); + + Load(@lua_absindex, 'lua_absindex'); + Load(@lua_gettop, 'lua_gettop'); + Load(@lua_settop, 'lua_settop'); + Load(@lua_pushvalue, 'lua_pushvalue'); + Load(@lua_remove, 'lua_remove'); + Load(@lua_insert, 'lua_insert'); + Load(@lua_replace, 'lua_replace'); + Load(@lua_copy, 'lua_copy'); + Load(@lua_checkstack, 'lua_checkstack'); + Load(@lua_xmove, 'lua_xmove'); + + Load(@lua_isnumber, 'lua_isnumber'); + Load(@lua_isstring, 'lua_isstring'); + Load(@lua_iscfunction, 'lua_iscfunction'); + Load(@lua_isuserdata, 'lua_isuserdata'); + Load(@lua_type, 'lua_type'); + Load(@lua_typename, 'lua_typename'); + Load(@lua_tonumberx, 'lua_tonumberx'); + Load(@lua_tointegerx, 'lua_tointegerx'); + Load(@lua_tounsignedx, 'lua_tounsignedx'); + Load(@lua_toboolean, 'lua_toboolean'); + Load(@lua_tolstring, 'lua_tolstring'); + Load(@lua_rawlen, 'lua_rawlen'); + Load(@lua_tocfunction, 'lua_tocfunction'); + Load(@lua_touserdata, 'lua_touserdata'); + Load(@lua_tothread, 'lua_tothread'); + Load(@lua_topointer, 'lua_topointer'); + + Load(@lua_arith, 'lua_arith'); + Load(@lua_rawequal, 'lua_rawequal'); + Load(@lua_compare, 'lua_compare'); + + Load(@lua_pushnil, 'lua_pushnil'); + Load(@lua_pushnumber, 'lua_pushnumber'); + Load(@lua_pushinteger, 'lua_pushinteger'); + Load(@lua_pushunsigned, 'lua_pushunsigned'); + Load(@lua_pushlstring, 'lua_pushlstring'); + Load(@lua_pushstring, 'lua_pushstring'); + Load(@lua_pushvfstring, 'lua_pushvfstring'); + Load(@lua_pushfstring, 'lua_pushfstring'); + Load(@lua_pushcclosure, 'lua_pushcclosure'); + Load(@lua_pushboolean, 'lua_pushboolean'); + Load(@lua_pushlightuserdata, 'lua_pushlightuserdata'); + Load(@lua_pushthread, 'lua_pushthread'); + + Load(@lua_getglobal, 'lua_getglobal'); + Load(@lua_gettable, 'lua_gettable'); + Load(@lua_getfield, 'lua_getfield'); + Load(@lua_rawget, 'lua_rawget'); + Load(@lua_rawgeti, 'lua_rawgeti'); + Load(@lua_rawgetp, 'lua_rawgetp'); + Load(@lua_newuserdata, 'lua_newuserdata'); + Load(@lua_getmetatable, 'lua_getmetatable'); + Load(@lua_getuservalue, 'lua_getuservalue'); + + Load(@lua_createtable, 'lua_createtable'); + Load(@lua_setglobal, 'lua_setglobal'); + Load(@lua_settable, 'lua_settable'); + Load(@lua_setfield, 'lua_setfield'); + + Load(@lua_rawset, 'lua_rawset'); + Load(@lua_rawseti, 'lua_rawseti'); + Load(@lua_rawsetp, 'lua_rawsetp'); + Load(@lua_setmetatable, 'lua_setmetatable'); + Load(@lua_setuservalue, 'lua_setuservalue'); + + Load(@lua_callk, 'lua_callk'); + Load(@lua_getctx, 'lua_getctx'); + Load(@lua_pcallk, 'lua_pcallk'); + + Load(@lua_yieldk, 'lua_yieldk'); + Load(@lua_resume, 'lua_resume'); + Load(@lua_status, 'lua_status'); + + Load(@lua_gc, 'lua_gc'); + + Load(@lua_load, 'lua_load'); + Load(@lua_dump, 'lua_dump'); + + Load(@lua_error, 'lua_error'); + Load(@lua_next, 'lua_next'); + + Load(@lua_concat, 'lua_concat'); + Load(@lua_len, 'lua_len'); + + Load(@lua_getallocf, 'lua_getallocf'); + Load(@lua_setallocf, 'lua_setallocf'); + + + Load(@lua_getstack, 'lua_getstack'); + Load(@lua_getinfo, 'lua_getinfo'); + + Load(@lua_getlocal, 'lua_getlocal'); + Load(@lua_setlocal, 'lua_setlocal'); + Load(@lua_getupvalue, 'lua_getupvalue'); + Load(@lua_setupvalue, 'lua_setupvalue'); + + Load(@lua_upvalueid, 'lua_upvalueid'); + Load(@lua_upvaluejoin, 'lua_upvaluejoin'); + + Load(@lua_sethook, 'lua_sethook'); + Load(@lua_gethook, 'lua_gethook'); + Load(@lua_gethookmask, 'lua_gethookmask'); + Load(@lua_gethookcount, 'lua_gethookcount'); + + Load(@luaopen_base, 'luaopen_base'); + Load(@luaopen_coroutine, 'luaopen_coroutine'); + Load(@luaopen_table, 'luaopen_table'); + Load(@luaopen_io, 'luaopen_io'); + Load(@luaopen_os, 'luaopen_os'); + Load(@luaopen_string, 'luaopen_string'); + Load(@luaopen_bit32, 'luaopen_bit32'); + Load(@luaopen_math, 'luaopen_math'); + Load(@luaopen_debug, 'luaopen_debug'); + Load(@luaopen_package, 'luaopen_package'); + + Load(@luaL_openlibs, 'luaL_openlibs'); + Load(@luaL_requiref, 'luaL_requiref'); + + Load(@luaL_setfuncs, 'luaL_setfuncs'); +end; + + +procedure UnloadLuaLib; +var + variable: PPointer; + +begin + if Assigned(LuaFunctions) then + begin + for variable in LuaFunctions do + variable^ := nil; + end; + + if LuaLibLoaded then + begin + FreeLibrary(LuaLibHandle); + LuaLibHandle := 0; + end; +end; + + +function LuaLibLoaded: Boolean; +begin + Result := (LuaLibHandle <> 0); +end; + + +{ Macros } +function lua_upvalueindex(idx: Integer): Integer; +begin + Result := (LUA_REGISTRYINDEX - idx); +end; + +procedure lua_call(L: lua_State; nargs, nresults: Integer); +begin + lua_callk(L, nargs, nresults, 0, nil); +end; + +function lua_pcall(L: lua_State; nargs, nresults, errfunc: Integer): Integer; +begin + Result := lua_pcallk(L, nargs, nresults, errfunc, 0, nil); +end; + +function lua_yield(L: lua_State; nresults: Integer): Integer; +begin + Result := lua_yieldk(L, nresults, 0, nil); +end; + +function lua_tonumber(L: lua_State; idx: Integer): lua_Number; +begin + Result := lua_tonumberx(L, idx, nil); +end; + +function lua_tointeger(L: lua_State; idx: Integer): lua_Integer; +begin + Result := lua_tointegerx(L, idx, nil); +end; + +function lua_tounsigned(L: lua_State; idx: Integer): lua_Unsigned; +begin + Result := lua_tounsignedx(L, idx, nil); +end; + +procedure lua_pop(L: lua_State; n: Integer); +begin + lua_settop(L, -(n) - 1); +end; + +procedure lua_newtable(L: lua_State); inline; +begin + lua_createtable(L, 0, 0); +end; + +procedure lua_register(L: lua_State; name: PAnsiChar; f: lua_CFunction); inline; +begin + lua_pushcfunction(L, f); + lua_setglobal(L, name); +end; + +procedure lua_pushcfunction(L: lua_State; f: lua_CFunction); +begin + lua_pushcclosure(L, f, 0); +end; + +function lua_isfunction(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TFUNCTION; +end; + +function lua_istable(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TTABLE; +end; + +function lua_islightuserdata(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TLIGHTUSERDATA; +end; + +function lua_isnil(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TNIL; +end; + +function lua_isboolean(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TBOOLEAN; +end; + +function lua_isthread(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TTHREAD; +end; + +function lua_isnone(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) = LUA_TNONE; +end; + +function lua_isnoneornil(L: lua_State; n: Integer): Boolean; +begin + Result := lua_type(L, n) <= 0; +end; + +function lua_pushliteral(L: lua_State; const s: AnsiString): PAnsiChar; +begin + Result := lua_pushlstring(L, PAnsiChar(s), Length(s)); +end; + +procedure lua_pushglobaltable(L: lua_State); +begin + lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); +end; + +function lua_tostring(L: lua_State; idx: Integer): PAnsiChar; +begin + Result := lua_tolstring(L, idx, nil); +end; + +procedure luaL_where(L: lua_State; level: Integer); +var + ar: lua_Debug; + msg: AnsiString; + +begin + if (lua_getstack(L, level, ar) <> 0) then // check function at level + begin + lua_getinfo(L, 'Sl', ar); // get info about it + if (ar.currentline > 0) then // is there info? + begin + msg := AnsiString(Format('%s:%d: ', [ar.short_src, ar.currentline])); + lua_pushlstring(L, PAnsiChar(msg), Length(msg)); + exit + end; + end; + lua_pushliteral(L, ''); // else, no information available... +end; + +function luaL_error(L: lua_State; fmt: PAnsiChar; argp: Pointer): Integer; +begin + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + lua_concat(L, 2); + Result := lua_error(L); +end; + + +initialization +finalization + UnloadLuaLib; + FreeAndNil(LuaFunctions); + +end. diff --git a/G940LEDControl/DelphiLua/Lua.pas b/G940LEDControl/DelphiLua/Lua.pas new file mode 100644 index 0000000..920260b --- /dev/null +++ b/G940LEDControl/DelphiLua/Lua.pas @@ -0,0 +1,2536 @@ +{ + Wrapper classes for Lua API + + Created by M. van Renswoude, April 2014: + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +} +unit Lua; + +interface +uses + System.Classes, + System.Generics.Collections, + System.Generics.Defaults, + System.Rtti, + System.SysUtils, + + Lua.API; + +type + ELuaException = class(Exception); + ELuaInitException = class(ELuaException); + ELuaUnsupportedParameterException = class(ELuaException); + ELuaUnsupportedVariableException = class(ELuaException); + ELuaNoFunctionException = class(ELuaException); + ELuaNativeCodeException = class(ELuaException); + + TLuaLibrary = (Base, Coroutine, Table, IO, OS, StringLib, Bit32, Math, Debug, Package, All); + TLuaLibraries = set of TLuaLibrary; + + TLuaDataType = (LuaNone, LuaNil, LuaNumber, LuaBoolean, LuaString, LuaTable, + LuaFunction, LuaUserData, LuaThread, LuaLightUserData); + + TLuaVariableType = (VariableNone, VariableBoolean, VariableInteger, + VariableNumber, VariableUserData, VariableString, + VariableTable, VariableFunction); + + ILuaTable = interface; + ILuaFunction = interface; + + + ILuaVariable = interface + ['{ADA0D4FB-F0FB-4493-8FEC-6FC92C80117F}'] + function GetVariableType: TLuaVariableType; + function GetDataType: TLuaDataType; + + function GetAsBoolean: Boolean; + function GetAsInteger: Integer; + function GetAsNumber: Double; + function GetAsUserData: Pointer; + function GetAsString: string; + function GetAsTable: ILuaTable; + function GetAsFunction: ILuaFunction; + + procedure SetAsBoolean(ABoolean: Boolean); + procedure SetAsInteger(AInteger: Integer); + procedure SetAsNumber(ANumber: Double); + procedure SetAsUserData(AUserData: Pointer); + procedure SetAsString(AString: string); + procedure SetAsTable(ATable: ILuaTable); + + property VariableType: TLuaVariableType read GetVariableType; + property DataType: TLuaDataType read GetDataType; + + property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean; + property AsInteger: Integer read GetAsInteger write SetAsInteger; + property AsNumber: Double read GetAsNumber write SetAsNumber; + property AsUserData: Pointer read GetAsUserData write SetAsUserData; + property AsString: string read GetAsString write SetAsString; + property AsTable: ILuaTable read GetAsTable write SetAsTable; + property AsFunction: ILuaFunction read GetAsFunction; + end; + + + TLuaImplicitVariable = record + Variable: ILuaVariable; + + class operator Implicit(AValue: ILuaVariable): TLuaImplicitVariable; + class operator Implicit(AValue: Boolean): TLuaImplicitVariable; + class operator Implicit(AValue: Integer): TLuaImplicitVariable; + class operator Implicit(AValue: Double): TLuaImplicitVariable; + class operator Implicit(AValue: Pointer): TLuaImplicitVariable; + class operator Implicit(const AValue: string): TLuaImplicitVariable; + class operator Implicit(AValue: ILuaTable): TLuaImplicitVariable; + class operator Implicit(AValue: TLuaImplicitVariable): ILuaVariable; + class operator Implicit(AValue: TLuaImplicitVariable): Boolean; + class operator Implicit(AValue: TLuaImplicitVariable): Integer; + class operator Implicit(AValue: TLuaImplicitVariable): Double; + class operator Implicit(AValue: TLuaImplicitVariable): Pointer; + class operator Implicit(AValue: TLuaImplicitVariable): string; + class operator Implicit(AValue: TLuaImplicitVariable): ILuaTable; + end; + + + TLuaKeyValuePair = record + Key: ILuaVariable; + Value: ILuaVariable; + end; + + + ILuaTableEnumerator = interface + ['{4C3F4E20-F9E7-42E6-9446-78C535AF2E30}'] + function GetCurrent: TLuaKeyValuePair; + function MoveNext: Boolean; + + property Current: TLuaKeyValuePair read GetCurrent; + end; + + + ILuaTable = interface + ['{57FD52A1-7D53-485B-A630-29841C498387}'] + function GetEnumerator: ILuaTableEnumerator; + + function HasValue(AKey: TLuaImplicitVariable): Boolean; + function GetValue(AKey: TLuaImplicitVariable): ILuaVariable; + procedure SetValue(AKey: TLuaImplicitVariable; AValue: TLuaImplicitVariable); + end; + + + TLuaTableEnumerator = class(TInterfacedObject, ILuaTableEnumerator) + private + FEnumerator: TEnumerator>; + public + constructor Create(AEnumerator: TEnumerator>); + destructor Destroy; override; + + { ILuaTableEnumerator } + function GetCurrent: TLuaKeyValuePair; + function MoveNext: Boolean; + + property Current: TLuaKeyValuePair read GetCurrent; + end; + + + TLuaVariableEqualityComparer = class(TInterfacedObject, IEqualityComparer) + public + { IEqualityComparer } + function Equals(const Left, Right: ILuaVariable): Boolean; reintroduce; + function GetHashCode(const Value: ILuaVariable): Integer; reintroduce; + end; + + + TLuaTable = class(TInterfacedObject, ILuaTable) + private + FTable: TDictionary; + public + constructor Create; + destructor Destroy; override; + + { ILuaTable } + function GetEnumerator: ILuaTableEnumerator; + + function HasValue(AKey: TLuaImplicitVariable): Boolean; + function GetValue(AKey: TLuaImplicitVariable): ILuaVariable; + procedure SetValue(AKey: TLuaImplicitVariable; AValue: TLuaImplicitVariable); + end; + + + ILuaParametersEnumerator = interface + function GetCurrent: ILuaVariable; + function MoveNext: Boolean; + property Current: ILuaVariable read GetCurrent; + end; + + + ILuaReadParameters = interface(ILuaVariable) + ['{FB611D9E-B51D-460B-B5AB-B567EF853222}'] + function GetCount: Integer; + function GetItem(Index: Integer): ILuaVariable; + + function GetEnumerator: ILuaParametersEnumerator; + function ToString: string; + + property Count: Integer read GetCount; + property Items[Index: Integer]: ILuaVariable read GetItem; default; + end; + + + ILuaWriteParameters = interface + ['{5CEEB16B-158E-44BE-8CAD-DC2C330A244A}'] + function GetCount: Integer; + + procedure Push(ABoolean: Boolean); overload; + procedure Push(AInteger: Integer); overload; + procedure Push(ANumber: Double); overload; + procedure Push(AUserData: Pointer); overload; + procedure Push(const AString: string); overload; + procedure Push(ATable: ILuaTable); overload; + + property Count: Integer read GetCount; + end; + + + TCustomLuaParameters = class(TInterfacedObject, ILuaVariable, ILuaReadParameters) + protected + function GetDefaultVariable: ILuaVariable; + public + { ILuaVariable } + function GetVariableType: TLuaVariableType; + function GetDataType: TLuaDataType; + + function GetAsBoolean: Boolean; + function GetAsInteger: Integer; + function GetAsNumber: Double; + function GetAsUserData: Pointer; + function GetAsString: string; + function GetAsTable: ILuaTable; + function GetAsFunction: ILuaFunction; + + procedure SetAsBoolean(ABoolean: Boolean); + procedure SetAsInteger(AInteger: Integer); + procedure SetAsNumber(ANumber: Double); + procedure SetAsUserData(AUserData: Pointer); + procedure SetAsString(AString: string); + procedure SetAsTable(ATable: ILuaTable); + + { ILuaReadParameters } + function GetCount: Integer; virtual; abstract; + function GetItem(Index: Integer): ILuaVariable; virtual; abstract; + + function GetEnumerator: ILuaParametersEnumerator; + function ToString: string; override; + end; + + + TLuaParameters = class(TCustomLuaParameters, ILuaWriteParameters) + private + FParameters: TList; + public + constructor Create; + destructor Destroy; override; + + function GetCount: Integer; override; + function GetItem(Index: Integer): ILuaVariable; override; + + { ILuaWriteParameters } + procedure Push(ABoolean: Boolean); overload; + procedure Push(AInteger: Integer); overload; + procedure Push(ANumber: Double); overload; + procedure Push(AUserData: Pointer); overload; + procedure Push(const AString: string); overload; + procedure Push(ATable: ILuaTable); overload; + end; + + + ILuaFunction = interface + ['{1BE5E470-0318-410E-8D5B-94BFE04A3DBE}'] + function Call(): ILuaReadParameters; overload; + function Call(AParameters: array of const): ILuaReadParameters; overload; + function Call(AParameters: ILuaReadParameters): ILuaReadParameters; overload; + end; + + + ILuaContext = interface + ['{1F999593-E3D1-4195-9463-A42025AE9830}'] + function GetParameters: ILuaReadParameters; + function GetResult: ILuaWriteParameters; + + property Parameters: ILuaReadParameters read GetParameters; + property Result: ILuaWriteParameters read GetResult; + end; + + + TLuaCFunction = reference to procedure(Context: ILuaContext); + TLuaCMethod = procedure(Context: ILuaContext) of object; + TLuaPushFunction = reference to procedure(AFunction: TLuaCFunction); + + + TCustomLuaRegistration = class(TObject) + private + FName: string; + protected + property Name: string read FName write FName; + public + constructor Create(const AName: string); + + procedure Apply(AState: lua_State; APushFunction: TLuaPushFunction); virtual; abstract; + end; + + + TLuaFunctionRegistration = class(TCustomLuaRegistration) + private + FCallback: TLuaCFunction; + protected + property Callback: TLuaCFunction read FCallback; + public + constructor Create(const AName: string; ACallback: TLuaCFunction); + + procedure Apply(AState: lua_State; APushFunction: TLuaPushFunction); override; + end; + + + TLuaFunctionTable = TDictionary; + + TLuaTableRegistration = class(TCustomLuaRegistration) + private + FFunctionTable: TLuaFunctionTable; + protected + property FunctionTable: TLuaFunctionTable read FFunctionTable; + public + constructor Create(const AName: string); + destructor Destroy; override; + + procedure RegisterFunction(const AName: string; AFunction: TLuaCFunction); virtual; + procedure Apply(AState: lua_State; APushFunction: TLuaPushFunction); override; + end; + + + TLuaRegistrationList = TObjectList; + TLuaRegisteredFunctionDictionary = TDictionary; + + + TLuaScript = class(TObject) + private + FStream: TStream; + FStreamOwnership: TStreamOwnership; + FBuffer: PAnsiChar; + public + constructor Create(const AData: string); overload; + constructor Create(const AStream: TStream; AOwnership: TStreamOwnership = soReference); overload; + destructor Destroy; override; + + function GetNextChunk(out ASize: NativeUint): PAnsiChar; virtual; + end; + + + TLua = class(TObject) + private + FState: lua_State; + FLoaded: Boolean; + FRegistrations: TLuaRegistrationList; + FRegisteredFunctions: TLuaRegisteredFunctionDictionary; + FRegisteredFunctionCookie: Integer; + FAutoOpenLibraries: TLuaLibraries; + FHasRun: Boolean; + FRttiContext: TRttiContext; + protected + function GetHasState: Boolean; virtual; + function GetState: lua_State; virtual; + + function DoAlloc(APointer: Pointer; AOldSize, ANewSize: NativeUint): Pointer; virtual; + + procedure DoNewState; virtual; + procedure DoClose; virtual; + procedure DoRegistration(ARegistration: TCustomLuaRegistration); virtual; + + procedure SetAutoOpenLibraries(const Value: TLuaLibraries); virtual; + protected + procedure CheckState; virtual; + procedure CheckIsFunction; virtual; + procedure AfterLoad; virtual; + + procedure AddRegistration(ARegistration: TCustomLuaRegistration); virtual; + function GetRegisteredFunctionCookie: Integer; virtual; + function RunRegisteredFunction(ACookie: Integer): Integer; virtual; + + property Loaded: Boolean read FLoaded write FLoaded; + property HasRun: Boolean read FHasRun write FHasRun; + property Registrations: TLuaRegistrationList read FRegistrations; + property RegisteredFunctions: TLuaRegisteredFunctionDictionary read FRegisteredFunctions; + public + constructor Create; + destructor Destroy; override; + + procedure LoadFromString(const AData: string; AAutoRun: Boolean = True; const AChunkName: string = ''); virtual; + procedure LoadFromStream(AStream: TStream; AOwnership: TStreamOwnership = soReference; AAutoRun: Boolean = True; const AChunkName: string = ''); virtual; + procedure LoadFromFile(const AFileName: string; AAutoRun: Boolean = True; const AChunkName: string = ''); virtual; + procedure LoadFromScript(AScript: TLuaScript; AOwnership: TStreamOwnership = soReference; AAutoRun: Boolean = True; const AChunkName: string = ''); virtual; + + function GetGlobalVariable(const AName: string): ILuaVariable; virtual; + procedure SetGlobalVariable(const AName: string; AVariable: TLuaImplicitVariable); virtual; + procedure RegisterFunction(const AName: string; AFunction: TLuaCFunction); virtual; +// procedure UnregisterFunction(); + + { Registers all published methods of the specified object. If ATableName + is provided, the methods will be bundled in a global table and accessible as + ATableName.Method(). If not provided, the methods are accessible directly + as global functions. } + procedure RegisterFunctions(AObject: TObject; const ATableName: string = ''; AIncludePublicVisibility: Boolean = False); virtual; +// procedure UnregisterFunctions(); + + procedure OpenLibraries(ALibraries: TLuaLibraries); virtual; + + { Get or set the current path(s) used for require calls. Paths must be separated + by semicolons and questions marks will be replaced with the requested file name, + as per the Lua documentation at: https://www.lua.org/pil/8.1.html } + function GetRequirePath: string; + procedure SetRequirePath(const APath: string); + procedure AddRequirePath(const APath: string); + + { These methods should only be called right after one of the + LoadFrom methods, which must have AutoRun set to False. } + procedure Run; virtual; + procedure GetByteCode(AStream: TStream; APop: Boolean = False); virtual; + procedure Capture(const AName: string); virtual; + + function Call(const AFunctionName: string): ILuaReadParameters; overload; virtual; + function Call(const AFunctionName: string; AParameters: array of const): ILuaReadParameters; overload; virtual; + function Call(const AFunctionName: string; AParameters: ILuaReadParameters): ILuaReadParameters; overload; virtual; + + property HasState: Boolean read GetHasState; + property State: lua_State read GetState; + + property AutoOpenLibraries: TLuaLibraries read FAutoOpenLibraries write SetAutoOpenLibraries default [TLuaLibrary.All]; + end; + + + TLuaHelpers = class(TObject) + private + class var RegistryKeyCounter: Int64; + public + class function GetLuaDataType(AType: Integer): TLuaDataType; + class function GetLuaVariableType(ADataType: TLuaDataType): TLuaVariableType; + + class function CreateParameters(AParameters: array of const): ILuaReadParameters; + + class procedure PushVariable(AState: lua_State; AVariable: ILuaVariable); overload; + class procedure PushVariable(AState: lua_State; AVariable: ILuaVariable; AVariableType: TLuaVariableType); overload; + class procedure PushString(AState: lua_State; const AValue: string); + class procedure PushTable(AState: lua_State; ATable: ILuaTable); + + class function AllocLuaString(const AValue: string): PAnsiChar; + class procedure FreeLuaString(AValue: PAnsiChar); + + class procedure RaiseLastLuaError(AState: lua_State); + class function LuaToString(AState: lua_State; AIndex: Integer): string; + class function CallFunction(AState: lua_State; AParameters: ILuaReadParameters): ILuaReadParameters; + + class function NewRegistryKey: string; + end; + + + +implementation +uses + System.Math, + System.SyncObjs, + System.TypInfo; + + +type + PLuaScript = ^TLuaScript; + + TLuaParametersEnumerator = class(TInterfacedObject, ILuaParametersEnumerator) + private + FParameters: ILuaReadParameters; + FIndex: Integer; + protected + property Parameters: ILuaReadParameters read FParameters; + public + constructor Create(AParameters: ILuaReadParameters); + + function GetCurrent: ILuaVariable; + function MoveNext: Boolean; + end; + + + TLuaStackParameters = class(TCustomLuaParameters) + private + FState: lua_State; + FCount: Integer; + protected + property State: lua_State read FState; + public + constructor Create(AState: lua_State; ACount: Integer = -1); + + { ILuaReadParameters } + function GetCount: Integer; override; + function GetItem(Index: Integer): ILuaVariable; override; + end; + + + TLuaStackVariable = class(TInterfacedObject, ILuaVariable) + private + FState: lua_State; + FIndex: Integer; + FTable: ILuaTable; + protected + property State: lua_State read FState; + property Index: Integer read FIndex; + public + constructor Create(AState: lua_State; AIndex: Integer); + + { ILuaVariable } + function GetDataType: TLuaDataType; + function GetVariableType: TLuaVariableType; + + function GetAsBoolean: Boolean; + function GetAsInteger: Integer; + function GetAsNumber: Double; + function GetAsUserData: Pointer; + function GetAsString: string; + function GetAsTable: ILuaTable; + function GetAsFunction: ILuaFunction; + + procedure SetAsBoolean(ABoolean: Boolean); + procedure SetAsInteger(AInteger: Integer); + procedure SetAsNumber(ANumber: Double); + procedure SetAsUserData(AUserData: Pointer); + procedure SetAsString(AString: string); + procedure SetAsTable(ATable: ILuaTable); + end; + + + TLuaResultParameters = class(TCustomLuaParameters) + private + FParameters: TList; + public + constructor Create(AState: lua_State; ACount: Integer); + destructor Destroy; override; + + function GetCount: Integer; override; + function GetItem(Index: Integer): ILuaVariable; override; + end; + + + TLuaVariable = class(TInterfacedObject, ILuaVariable) + private + FVariableType: TLuaVariableType; + FDataType: TLuaDataType; + FBooleanValue: Boolean; + FIntegerValue: Integer; + FNumberValue: Double; + FUserDataValue: Pointer; + FStringValue: string; + FTableValue: ILuaTable; + FFunctionValue: ILuaFunction; + protected + property VariableType: TLuaVariableType read FVariableType write FVariableType; + property DataType: TLuaDataType read FDataType write FDataType; + property BooleanValue: Boolean read FBooleanValue write FBooleanValue; + property IntegerValue: Integer read FIntegerValue write FIntegerValue; + property NumberValue: Double read FNumberValue write FNumberValue; + property UserDataValue: Pointer read FUserDataValue write FUserDataValue; + property StringValue: string read FStringValue write FStringValue; + property TableValue: ILuaTable read FTableValue write FTableValue; + property FunctionValue: ILuaFunction read FFunctionValue write FFunctionValue; + public + constructor Create; overload; + constructor Create(ABoolean: Boolean); overload; + constructor Create(AInteger: Integer); overload; + constructor Create(ANumber: Double); overload; + constructor Create(AUserData: Pointer); overload; + constructor Create(const AString: string); overload; + constructor Create(ATable: ILuaTable); overload; + constructor Create(AFunction: ILuaFunction); overload; + + { ILuaParameter } + function GetVariableType: TLuaVariableType; + function GetDataType: TLuaDataType; + + function GetAsBoolean: Boolean; + function GetAsInteger: Integer; + function GetAsNumber: Double; + function GetAsUserData: Pointer; + function GetAsString: string; + function GetAsTable: ILuaTable; + function GetAsFunction: ILuaFunction; + + procedure SetAsBoolean(ABoolean: Boolean); + procedure SetAsInteger(AInteger: Integer); + procedure SetAsNumber(ANumber: Double); + procedure SetAsUserData(AUserData: Pointer); + procedure SetAsString(AString: string); + procedure SetAsTable(ATable: ILuaTable); + end; + + + TLuaCachedVariable = class(TLuaVariable) + public + constructor Create(AState: lua_State; AIndex: Integer); + end; + + + TLuaCachedTable = class(TLuaTable) + public + constructor Create(AState: lua_State; AIndex: Integer); + end; + + + TLuaStackWriteParameters = class(TInterfacedObject, ILuaWriteParameters) + private + FState: lua_State; + FCount: Integer; + protected + procedure Pushed; + + property State: lua_State read FState; + public + constructor Create(AState: lua_State); + + { ILuaWriteParameters } + function GetCount: Integer; + + procedure Push(ABoolean: Boolean); overload; + procedure Push(AInteger: Integer); overload; + procedure Push(ANumber: Double); overload; + procedure Push(AUserData: Pointer); overload; + procedure Push(const AString: string); overload; + procedure Push(ATable: ILuaTable); overload; + end; + + + TLuaFunction = class(TInterfacedObject, ILuaFunction) + private + FState: lua_State; + FRegistryKey: string; + protected + property State: lua_State read FState; + property RegistryKey: string read FRegistryKey; + public + constructor Create(AState: lua_State; AIndex: Integer); + destructor Destroy; override; + + { ILuaFunction } + function Call(): ILuaReadParameters; overload; + function Call(AParameters: array of const): ILuaReadParameters; overload; + function Call(AParameters: ILuaReadParameters): ILuaReadParameters; overload; + end; + + + TLuaContext = class(TInterfacedObject, ILuaContext) + private + FParameters: ILuaReadParameters; + FResult: ILuaWriteParameters; + public + constructor Create(AState: lua_State); + + { ILuaContext } + function GetParameters: ILuaReadParameters; + function GetResult: ILuaWriteParameters; + end; + + + +{ TLuaHelpers } +class function TLuaHelpers.GetLuaDataType(AType: Integer): TLuaDataType; +begin + case AType of + LUA_TNIL: Result := LuaNil; + LUA_TNUMBER: Result := LuaNumber; + LUA_TBOOLEAN: Result := LuaBoolean; + LUA_TSTRING: Result := LuaString; + LUA_TTABLE: Result := LuaTable; + LUA_TFUNCTION: Result := LuaFunction; + LUA_TUSERDATA: Result := LuaUserData; + LUA_TTHREAD: Result := LuaThread; + LUA_TLIGHTUSERDATA: Result := LuaLightUserData; + else + Result := LuaNone; + end; +end; + + +class function TLuaHelpers.GetLuaVariableType(ADataType: TLuaDataType): TLuaVariableType; +begin + case ADataType of + LuaNumber: Result := VariableNumber; + LuaBoolean: Result := VariableBoolean; + LuaString: Result := VariableString; + LuaTable: Result := VariableTable; + LuaFunction: Result := VariableFunction; + LuaUserData: Result := VariableUserData; + LuaLightUserData: Result := VariableUserData; + else + Result := VariableNone; + end; +end; + + +class function TLuaHelpers.CreateParameters(AParameters: array of const): ILuaReadParameters; +var + parameterIndex: Integer; + parameter: TVarRec; + resultParameters: TLuaParameters; + table: ILuaTable; + +begin + resultParameters := TLuaParameters.Create; + + for parameterIndex := Low(AParameters) to High(AParameters) do + begin + parameter := AParameters[parameterIndex]; + case parameter.VType of + vtInteger: resultParameters.Push(parameter.VInteger); + vtBoolean: resultParameters.Push(parameter.VBoolean); + vtChar: resultParameters.Push(string(parameter.VChar)); + vtExtended: resultParameters.Push(parameter.VExtended^); + vtString: resultParameters.Push(string(parameter.VString)); + vtPointer: resultParameters.Push(parameter.VPointer); + vtPChar: resultParameters.Push(string(parameter.VPChar)); + vtObject: + if parameter.VObject is TLuaTable then + resultParameters.Push(TLuaTable(parameter.VObject)); + + vtWideChar: resultParameters.Push(string(parameter.VWideChar)); + vtPWideChar: resultParameters.Push(string(parameter.VPWideChar)); + vtAnsiString: resultParameters.Push(string(PAnsiChar(parameter.VAnsiString))); + vtCurrency: resultParameters.Push(parameter.VCurrency^); +// vtVariant: resultParameters.Push(parameter.VVariant); + vtInterface: + if Supports(IInterface(parameter.VInterface), ILuaTable, table) then + resultParameters.Push(table); + + vtWideString: resultParameters.Push(string(PWideString(parameter.VWideString))); + vtInt64: resultParameters.Push(parameter.VInt64^); + vtUnicodeString: resultParameters.Push(string(PUnicodeString(parameter.VUnicodeString))); + else + raise ELuaUnsupportedParameterException.CreateFmt('Parameter type %d not supported (index: %d)', [parameter.VType, parameterIndex]); + end; + end; + + Result := resultParameters; +end; + + +class procedure TLuaHelpers.PushVariable(AState: lua_State; AVariable: ILuaVariable); +begin + PushVariable(AState, AVariable, AVariable.VariableType); +end; + + +class procedure TLuaHelpers.PushVariable(AState: lua_State; AVariable: ILuaVariable; AVariableType: TLuaVariableType); +begin + case AVariableType of + VariableNone: lua_pushnil(AState); + VariableBoolean: lua_pushboolean(AState, IfThen(AVariable.AsBoolean, 1, 0)); + VariableInteger: lua_pushinteger(AState, AVariable.AsInteger); + VariableNumber: lua_pushnumber(AState, AVariable.AsNumber); + VariableUserData: + if AVariable.AsUserData = nil then + lua_pushnil(AState) + else + lua_pushlightuserdata(AState, AVariable.AsUserData); + + VariableString: PushString(AState, AVariable.AsString); + VariableTable: PushTable(AState, AVariable.AsTable); + else + raise ELuaUnsupportedVariableException.CreateFmt('Variable type not supported: %d', [Ord(AVariableType)]); + end; +end; + + +class procedure TLuaHelpers.PushString(AState: lua_State; const AValue: string); +var + stringValue: PAnsiChar; + +begin + stringValue := AllocLuaString(AValue); + try + lua_pushlstring(AState, stringValue, Length(AValue)); + finally + FreeLuaString(stringValue); + end; +end; + + +class procedure TLuaHelpers.PushTable(AState: lua_State; ATable: ILuaTable); +var + pair: TLuaKeyValuePair; + +begin + lua_newtable(AState); + + for pair in ATable do + begin + PushVariable(AState, pair.Key); + PushVariable(AState, pair.Value); + lua_settable(AState, -3); + end; +end; + + +// Casting strings directly to PAnsiChar (via AnsiString) causes corruption +// with table values, at least in Delphi XE2. Can't really explain why, seems +// the input string goes out of scope, so let's just go through the motions +// to create a copy and be safe. +class function TLuaHelpers.AllocLuaString(const AValue: string): PAnsiChar; +begin + if Length(AValue) > 0 then + begin + GetMem(Result, Length(AValue) + 1); + StrPCopy(Result, AnsiString(AValue)); + end else + Result := nil; +end; + + +class procedure TLuaHelpers.FreeLuaString(AValue: PAnsiChar); +begin + FreeMem(AValue); +end; + +// If someone cares to reproduce this issue and optimize the code, use these +// two and the TableLuaFunction test should fail with a corrupted value +// (#11#0#0#0#11#0#0#0#11#0#0#0#11#0#0#0#11). +(* +class function TLuaHelpers.AllocLuaString(const AValue: string): PAnsiChar; +begin + if Length(AValue) > 0 then + Result := PAnsiChar(AnsiString(AValue)) + else + Result := nil; +end; + +class procedure TLuaHelpers.FreeLuaString(AValue: PAnsiChar); +begin +end; +*) + + + + +class procedure TLuaHelpers.RaiseLastLuaError(AState: lua_State); +var + errorMessage: string; + +begin + errorMessage := LuaToString(AState, -1); + lua_pop(AState, 1); + + raise ELuaException.Create(errorMessage); +end; + + +class function TLuaHelpers.LuaToString(AState: lua_State; AIndex: Integer): string; +var + len: NativeUint; + value: PAnsiChar; + stringValue: RawByteString; + +begin + value := lua_tolstring(AState, AIndex, @len); + SetString(stringValue, value, len); + + Result := string(stringValue); +end; + + +class function TLuaHelpers.CallFunction(AState: lua_State; AParameters: ILuaReadParameters): ILuaReadParameters; +var + stackIndex: Integer; + parameterCount: Integer; + parameter: ILuaVariable; + +begin + { Assumption: the function to call is the top item on the stack } + stackIndex := Pred(lua_gettop(AState)); + + parameterCount := 0; + if Assigned(AParameters) then + begin + parameterCount := AParameters.Count; + for parameter in AParameters do + PushVariable(AState, parameter); + end; + + if lua_pcall(AState, parameterCount, LUA_MULTRET, 0) <> 0 then + RaiseLastLuaError(AState); + + Result := TLuaResultParameters.Create(AState, lua_gettop(AState) - stackIndex); +end; + + +class function TLuaHelpers.NewRegistryKey: string; +begin + // This could be incremented on a per-State basis, but this'll do for now. + Result := Format('DelphiLuaWrapper_%d', [TInterlocked.Increment(RegistryKeyCounter)]); +end; + + + +{ TLuaImplicitVariable } +class operator TLuaImplicitVariable.Implicit(AValue: ILuaVariable): TLuaImplicitVariable; +begin + Result.Variable := AValue; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: Boolean): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: Integer): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: Double): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: Pointer): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(const AValue: string): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: ILuaTable): TLuaImplicitVariable; +begin + Result.Variable := TLuaVariable.Create(AValue); +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): ILuaVariable; +begin + Result := AValue.Variable; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): Boolean; +begin + Result := AValue.Variable.AsBoolean; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): Integer; +begin + Result := AValue.Variable.AsInteger; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): Double; +begin + Result := AValue.Variable.AsNumber; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): Pointer; +begin + Result := AValue.Variable.AsUserData; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): string; +begin + Result := AValue.Variable.AsString; +end; + + +class operator TLuaImplicitVariable.Implicit(AValue: TLuaImplicitVariable): ILuaTable; +begin + Result := AValue.Variable.AsTable; +end; + + +{ TLuaTableEnumerator } +constructor TLuaTableEnumerator.Create(AEnumerator: TEnumerator>); +begin + inherited Create; + + FEnumerator := AEnumerator; +end; + + +destructor TLuaTableEnumerator.Destroy; +begin + FreeAndNil(FEnumerator); + + inherited Destroy; +end; + + +function TLuaTableEnumerator.GetCurrent: TLuaKeyValuePair; +var + current: TPair; + +begin + current := FEnumerator.Current; + + Result.Key := current.Key; + Result.Value := current.Value; +end; + + +function TLuaTableEnumerator.MoveNext: Boolean; +begin + Result := FEnumerator.MoveNext; +end; + + +{ TLuaVariableEqualityComparer } +function TLuaVariableEqualityComparer.Equals(const Left, Right: ILuaVariable): Boolean; +begin + Result := (Left.VariableType = Right.VariableType); + if Result then + begin + case Left.VariableType of + VariableBoolean: Result := (Left.AsBoolean = Right.AsBoolean); + VariableInteger: Result := (Left.AsInteger = Right.AsInteger); + VariableNumber: Result := SameValue(Left.AsNumber, Right.AsNumber); + VariableUserData: Result := (Left.AsUserData = Right.AsUserData); + VariableString: Result := (Left.AsString = Right.AsString); + VariableTable: Result := (Left.AsTable = Right.AsTable); + end; + end; +end; + +function TLuaVariableEqualityComparer.GetHashCode(const Value: ILuaVariable): Integer; +var + i: Integer; + m: Extended; + e: Integer; + p: Pointer; + s: string; + +begin + Result := 0; + + // System.Generics.Defaults has a decent set of GetHashCode_ functions... + // ...which are of course private. + case Value.VariableType of + VariableBoolean: + Result := Ord(Value.AsBoolean); + VariableInteger: + begin + i := Value.AsInteger; + Result := BobJenkinsHash(i, SizeOf(i), 0); + end; + VariableNumber: + begin + // Denormalized floats and positive/negative 0.0 complicate things. + Frexp(Value.AsNumber, m, e); + if m = 0 then + m := Abs(m); + Result := BobJenkinsHash(m, SizeOf(m), 0); + Result := BobJenkinsHash(e, SizeOf(e), Result); + end; + VariableUserData: + begin + p := Value.AsUserData; + Result := BobJenkinsHash(p, SizeOf(p), 0); + end; + VariableString: + begin + s := Value.AsString; + if Length(s) > 0 then + Result := BobJenkinsHash(s[1], Length(s) * SizeOf(s[1]), 0); + end; + VariableTable: + begin + p := Pointer(Value.AsTable); + Result := BobJenkinsHash(p, SizeOf(p), 0); + end; + end; +end; + + +{ TLuaTable } +constructor TLuaTable.Create; +begin + inherited Create; + + FTable := TDictionary.Create(TLuaVariableEqualityComparer.Create); +end; + + +destructor TLuaTable.Destroy; +begin + FreeAndNil(FTable); + + inherited Destroy; +end; + + +function TLuaTable.GetEnumerator: ILuaTableEnumerator; +begin + Result := TLuaTableEnumerator.Create(FTable.GetEnumerator); +end; + + +function TLuaTable.HasValue(AKey: TLuaImplicitVariable): Boolean; +begin + Result := FTable.ContainsKey(AKey); +end; + +function TLuaTable.GetValue(AKey: TLuaImplicitVariable): ILuaVariable; +begin + Result := FTable[AKey]; +end; + + +procedure TLuaTable.SetValue(AKey, AValue: TLuaImplicitVariable); +begin + FTable.AddOrSetValue(AKey, AValue); +end; + + +{ TCustomLuaRegistration } +constructor TCustomLuaRegistration.Create(const AName: string); +begin + inherited Create; + + FName := AName; +end; + + +{ TLuaFunctionRegistration } +procedure TLuaFunctionRegistration.Apply(AState: lua_State; APushFunction: TLuaPushFunction); +var + functionName: PAnsiChar; + +begin + functionName := TLuaHelpers.AllocLuaString(Name); + try + APushFunction(Callback); + lua_setglobal(AState, functionName); + finally + TLuaHelpers.FreeLuaString(functionName); + end; +end; + +constructor TLuaFunctionRegistration.Create(const AName: string; ACallback: TLuaCFunction); +begin + inherited Create(AName); + + FCallback := ACallback; +end; + + +{ TLuaTableRegistration } +constructor TLuaTableRegistration.Create(const AName: string); +begin + inherited Create(AName); + + FFunctionTable := TLuaFunctionTable.Create; +end; + + +destructor TLuaTableRegistration.Destroy; +begin + FreeAndNil(FFunctionTable); + + inherited Destroy; +end; + + +procedure TLuaTableRegistration.RegisterFunction(const AName: string; AFunction: TLuaCFunction); +begin + FunctionTable.AddOrSetValue(AName, AFunction); +end; + + +procedure TLuaTableRegistration.Apply(AState: lua_State; APushFunction: TLuaPushFunction); +var + pair: TPair; + functionName: PAnsiChar; + tableName: PAnsiChar; + +begin + lua_newtable(AState); + + for pair in FunctionTable do + begin + functionName := TLuaHelpers.AllocLuaString(pair.Key); + try + lua_pushstring(AState, functionName); + APushFunction(pair.Value); + lua_settable(AState, -3); + finally + TLuaHelpers.FreeLuaString(functionName); + end; + end; + + tableName := TLuaHelpers.AllocLuaString(Name); + try + lua_setglobal(AState, tableName); + finally + TLuaHelpers.FreeLuaString(tableName); + end; +end; + + +{ TLuaScript } +constructor TLuaScript.Create(const AData: string); +begin + Create(TStringStream.Create(AData), soOwned); +end; + + +constructor TLuaScript.Create(const AStream: TStream; AOwnership: TStreamOwnership); +begin + inherited Create; + + FStream := AStream; + FStreamOwnership := AOwnership; +end; + + +destructor TLuaScript.Destroy; +begin + if Assigned(FBuffer) then + FreeMem(FBuffer); + + if FStreamOwnership = soOwned then + FreeAndNil(FStream); + + inherited Destroy; +end; + + +function TLuaScript.GetNextChunk(out ASize: NativeUint): PAnsiChar; +const + BufferSize = 4096; + +begin + if not Assigned(FBuffer) then + GetMem(FBuffer, BufferSize); + + ASize := FStream.Read(FBuffer^, BufferSize); + if ASize > 0 then + Result := FBuffer + else + Result := nil; +end; + + + +{ Callback functions } +function LuaWrapperAlloc(ud, ptr: Pointer; osize, nsize: size_t): Pointer; cdecl; +begin + Result := TLua(ud).DoAlloc(ptr, osize, nsize); +end; + + +function LuaWrapperReader(L: lua_State; ud: Pointer; var sz: Lua.size_t): PAnsiChar; cdecl; +var + script: PLuaScript; + +begin + script := ud; + Result := script^.GetNextChunk(sz); +end; + + +function LuaWrapperWriter(L: lua_State; p: Pointer; sz: size_t; ud: Pointer): Integer; cdecl; +var + stream: TStream; + +begin + stream := TStream(ud^); + try + stream.WriteBuffer(p^, sz); + Result := 0; + except + on E:EStreamError do + Result := 1; + end; +end; + + +function LuaWrapperFunction(L: lua_State): Integer; cdecl; +var + lua: TLua; + cookie: Integer; + +begin + Result := 0; + + lua := TLua(lua_touserdata(L, lua_upvalueindex(1))); + cookie := lua_tointeger(L, lua_upvalueindex(2)); + + if Assigned(lua) then + Result := lua.RunRegisteredFunction(cookie); +end; + + +{ TLua } +constructor TLua.Create; +begin + inherited Create; + + FAutoOpenLibraries := [TLuaLibrary.All]; + FRegistrations := TLuaRegistrationList.Create(True); + FRegisteredFunctions := TLuaRegisteredFunctionDictionary.Create; +end; + + +destructor TLua.Destroy; +begin + FreeAndNil(FRegisteredFunctions); + FreeAndNil(FRegistrations); + + if HasState then + DoClose; + + inherited Destroy; +end; + + +procedure TLua.LoadFromString(const AData: string; AAutoRun: Boolean; const AChunkName: string); +begin + LoadFromScript(TLuaScript.Create(AData), soOwned, AAutoRun, AChunkName); +end; + + +procedure TLua.LoadFromStream(AStream: TStream; AOwnership: TStreamOwnership; AAutoRun: Boolean; const AChunkName: string); +begin + LoadFromScript(TLuaScript.Create(AStream, AOwnership), soOwned, AAutoRun, AChunkName); +end; + + +procedure TLua.LoadFromFile(const AFileName: string; AAutoRun: Boolean; const AChunkName: string); +var + chunkName: string; + +begin + if Length(AChunkName) > 0 then + chunkName := AChunkName + else + chunkName := ExtractFileName(AFileName); + + LoadFromScript(TLuaScript.Create(TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone), soOwned), soOwned, AAutoRun, chunkName); +end; + + +procedure TLua.LoadFromScript(AScript: TLuaScript; AOwnership: TStreamOwnership; AAutoRun: Boolean; const AChunkName: string); +var + chunkName: PAnsiChar; + +begin + try + chunkName := TLuaHelpers.AllocLuaString(AChunkName); + try + if lua_load(State, LuaWrapperReader, @AScript, chunkName, nil) <> 0 then + TLuaHelpers.RaiseLastLuaError(State); + finally + TLuaHelpers.FreeLuaString(chunkName); + end; + + if not Loaded then + AfterLoad; + + if AAutoRun then + Run; + finally + if AOwnership = soOwned then + FreeAndNil(AScript); + end; +end; + + +procedure TLua.OpenLibraries(ALibraries: TLuaLibraries); +begin + if TLuaLibrary.All in ALibraries then + luaL_openlibs(State) + else + begin + if TLuaLibrary.Base in ALibraries then + luaL_requiref(State, 'base', luaopen_base, 1); + + if TLuaLibrary.Coroutine in ALibraries then + luaL_requiref(State, 'coroutine', luaopen_coroutine, 1); + + if TLuaLibrary.Table in ALibraries then + luaL_requiref(State, 'table', luaopen_table, 1); + + if TLuaLibrary.IO in ALibraries then + luaL_requiref(State, 'io', luaopen_io, 1); + + if TLuaLibrary.OS in ALibraries then + luaL_requiref(State, 'os', luaopen_os, 1); + + if TLuaLibrary.StringLib in ALibraries then + luaL_requiref(State, 'string', luaopen_string, 1); + + if TLuaLibrary.Bit32 in ALibraries then + luaL_requiref(State, 'bit32', luaopen_bit32, 1); + + if TLuaLibrary.Math in ALibraries then + luaL_requiref(State, 'math', luaopen_math, 1); + + if TLuaLibrary.Debug in ALibraries then + luaL_requiref(State, 'debug', luaopen_debug, 1); + + if TLuaLibrary.Package in ALibraries then + luaL_requiref(State, 'package', luaopen_package, 1); + end; +end; + + +function TLua.GetRequirePath: string; +begin + CheckState; + + lua_getglobal(State, 'package'); + try + lua_getfield(State, -1, 'path'); + try + Result := TLuaHelpers.LuaToString(State, -1); + finally + lua_pop(State, 1); + end; + finally + lua_pop(State, 1); + end; +end; + + +procedure TLua.SetRequirePath(const APath: string); +begin + CheckState; + + lua_getglobal(State, 'package'); + try + TLuaHelpers.PushString(State, APath); + lua_setfield(State, -2, 'path'); + finally + lua_pop(State, 1); + end; +end; + + +procedure TLua.AddRequirePath(const APath: string); +var + path: string; + +begin + path := GetRequirePath; + if (Length(path) > 0) and (path[Length(path)] <> ';') then + path := path + ';'; + + SetRequirePath(path + APath); +end; + + +procedure TLua.Run; +begin + CheckIsFunction; + + if lua_pcall(State, 0, 0, 0) <> 0 then + TLuaHelpers.RaiseLastLuaError(State); + + HasRun := True; +end; + + +procedure TLua.GetByteCode(AStream: TStream; APop: Boolean); +var + returnCode: Integer; + +begin + CheckIsFunction; + + try + returnCode := lua_dump(State, LuaWrapperWriter, @AStream); + if returnCode <> 0 then + raise ELuaException.CreateFmt('lua_dump returned code %d', [returnCode]); + finally + if APop then + lua_pop(State, 1); + end; +end; + + +procedure TLua.Capture(const AName: string); +var + name: PAnsiChar; + +begin + CheckIsFunction; + + // Create a new table to serve as the environment + lua_newtable(State); + + // Set the global AName to the new table + lua_pushvalue(State, -1); + name := TLuaHelpers.AllocLuaString(AName); + try + lua_setglobal(State, name); + finally + TLuaHelpers.FreeLuaString(name); + end; + + // Set the global environment as the table's metatable index, so calls to + // global functions and variables still work + lua_newtable(State); + TLuaHelpers.PushString(State, '__index'); + lua_pushglobaltable(State); + lua_settable(State, -3); + + lua_setmetatable(State, -2); + + // Set the new table as the environment (upvalue at index 1) + lua_setupvalue(State, -2, 1); + + if lua_pcall(State, 0, 0, 0) <> 0 then + TLuaHelpers.RaiseLastLuaError(State); +end; + + +function TLua.Call(const AFunctionName: string): ILuaReadParameters; +begin + Result := Call(AFunctionName, nil); +end; + + +function TLua.Call(const AFunctionName: string; AParameters: array of const): ILuaReadParameters; +begin + Result := Call(AFunctionName, TLuaHelpers.CreateParameters(AParameters)); +end; + + +function TLua.Call(const AFunctionName: string; AParameters: ILuaReadParameters): ILuaReadParameters; +var + functionName: PAnsiChar; + +begin + { Global functions are only present after the has run once: + http://lua-users.org/lists/lua-l/2011-01/msg01154.html } + if not HasRun then + Run; + + functionName := TLuaHelpers.AllocLuaString(AFunctionName); + try + lua_getglobal(State, functionName); + finally + TLuaHelpers.FreeLuaString(functionName); + end; + + Result := TLuaHelpers.CallFunction(State, AParameters); +end; + + +procedure TLua.CheckState; +begin + if not LuaLibLoaded then + LoadLuaLib; + + if not HasState then + DoNewState; +end; + + +procedure TLua.CheckIsFunction; +begin + if not lua_isfunction(State, -1) then + raise ELuaNoFunctionException.Create('No function on top of the stack, use the LoadFrom methods first'); +end; + + +procedure TLua.AfterLoad; +var + registration: TCustomLuaRegistration; + +begin + Loaded := True; + HasRun := False; + + { Register functions in the current environment } + for registration in Registrations do + DoRegistration(registration); +end; + + +function TLua.GetGlobalVariable(const AName: string): ILuaVariable; +var + name: PAnsiChar; + +begin + name := TLuaHelpers.AllocLuaString(AName); + try + lua_getglobal(State, name); + + Result := TLuaCachedVariable.Create(State, -1); + lua_pop(State, 1); + finally + TLuaHelpers.FreeLuaString(name); + end; +end; + + +procedure TLua.SetGlobalVariable(const AName: string; AVariable: TLuaImplicitVariable); +var + name: PAnsiChar; + +begin + name := TLuaHelpers.AllocLuaString(AName); + try + TLuaHelpers.PushVariable(State, AVariable); + lua_setglobal(State, name); + finally + TLuaHelpers.FreeLuaString(name); + end; +end; + + +procedure TLua.RegisterFunction(const AName: string; AFunction: TLuaCFunction); +begin + { Since anonymous methods are basically interfaces, we need to keep a reference around } + AddRegistration(TLuaFunctionRegistration.Create(AName, AFunction)); +end; + + +procedure TLua.RegisterFunctions(AObject: TObject; const ATableName: string; AIncludePublicVisibility: Boolean); + + { This wrapper is needed because Delphi's anonymous functions capture + variables, not values. We need a stable 'callback' here. } + function CaptureCallback(AMethod: TMethod): TLuaCFunction; inline; + begin + Result := TLuaCMethod(AMethod); + end; + +var + rttiType: TRttiType; + rttiMethod: TRttiMethod; + rttiParameters: TArray; + callback: TMethod; + tableRegistration: TLuaTableRegistration; + +begin + tableRegistration := nil; + if Length(ATableName) > 0 then + tableRegistration := TLuaTableRegistration.Create(ATableName); + + rttiType := FRttiContext.GetType(AObject.ClassType); + for rttiMethod in rttiType.GetMethods do + begin + if (rttiMethod.Visibility = mvPublished) or + (AIncludePublicVisibility and (rttiMethod.Visibility = mvPublic)) then + begin + rttiParameters := rttiMethod.GetParameters; + + { Check if one parameter of type ILuaContext is present } + if (Length(rttiParameters) = 1) and + (Assigned(rttiParameters[0].ParamType)) and + (rttiParameters[0].ParamType.TypeKind = tkInterface) and + (TRttiInterfaceType(rttiParameters[0].ParamType).GUID = ILuaContext) then + begin + callback.Code := rttiMethod.CodeAddress; + callback.Data := AObject; + + if Assigned(tableRegistration) then + tableRegistration.RegisterFunction(rttiMethod.Name, CaptureCallback(callback)) + else + AddRegistration(TLuaFunctionRegistration.Create(rttiMethod.Name, CaptureCallback(callback))); + end; + end; + end; + + if Assigned(tableRegistration) then + AddRegistration(tableRegistration); +end; + + +function TLua.DoAlloc(APointer: Pointer; AOldSize, ANewSize: NativeUint): Pointer; +begin + Result := DefaultLuaAlloc(nil, APointer, AOldSize, ANewSize); +end; + + +procedure TLua.DoNewState; +begin + FState := lua_newstate(@LuaWrapperAlloc, Pointer(Self)); + if not HasState then + raise ELuaInitException.Create('Failed to initialize new state'); + + OpenLibraries(AutoOpenLibraries); +end; + + +procedure TLua.DoClose; +begin + lua_close(FState); + FState := nil; +end; + + +procedure TLua.DoRegistration(ARegistration: TCustomLuaRegistration); +var + this: TLua; + +begin + this := Self; + + ARegistration.Apply(State, + procedure(AFunction: TLuaCFunction) + var + cookie: Integer; + + begin + cookie := GetRegisteredFunctionCookie; + RegisteredFunctions.Add(cookie, AFunction); + + lua_pushlightuserdata(State, this); + lua_pushinteger(State, Cookie); + lua_pushcclosure(State, @LuaWrapperFunction, 2); + end); +end; + +procedure TLua.AddRegistration(ARegistration: TCustomLuaRegistration); +begin + Registrations.Add(ARegistration); + + { Only register functions after Load, otherwise they'll not be available in the environment } + if Loaded then + DoRegistration(ARegistration); +end; + + +function TLua.GetRegisteredFunctionCookie: Integer; +begin + Inc(FRegisteredFunctionCookie); + Result := FRegisteredFunctionCookie; +end; + + +function TLua.RunRegisteredFunction(ACookie: Integer): Integer; +var + context: ILuaContext; + +begin + Result := 0; + + if RegisteredFunctions.ContainsKey(ACookie) then + begin + context := TLuaContext.Create(State); + + try + RegisteredFunctions[ACookie](context); + Result := context.Result.Count; + except + on E:Exception do + Result := luaL_error(State, PAnsiChar(AnsiString(E.Message)), nil); + end; + end; +end; + + +function TLua.GetHasState: Boolean; +begin + Result := Assigned(FState); +end; + + +function TLua.GetState: lua_State; +begin + CheckState; + Result := FState; +end; + + +procedure TLua.SetAutoOpenLibraries(const Value: TLuaLibraries); +begin + FAutoOpenLibraries := Value; +end; + + +{ TLuaParametersEnumerator } +constructor TLuaParametersEnumerator.Create(AParameters: ILuaReadParameters); +begin + inherited Create; + FParameters := AParameters; + FIndex := -1; +end; + +function TLuaParametersEnumerator.GetCurrent: ILuaVariable; +begin + Result := Parameters.Items[FIndex]; +end; + + +function TLuaParametersEnumerator.MoveNext: Boolean; +begin + Inc(FIndex); + Result := FIndex < Parameters.Count; +end; + + +{ TCustomLuaParameters } +function TCustomLuaParameters.GetEnumerator: ILuaParametersEnumerator; +begin + Result := TLuaParametersEnumerator.Create(Self); +end; + + +function TCustomLuaParameters.GetVariableType: TLuaVariableType; +begin + Result := GetDefaultVariable.GetVariableType; +end; + + +function TCustomLuaParameters.GetDataType: TLuaDataType; +begin + Result := GetDefaultVariable.GetDataType; +end; + + +function TCustomLuaParameters.GetAsBoolean: Boolean; +begin + Result := GetDefaultVariable.GetAsBoolean; +end; + + +function TCustomLuaParameters.GetAsInteger: Integer; +begin + Result := GetDefaultVariable.GetAsInteger; +end; + + +function TCustomLuaParameters.GetAsNumber: Double; +begin + Result := GetDefaultVariable.GetAsNumber; +end; + + +function TCustomLuaParameters.GetAsUserData: Pointer; +begin + Result := GetDefaultVariable.GetAsUserData; +end; + + +function TCustomLuaParameters.GetAsString: string; +begin + Result := GetDefaultVariable.GetAsString; +end; + + +function TCustomLuaParameters.GetAsTable: ILuaTable; +begin + Result := GetDefaultVariable.GetAsTable; +end; + + +function TCustomLuaParameters.GetAsFunction: ILuaFunction; +begin + Result := GetDefaultVariable.GetAsFunction; +end; + + +procedure TCustomLuaParameters.SetAsBoolean(ABoolean: Boolean); +begin + GetDefaultVariable.SetAsBoolean(ABoolean); +end; + + +procedure TCustomLuaParameters.SetAsInteger(AInteger: Integer); +begin + GetDefaultVariable.SetAsInteger(AInteger); +end; + + +procedure TCustomLuaParameters.SetAsNumber(ANumber: Double); +begin + GetDefaultVariable.SetAsNumber(ANumber); +end; + + +procedure TCustomLuaParameters.SetAsUserData(AUserData: Pointer); +begin + GetDefaultVariable.SetAsUserData(AUserData); +end; + + +procedure TCustomLuaParameters.SetAsString(AString: string); +begin + GetDefaultVariable.SetAsString(AString); +end; + + +procedure TCustomLuaParameters.SetAsTable(ATable: ILuaTable); +begin + GetDefaultVariable.SetAsTable(ATable); +end; + + +function TCustomLuaParameters.GetDefaultVariable: ILuaVariable; +begin + Result := GetItem(0); +end; + + +function TCustomLuaParameters.ToString: string; +var + parameterIndex: Integer; + +begin + Result := ''; + + for parameterIndex := 0 to Pred(GetCount) do + Result := Result + GetItem(parameterIndex).AsString; +end; + + +{ TLuaCFunctionParameters } +constructor TLuaStackParameters.Create(AState: lua_State; ACount: Integer); +begin + inherited Create; + + FState := AState; + FCount := ACount; + + if FCount = -1 then + FCount := lua_gettop(State); +end; + + +function TLuaStackParameters.GetCount: Integer; +begin + Result := FCount; +end; + + +function TLuaStackParameters.GetItem(Index: Integer): ILuaVariable; +begin + if (Index < 0) or (Index >= GetCount) then + raise ERangeError.CreateFmt('Invalid parameter index: %d', [Index]); + + Result := TLuaStackVariable.Create(State, Succ(Index)); +end; + + +{ TLuaCFunctionParameter } +constructor TLuaStackVariable.Create(AState: lua_State; AIndex: Integer); +begin + inherited Create; + + FState := AState; + FIndex := AIndex; +end; + + +function TLuaStackVariable.GetVariableType: TLuaVariableType; +begin + Result := TLuaHelpers.GetLuaVariableType(GetDataType); +end; + + +function TLuaStackVariable.GetDataType: TLuaDataType; +begin + Result := TLuaHelpers.GetLuaDataType(lua_type(State, Index)); +end; + + +function TLuaStackVariable.GetAsBoolean: Boolean; +begin + Result := (lua_toboolean(State, Index) <> 0); +end; + + +function TLuaStackVariable.GetAsInteger: Integer; +begin + Result := lua_tointeger(State, Index); +end; + + +function TLuaStackVariable.GetAsNumber: Double; +begin + Result := lua_tonumber(State, Index); +end; + + +function TLuaStackVariable.GetAsUserData: Pointer; +begin + Result := lua_touserdata(State, Index); +end; + + +function TLuaStackVariable.GetAsString: string; +begin + Result := TLuaHelpers.LuaToString(State, Index); +end; + + +function TLuaStackVariable.GetAsTable: ILuaTable; +begin + if not lua_istable(State, Index) then + Result := nil; + + if not Assigned(FTable) then + FTable := TLuaCachedTable.Create(State, Index); + + Result := FTable; +end; + + +function TLuaStackVariable.GetAsFunction: ILuaFunction; +begin + if not lua_isfunction(State, Index) then + Result := nil; + + Result := TLuaFunction.Create(State, Index); +end; + + +procedure TLuaStackVariable.SetAsBoolean(ABoolean: Boolean); +begin + lua_pushboolean(State, IfThen(ABoolean, 1, 0)); + lua_replace(State, Index); +end; + + +procedure TLuaStackVariable.SetAsInteger(AInteger: Integer); +begin + TLuaHelpers.PushVariable(State, Self, VariableInteger); + lua_replace(State, Index); +end; + + +procedure TLuaStackVariable.SetAsNumber(ANumber: Double); +begin + TLuaHelpers.PushVariable(State, Self, VariableNumber); + lua_replace(State, Index); +end; + + +procedure TLuaStackVariable.SetAsString(AString: string); +begin + TLuaHelpers.PushVariable(State, Self, VariableString); + lua_replace(State, Index); +end; + + +procedure TLuaStackVariable.SetAsTable(ATable: ILuaTable); +begin + TLuaHelpers.PushVariable(State, Self, VariableTable); + lua_replace(State, Index); +end; + + +procedure TLuaStackVariable.SetAsUserData(AUserData: Pointer); +begin + TLuaHelpers.PushVariable(State, Self, VariableUserData); + lua_replace(State, Index); +end; + + +{ TLuaResultParameters } +constructor TLuaResultParameters.Create(AState: lua_State; ACount: Integer); +var + parameterIndex: Integer; + +begin + inherited Create; + + FParameters := TList.Create; + + if ACount > 0 then + begin + FParameters.Capacity := ACount; + + for parameterIndex := ACount downto 1 do + FParameters.Add(TLuaCachedVariable.Create(AState, -ACount)); + + lua_pop(AState, ACount); + end; +end; + + +destructor TLuaResultParameters.Destroy; +begin + FreeAndNil(FParameters); + + inherited Destroy; +end; + + +function TLuaResultParameters.GetCount: Integer; +begin + Result := FParameters.Count; +end; + + +function TLuaResultParameters.GetItem(Index: Integer): ILuaVariable; +begin + Result := FParameters[Index]; +end; + + +{ TLuaVariable } +constructor TLuaVariable.Create; +begin +end; + + +constructor TLuaVariable.Create(ABoolean: Boolean); +begin + Create; + SetAsBoolean(ABoolean); +end; + + +constructor TLuaVariable.Create(AInteger: Integer); +begin + Create; + SetAsInteger(AInteger); +end; + + +constructor TLuaVariable.Create(ANumber: Double); +begin + Create; + SetAsNumber(ANumber); +end; + + +constructor TLuaVariable.Create(AUserData: Pointer); +begin + Create; + SetAsUserData(AUserData); +end; + + +constructor TLuaVariable.Create(const AString: string); +begin + Create; + SetAsString(AString); +end; + + +constructor TLuaVariable.Create(AFunction: ILuaFunction); +begin + Create; + VariableType := VariableFunction; + DataType := LuaFunction; + FunctionValue := AFunction; +end; + + +constructor TLuaVariable.Create(ATable: ILuaTable); +begin + Create; + SetAsTable(ATable); +end; + + +function TLuaVariable.GetVariableType: TLuaVariableType; +begin + Result := VariableType; +end; + + +function TLuaVariable.GetDataType: TLuaDataType; +begin + Result := DataType; +end; + + +function TLuaVariable.GetAsBoolean: Boolean; +begin + Result := BooleanValue; +end; + + +function TLuaVariable.GetAsInteger: Integer; +begin + Result := IntegerValue; +end; + + +function TLuaVariable.GetAsNumber: Double; +begin + Result := NumberValue; +end; + + +function TLuaVariable.GetAsUserData: Pointer; +begin + Result := UserDataValue; +end; + + +function TLuaVariable.GetAsString: string; +begin + Result := StringValue; +end; + + +function TLuaVariable.GetAsTable: ILuaTable; +begin + Result := TableValue; +end; + + +function TLuaVariable.GetAsFunction: ILuaFunction; +begin + Result := FunctionValue; +end; + + +procedure TLuaVariable.SetAsBoolean(ABoolean: Boolean); +begin + VariableType := VariableBoolean; + DataType := LuaBoolean; + BooleanValue := ABoolean; +end; + + +procedure TLuaVariable.SetAsInteger(AInteger: Integer); +begin + VariableType := VariableInteger; + DataType := LuaString; + IntegerValue := AInteger; +end; + + +procedure TLuaVariable.SetAsNumber(ANumber: Double); +begin + VariableType := VariableNumber; + DataType := LuaNumber; + NumberValue := ANumber; +end; + + +procedure TLuaVariable.SetAsUserData(AUserData: Pointer); +begin + VariableType := VariableUserData; + DataType := LuaLightUserData; + UserDataValue := AUserData; +end; + + +procedure TLuaVariable.SetAsString(AString: string); +begin + VariableType := VariableString; + DataType := LuaString; + StringValue := AString; +end; + + +procedure TLuaVariable.SetAsTable(ATable: ILuaTable); +begin + VariableType := VariableTable; + DataType := LuaTable; + TableValue := ATable; +end; + + +{ TLuaCachedVariable } +constructor TLuaCachedVariable.Create(AState: lua_State; AIndex: Integer); +begin + inherited Create; + + DataType := TLuaHelpers.GetLuaDataType(lua_type(AState, AIndex)); + VariableType := TLuaHelpers.GetLuaVariableType(FDataType); + + BooleanValue := (lua_toboolean(AState, AIndex) <> 0); + IntegerValue := lua_tointeger(AState, AIndex); + NumberValue := lua_tonumber(AState, AIndex); + UserDataValue := lua_touserdata(AState, AIndex); + + { While traversing a table, do not call lua_tolstring directly on a key, + unless you know that the key is actually a string. Recall that lua_tolstring + may change the value at the given index; this confuses the next call to + lua_next. + + http://www.lua.org/manual/5.2/manual.html#lua_next } + case lua_type(AState, AIndex) of + LUA_TSTRING: StringValue := TLuaHelpers.LuaToString(AState, AIndex); + LUA_TNUMBER: StringValue := FloatToStr(NumberValue); + end; + + if lua_istable(AState, AIndex) then + TableValue := TLuaCachedTable.Create(AState, AIndex); + + if lua_isfunction(AState, AIndex) then + FunctionValue := TLuaFunction.Create(AState, AIndex); +end; + + +{ TLuaCachedTable } +constructor TLuaCachedTable.Create(AState: lua_State; AIndex: Integer); +var + tableIndex: Integer; + key: ILuaVariable; + value: ILuaVariable; + +begin + inherited Create; + + lua_pushnil(AState); + + tableIndex := AIndex; + if AIndex < 0 then + Dec(tableIndex); + + while (lua_next(AState, tableIndex) <> 0) do + begin + key := TLuaCachedVariable.Create(AState, -2); + value := TLuaCachedVariable.Create(AState, -1); + + SetValue(key, value); + + { Remove value, keep key for the next iteration } + lua_pop(AState, 1); + end; +end; + + +{ TLuaParameters } +constructor TLuaParameters.Create; +begin + inherited Create; + + FParameters := TList.Create; +end; + + +destructor TLuaParameters.Destroy; +begin + FreeAndNil(FParameters); + + inherited Destroy; +end; + + +function TLuaParameters.GetCount: Integer; +begin + Result := FParameters.Count; +end; + + +function TLuaParameters.GetItem(Index: Integer): ILuaVariable; +begin + Result := FParameters[Index]; +end; + + +procedure TLuaParameters.Push(ABoolean: Boolean); +begin + FParameters.Add(TLuaVariable.Create(ABoolean)); +end; + + +procedure TLuaParameters.Push(AInteger: Integer); +begin + FParameters.Add(TLuaVariable.Create(AInteger)); +end; + + +procedure TLuaParameters.Push(ANumber: Double); +begin + FParameters.Add(TLuaVariable.Create(ANumber)); +end; + + +procedure TLuaParameters.Push(AUserData: Pointer); +begin + FParameters.Add(TLuaVariable.Create(AUserData)); +end; + + +procedure TLuaParameters.Push(const AString: string); +begin + FParameters.Add(TLuaVariable.Create(AString)); +end; + + +procedure TLuaParameters.Push(ATable: ILuaTable); +begin + FParameters.Add(TLuaVariable.Create(ATable)); +end; + + +{ TLuaContext } +constructor TLuaContext.Create(AState: lua_State); +begin + inherited Create; + + FParameters := TLuaStackParameters.Create(AState); + FResult := TLuaStackWriteParameters.Create(AState); +end; + + +function TLuaContext.GetParameters: ILuaReadParameters; +begin + Result := FParameters; +end; + + +function TLuaContext.GetResult: ILuaWriteParameters; +begin + Result := FResult; +end; + + +{ TLuaResult } +constructor TLuaStackWriteParameters.Create(AState: lua_State); +begin + inherited Create; + + FState := AState; +end; + + +function TLuaStackWriteParameters.GetCount: Integer; +begin + Result := FCount; +end; + + +procedure TLuaStackWriteParameters.Push(ABoolean: Boolean); +begin + lua_pushboolean(State, IfThen(ABoolean, 1, 0)); + Pushed; +end; + + +procedure TLuaStackWriteParameters.Push(AInteger: Integer); +begin + lua_pushinteger(State, AInteger); + Pushed; +end; + + +procedure TLuaStackWriteParameters.Push(ANumber: Double); +begin + lua_pushnumber(State, ANumber); + Pushed; +end; + + +procedure TLuaStackWriteParameters.Push(AUserData: Pointer); +begin + if AUserData = nil then + lua_pushnil(State) + else + lua_pushlightuserdata(State, AUserData); + + Pushed; +end; + + +procedure TLuaStackWriteParameters.Push(const AString: string); +var + value: PAnsiChar; + +begin + value := TLuaHelpers.AllocLuaString(AString); + try + lua_pushlstring(State, value, Length(AString)); + Pushed; + finally + TLuaHelpers.FreeLuaString(value); + end; +end; + + +procedure TLuaStackWriteParameters.Push(ATable: ILuaTable); +begin + TLuaHelpers.PushTable(State, ATable); + Pushed; +end; + + +procedure TLuaStackWriteParameters.Pushed; +begin + Inc(FCount); +end; + + +{ TLuaCFunction } +constructor TLuaFunction.Create(AState: lua_State; AIndex: Integer); +var + actualIndex: Integer; + +begin + inherited Create; + + FState := AState; + + // There is no way to retrieve the function in a way that allows pushing + // it back later. Instead, make use of Lua's registry: + // http://stackoverflow.com/questions/1416797/reference-to-lua-function-in-c-c + FRegistryKey := TLuaHelpers.NewRegistryKey; + actualIndex := AIndex; + + // If the index is relative to the top, compensate for pushing the key + if actualIndex < 0 then + Dec(actualIndex); + + TLuaHelpers.PushString(AState, RegistryKey); + lua_pushvalue(AState, actualIndex); + lua_rawset(AState, LUA_REGISTRYINDEX); +end; + + +destructor TLuaFunction.Destroy; +begin + TLuaHelpers.PushString(State, RegistryKey); + lua_pushnil(State); + lua_rawset(State, LUA_REGISTRYINDEX); + + inherited Destroy; +end; + + +function TLuaFunction.Call: ILuaReadParameters; +begin + Result := Call(nil); +end; + + +function TLuaFunction.Call(AParameters: array of const): ILuaReadParameters; +begin + Result := Call(TLuaHelpers.CreateParameters(AParameters)); +end; + + +function TLuaFunction.Call(AParameters: ILuaReadParameters): ILuaReadParameters; +begin + TLuaHelpers.PushString(State, RegistryKey); + lua_rawget(State, LUA_REGISTRYINDEX); + + Result := TLuaHelpers.CallFunction(State, AParameters); +end; + +end. diff --git a/G940LEDControl/DelphiLua/readme.txt b/G940LEDControl/DelphiLua/readme.txt new file mode 100644 index 0000000..cf1b522 --- /dev/null +++ b/G940LEDControl/DelphiLua/readme.txt @@ -0,0 +1 @@ +Source: https://git.x2software.net/delphi/delphilua \ No newline at end of file diff --git a/G940LEDControl/Forms/ButtonFunctionFrm.dfm b/G940LEDControl/Forms/ButtonFunctionFrm.dfm index 68959e6..7440a6c 100644 --- a/G940LEDControl/Forms/ButtonFunctionFrm.dfm +++ b/G940LEDControl/Forms/ButtonFunctionFrm.dfm @@ -255,14 +255,17 @@ object ButtonFunctionForm: TButtonFunctionForm Header.Font.Height = -11 Header.Font.Name = 'Tahoma' Header.Font.Style = [] - Header.Options = [hoAutoResize, hoColumnResize, hoDrag, hoShowSortGlyphs, hoVisible] + Header.Options = [hoAutoResize, hoColumnResize, hoDrag, hoShowSortGlyphs, hoVisible, hoHeaderClickAutoSort] + Header.SortColumn = 0 IncrementalSearch = isAll TabOrder = 1 TreeOptions.AutoOptions = [toAutoDropExpand, toAutoScrollOnExpand, toAutoSort, toAutoTristateTracking, toAutoDeleteMovedNodes] TreeOptions.MiscOptions = [toAcceptOLEDrop, toFullRepaintOnResize, toInitOnSave, toWheelPanning, toEditOnClick] TreeOptions.PaintOptions = [toShowButtons, toShowDropmark, toShowTreeLines, toThemeAware, toUseBlendedImages] TreeOptions.SelectionOptions = [toFullRowSelect] + OnCompareNodes = vstFunctionsCompareNodes OnFocusChanged = vstFunctionsFocusChanged + OnFreeNode = vstFunctionsFreeNode OnGetText = vstFunctionsGetText OnPaintText = vstFunctionsPaintText OnIncrementalSearch = vstFunctionsIncrementalSearch diff --git a/G940LEDControl/Forms/ButtonFunctionFrm.pas b/G940LEDControl/Forms/ButtonFunctionFrm.pas index f1f7f10..8153063 100644 --- a/G940LEDControl/Forms/ButtonFunctionFrm.pas +++ b/G940LEDControl/Forms/ButtonFunctionFrm.pas @@ -15,6 +15,7 @@ uses LEDColorIntf, LEDFunctionIntf, + LEDFunctionRegistry, LEDStateIntf, Profile, Vcl.ActnList; @@ -60,10 +61,12 @@ type procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); + procedure vstFunctionsFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure vstFunctionsFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure vstFunctionsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstFunctionsIncrementalSearch(Sender: TBaseVirtualTree; Node: PVirtualNode; const SearchText: string; var Result: Integer); procedure vstFunctionsPaintText(Sender: TBaseVirtualTree; const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType); + procedure vstFunctionsCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); private FProfile: TProfile; FButtonIndex: Integer; @@ -73,8 +76,9 @@ type FSelectedProvider: ILEDFunctionProvider; FSelectedFunction: ILEDFunction; FStateControls: TStateControlInfoList; + FFunctionRegistry: TLEDFunctionRegistry; protected - procedure Initialize(AProfile: TProfile; AButtonIndex: Integer); + procedure Initialize(AFunctionRegistry: TLEDFunctionRegistry; AProfile: TProfile; AButtonIndex: Integer); procedure LoadFunctions; procedure ApplyFilter(const AFilter: string); @@ -91,8 +95,9 @@ type property Profile: TProfile read FProfile; property ButtonIndex: Integer read FButtonIndex; + property FunctionRegistry: TLEDFunctionRegistry read FFunctionRegistry; public - class function Execute(AProfile: TProfile; AButtonIndex: Integer): Boolean; + class function Execute(AFunctionRegistry: TLEDFunctionRegistry; AProfile: TProfile; AButtonIndex: Integer): Boolean; end; @@ -118,7 +123,6 @@ uses System.SysUtils, Winapi.Windows, - LEDFunctionRegistry, LEDResources; @@ -150,11 +154,11 @@ const { TButtonFunctionForm } -class function TButtonFunctionForm.Execute(AProfile: TProfile; AButtonIndex: Integer): Boolean; +class function TButtonFunctionForm.Execute(AFunctionRegistry: TLEDFunctionRegistry; AProfile: TProfile; AButtonIndex: Integer): Boolean; begin with Self.Create(nil) do try - Initialize(AProfile, AButtonIndex); + Initialize(AFunctionRegistry, AProfile, AButtonIndex); Result := (ShowModal = mrOk); finally Free; @@ -247,7 +251,7 @@ begin categoryNodes := TDictionary.Create; try - for provider in TLEDFunctionRegistry.Providers do + for provider in FunctionRegistry.Providers do begin isCurrentProvider := Assigned(CurrentProvider) and (provider.GetUID = CurrentProvider.GetUID); @@ -371,8 +375,9 @@ begin end; -procedure TButtonFunctionForm.Initialize(AProfile: TProfile; AButtonIndex: Integer); +procedure TButtonFunctionForm.Initialize(AFunctionRegistry: TLEDFunctionRegistry; AProfile: TProfile; AButtonIndex: Integer); begin + FFunctionRegistry := AFunctionRegistry; FProfile := AProfile; FButtonIndex := AButtonIndex; FButton := nil; @@ -384,7 +389,7 @@ begin if Profile.HasButton(ButtonIndex) then begin FButton := Profile.Buttons[ButtonIndex]; - FCurrentProvider := TLEDFunctionRegistry.Find(Button.ProviderUID); + FCurrentProvider := FunctionRegistry.Find(Button.ProviderUID); if Assigned(CurrentProvider) then FCurrentFunction := CurrentProvider.Find(Button.FunctionUID); @@ -519,6 +524,38 @@ begin end; +procedure TButtonFunctionForm.vstFunctionsFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); +var + nodeData: PFunctionNodeData; + +begin + nodeData := Sender.GetNodeData(Node); + Finalize(nodeData^); +end; + + +procedure TButtonFunctionForm.vstFunctionsCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); +var + nodeData1: PFunctionNodeData; + nodeData2: PFunctionNodeData; + +begin + nodeData1 := Sender.GetNodeData(Node1); + nodeData2 := Sender.GetNodeData(Node2); + + if nodeData1^.NodeType <> nodeData2^.NodeType then + exit; + + case nodeData1^.NodeType of + ntCategory: + Result := CompareText(nodeData1^.LEDFunction.GetCategoryName, nodeData2^.LEDFunction.GetCategoryName); + + ntFunction: + Result := CompareText(nodeData1^.LEDFunction.GetDisplayName, nodeData2^.LEDFunction.GetDisplayName); + end; +end; + + procedure TButtonFunctionForm.vstFunctionsFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); var nodeData: PFunctionNodeData; diff --git a/G940LEDControl/Forms/MainFrm.dfm b/G940LEDControl/Forms/MainFrm.dfm index 2d46e27..70b89a6 100644 --- a/G940LEDControl/Forms/MainFrm.dfm +++ b/G940LEDControl/Forms/MainFrm.dfm @@ -1,7 +1,7 @@ object MainForm: TMainForm Left = 0 Top = 0 - ActiveControl = cmbProfiles + ActiveControl = cbCheckUpdates BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = 'G940 LED Control' @@ -30,7 +30,7 @@ object MainForm: TMainForm Margins.Top = 8 Margins.Right = 8 Margins.Bottom = 8 - ActivePage = tsButtons + ActivePage = tsAbout Align = alClient TabOrder = 0 object tsButtons: TTabSheet @@ -559,9 +559,9 @@ object MainForm: TMainForm object lblCopyright: TLabel Left = 16 Top = 35 - Width = 95 + Width = 129 Height = 13 - Caption = #169' 2011 X'#178'Software' + Caption = #169' 2011 - 2017 X'#178'Software' end object lblWebsite: TLabel Left = 16 @@ -1175,4 +1175,27 @@ object MainForm: TMainForm Left = 300 Top = 436 end + object ScriptErrorDialog: TTaskDialog + Buttons = < + item + Caption = '&Try again' + Default = True + CommandLinkHint = 'Reload all scripts' + ModalResult = 4 + end + item + Caption = '&Cancel' + CommandLinkHint = 'Exit G940LEDControl' + ModalResult = 8 + end> + CommonButtons = [] + ExpandedText = '' + Flags = [tfAllowDialogCancellation, tfUseCommandLinks, tfExpandedByDefault] + MainIcon = 2 + RadioButtons = <> + Text = '' + Title = 'Script error' + Left = 384 + Top = 376 + end end diff --git a/G940LEDControl/Forms/MainFrm.pas b/G940LEDControl/Forms/MainFrm.pas index 1fd6bb5..1be8b08 100644 --- a/G940LEDControl/Forms/MainFrm.pas +++ b/G940LEDControl/Forms/MainFrm.pas @@ -24,11 +24,12 @@ uses X2UtPersistIntf, ControlIntf, + LEDFunctionRegistry, FSXSimConnectIntf, LEDStateConsumer, Profile, ProfileManager, - Settings; + Settings, Vcl.Dialogs; const @@ -128,6 +129,7 @@ type TrayIcon: TTrayIcon; ApplicationEvents: TApplicationEvents; cbFSXSEAutoLaunch: TCheckBox; + ScriptErrorDialog: TTaskDialog; procedure FormCreate(Sender: TObject); procedure lblLinkLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); @@ -163,6 +165,8 @@ type FSettingsFileName: string; FSettings: TSettings; FLoadingSettings: Boolean; + + FFunctionRegistry: TLEDFunctionRegistry; protected procedure RegisterDeviceArrival; procedure UnregisterDeviceArrival; @@ -219,14 +223,16 @@ type property StateConsumerTask: IOmniTaskControl read FStateConsumerTask; property Log: IX2Log read FLog; + property FunctionRegistry: TLEDFunctionRegistry read FFunctionRegistry; end; implementation uses + System.IOUtils, System.SysUtils, + System.Types, System.Win.ComObj, - Vcl.Dialogs, Vcl.Graphics, Winapi.ShellAPI, @@ -241,13 +247,15 @@ uses ButtonFunctionFrm, ConfigConversion, FSXAutoLaunch, + FSXLEDFunctionProvider, FSXLEDFunctionProviderIntf, FSXResources, FSXSimConnectStateMonitor, G940LEDStateConsumer, LEDColorIntf, LEDFunctionIntf, - LEDFunctionRegistry, + LuaLEDFunctionProvider, + StaticLEDFunction, StaticResources; @@ -258,6 +266,9 @@ const DefaultProfileName = 'Default'; ProfilePostfixModified = ' (modified)'; + ScriptsPath = 'Scripts\'; + FSXScriptsPath = ScriptsPath + 'FSX\'; + UserDataPath = 'G940LEDControl\'; FilenameProfiles = UserDataPath + 'Profiles.xml'; FilenameSettings = UserDataPath + 'Settings.xml'; @@ -302,6 +313,8 @@ procedure TMainForm.FormCreate(Sender: TObject); var worker: IOmniWorker; + scriptPaths: TStringDynArray; + provider: ILEDFunctionProvider; begin FLog := TX2GlobalLog.Category('UI'); @@ -316,10 +329,48 @@ begin SetFSXState(TextFSXDisconnected, False); + + FFunctionRegistry := TLEDFunctionRegistry.Create; + FunctionRegistry.Register(TStaticLEDFunctionProvider.Create); + + SetLength(scriptPaths, 2); + scriptPaths[0] := App.Path + FSXScriptsPath; + scriptPaths[1] := App.UserPath + UserDataPath + FSXScriptsPath; + + if DebugHook <> 0 then + begin + SetLength(scriptPaths, 3); + scriptPaths[2] := TPath.GetFullPath(App.Path + '..\' + FSXScriptsPath); + end; + + while True do + begin + try + provider := TFSXLEDFunctionProvider.Create(scriptPaths); + Break; + except + on E:ELuaScriptLoadError do + begin + ScriptErrorDialog.Caption := Self.Caption; + ScriptErrorDialog.Text := Format('One or more errors occured while trying to load "%s"', [E.Filename]); + ScriptErrorDialog.ExpandedText := E.Message; + ScriptErrorDialog.Execute; + + if ScriptErrorDialog.ModalResult = mrClose then + begin + Application.Terminate; + Exit; + end; + end; + end; + end; + + FunctionRegistry.Register(provider); + FEventMonitor := TOmniEventMonitor.Create(Self); Log.Info('Starting G940 LED state consumer thread'); - worker := TG940LEDStateConsumer.Create(TX2GlobalLog.Category('G940 LED state consumer')); + worker := TG940LEDStateConsumer.Create(TX2GlobalLog.Category('G940 LED state consumer'), FunctionRegistry); FStateConsumerTask := EventMonitor.Monitor(CreateTask(worker)); EventMonitor.OnTaskMessage := EventMonitorMessage; @@ -362,6 +413,14 @@ begin TX2LogObserverMonitorForm.CloseInstance(TX2GlobalLog.Instance); TX2LogObserverMonitorForm.UnlockInstance(TX2GlobalLog.Instance); + + if Assigned(StateConsumerTask) then + begin + StateConsumerTask.Stop; + StateConsumerTask.WaitFor(INFINITE); + end; + + FreeAndNil(FFunctionRegistry); end; @@ -709,7 +768,7 @@ begin end; buttonFunction := nil; - provider := TLEDFunctionRegistry.Find(providerUID); + provider := FunctionRegistry.Find(providerUID); if Assigned(provider) then buttonFunction := provider.Find(functionUID); @@ -908,7 +967,7 @@ begin end; buttonIndex := (Sender as TComponent).Tag; - if TButtonFunctionForm.Execute(profile, buttonIndex) then + if TButtonFunctionForm.Execute(FunctionRegistry, profile, buttonIndex) then begin if newProfile then AddProfile(profile); @@ -1291,7 +1350,7 @@ var fsxProvider: IFSXLEDFunctionProvider; begin - if Supports(TLEDFunctionRegistry.Find(FSXProviderUID), IFSXLEDFunctionProvider, fsxProvider) then + if Supports(FunctionRegistry.Find(FSXProviderUID), IFSXLEDFunctionProvider, fsxProvider) then fsxProvider.SetProfileMenu(Settings.ProfileMenu, Settings.ProfileMenuCascaded); end; @@ -1301,7 +1360,7 @@ var fsxProvider: IFSXLEDFunctionProvider; begin - if Supports(TLEDFunctionRegistry.Find(FSXProviderUID), IFSXLEDFunctionProvider, fsxProvider) then + if Supports(FunctionRegistry.Find(FSXProviderUID), IFSXLEDFunctionProvider, fsxProvider) then fsxProvider.SetProfileMenu(False, False); end; diff --git a/G940LEDControl/G940LEDControl.dpr b/G940LEDControl/G940LEDControl.dpr index 0d25542..9dc91a2 100644 --- a/G940LEDControl/G940LEDControl.dpr +++ b/G940LEDControl/G940LEDControl.dpr @@ -38,7 +38,10 @@ uses FSXLEDFunctionProviderIntf in 'Units\FSXLEDFunctionProviderIntf.pas', SimBaseDocumentXMLBinding in 'Units\SimBaseDocumentXMLBinding.pas', FSXAutoLaunch in 'Units\FSXAutoLaunch.pas', - ControlIntf in 'Units\ControlIntf.pas'; + ControlIntf in 'Units\ControlIntf.pas', + Lua.API in 'DelphiLua\Lua.API.pas', + Lua in 'DelphiLua\Lua.pas', + LuaLEDFunctionProvider in 'Units\LuaLEDFunctionProvider.pas'; {$R *.res} @@ -50,14 +53,17 @@ var begin isRestarting := FindCmdLineSwitch('restart'); - while not SingleInstance('{67D1802F-2AB8-40B9-ADD7-14C9D36903C8}', False, False) do + if not FindCmdLineSwitch('multiinstance') then begin - Instance.Close; + while not SingleInstance('{67D1802F-2AB8-40B9-ADD7-14C9D36903C8}', False, False) do + begin + Instance.Close; - if not isRestarting then - exit; + if not isRestarting then + exit; - Sleep(1000); + Sleep(1000); + end; end; Application.Initialize; @@ -65,7 +71,6 @@ begin Application.ShowMainForm := not isRestarting; Application.Title := 'G940 LED Control'; Application.CreateForm(TMainForm, MainForm); - if isRestarting then MainForm.Visible := True; diff --git a/G940LEDControl/G940LEDControl.dproj b/G940LEDControl/G940LEDControl.dproj index 01e0c27..59bb1e2 100644 --- a/G940LEDControl/G940LEDControl.dproj +++ b/G940LEDControl/G940LEDControl.dproj @@ -49,23 +49,25 @@ true - 2 - rtl;dbrtl;$(DCC_UsePackage) + 6 + 1 + rtl;dbrtl;xmlrtl;$(DCC_UsePackage) Lib Bin ..\Shared;$(DCC_UnitSearchPath) - true None G940LEDControl_Icon.ico Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;System;Xml;Data;Datasnap;Web;Soap;Winapi;System.Win;$(DCC_Namespace) - CompanyName=X²Software;FileDescription=G940 LED Control;FileVersion=1.2.0.0;InternalName=;LegalCopyright=© 2011 - 2017 X²Software;LegalTrademarks=;OriginalFilename=G940LEDControl.exe;ProductName=G940 LED Control;ProductVersion=1.2;Comments= + CompanyName=X²Software;FileDescription=G940 LED Control;FileVersion=1.1.6.0;InternalName=;LegalCopyright=© 2011 - 2016 X²Software;LegalTrademarks=;OriginalFilename=G940LEDControl.exe;ProductName=G940 LED Control;ProductVersion=1.1;Comments= 1033 + vclx;vcl;vclactnband;$(DCC_UsePackage) G940LEDControl_Icon.ico $(BDS)\bin\default_app.manifest + vclx;vcl;vclactnband;$(DCC_UsePackage) false false false @@ -73,6 +75,11 @@ $(BDS)\bin\default_app.manifest + true + 0 + 2 + CompanyName=X²Software;FileDescription=G940 LED Control;FileVersion=2.0.0.0;InternalName=;LegalCopyright=© 2011 - 2017 X²Software;LegalTrademarks=;OriginalFilename=G940LEDControl.exe;ProductName=G940 LED Control;ProductVersion=2.0;Comments= + 0 7.0 False False @@ -94,8 +101,7 @@ False - /restart - false + /multiinstance CompanyName=;FileDescription=;FileVersion=1.1.3.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProductName=;ProductVersion=0.2;Comments= $(BDS)\bin\default_app.manifest @@ -141,6 +147,9 @@ + + + Cfg_2 Base diff --git a/G940LEDControl/G940LEDControl.res b/G940LEDControl/G940LEDControl.res index 99a53a8..6bf97bc 100644 Binary files a/G940LEDControl/G940LEDControl.res and b/G940LEDControl/G940LEDControl.res differ diff --git a/G940LEDControl/Scripts/FSX/autopilot.lua b/G940LEDControl/Scripts/FSX/autopilot.lua new file mode 100644 index 0000000..20ffd99 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/autopilot.lua @@ -0,0 +1,45 @@ +local strings = require './lib/strings' + + +local function RegisterAutopilotFunction(functionUid, functionDisplayName, variableName) + RegisterFunction( + { + uid = functionUid, + category = strings.Category.FSX.AutoPilot, + displayName = functionDisplayName, + states = { + notAvailable = { displayName = 'Not available', default = LEDColor.Off, order = 1 }, + on = { displayName = 'On', default = LEDColor.Green, order = 2 }, + off = { displayName = 'Off', default = LEDColor.Red, order = 3 } + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + autoPilotAvailable = { variable = 'AUTOPILOT AVAILABLE', type = SimConnectDataType.Bool }, + autoPilotState = { variable = variableName, type = SimConnectDataType.Bool } + }, + function(context, data) + if data.autoPilotAvailable then + if data.autoPilotState then + SetState(context, 'on') + else + SetState(context, 'off') + end + else + SetState(context, 'notAvailable') + end + end) + end + ) +end + +RegisterAutopilotFunction('autoPilotMaster', 'Autopilot master', 'AUTOPILOT MASTER') +RegisterAutopilotFunction('autoPilotHeading', 'Autopilot heading', 'AUTOPILOT HEADING LOCK') +RegisterAutopilotFunction('autoPilotApproach', 'Autopilot approach', 'AUTOPILOT APPROACH HOLD') +RegisterAutopilotFunction('autoPilotBackcourse', 'Autopilot backcourse', 'AUTOPILOT BACKCOURSE HOLD') +RegisterAutopilotFunction('autoPilotAltitude', 'Autopilot altitude', 'AUTOPILOT ALTITUDE LOCK') +RegisterAutopilotFunction('autoPilotNav', 'Autopilot nav', 'AUTOPILOT NAV1 LOCK') +RegisterAutopilotFunction('autoPilotAirspeed', 'Autopilot airspeed', 'AUTOPILOT AIRSPEED HOLD') diff --git a/G940LEDControl/Scripts/FSX/controlsurfaces.lua b/G940LEDControl/Scripts/FSX/controlsurfaces.lua new file mode 100644 index 0000000..e37b857 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/controlsurfaces.lua @@ -0,0 +1,262 @@ +local strings = require './lib/strings' + + +-- Flaps +RegisterFunction( + { + uid = 'flaps', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Flaps', + states = { + notAvailable = { displayName = 'No flaps', default = LEDColor.Off, order = 1 }, + retracted = { displayName = 'Retracted', default = LEDColor.Green, order = 2 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 3 }, + extended = { displayName = 'Extended', default = LEDColor.Red, order = 4 }, + speedExceeded = { displayName = 'Speed exceeded', default = LEDColor.FlashingAmberNormal, order = 5 }, + damageBySpeed = { displayName = 'Damage by speed', default = LEDColor.FlashingRedFast, order = 6 } + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + flapsAvailable = { variable = 'FLAPS AVAILABLE', type = SimConnectDataType.Bool }, + percentageExtended = { variable = 'FLAPS HANDLE PERCENT', type = SimConnectDataType.Float64, units = 'percent' }, + damageBySpeed = { variable = 'FLAP DAMAGE BY SPEED', type = SimConnectDataType.Bool }, + speedExceeded = { variable = 'FLAP SPEED EXCEEDED', type = SimConnectDataType.Bool }, + }, + function(context, data) + if data.damageBySpeed then + SetState(context, 'damageBySpeed') + elseif data.speedExceeded then + SetState(context, 'speedExceeded') + elseif data.flapsAvailable then + local extended = math.floor(data.percentageExtended) + + if extended >= 0 and extended <= 5 then + SetState(context, 'retracted') + elseif extended >= 95 and extended <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + else + SetState(context, 'notAvailable') + end + end) + end +) + +-- Flaps (handle position) +RegisterFunction( + { + uid = 'flapsHandleIndex', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Flaps (handle position)', + states = { + ['notAvailable'] = { displayName = 'Not available', default = LEDColor.Off, order = 1 }, + ['0'] = { displayName = 'Position 0 (Up)', default = LEDColor.Green, order = 2 }, + ['1'] = { displayName = 'Position 1', default = LEDColor.Amber, order = 3 }, + ['2'] = { displayName = 'Position 2', default = LEDColor.Amber, order = 4 }, + ['3'] = { displayName = 'Position 3', default = LEDColor.Amber, order = 5 }, + ['4'] = { displayName = 'Position 4', default = LEDColor.Amber, order = 6 }, + ['5'] = { displayName = 'Position 5', default = LEDColor.Amber, order = 7 }, + ['6'] = { displayName = 'Position 6', default = LEDColor.Amber, order = 8 }, + ['7'] = { displayName = 'Position 7', default = LEDColor.Amber, order = 9 }, + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + flapsAvailable = { variable = 'FLAPS AVAILABLE', type = SimConnectDataType.Bool }, + index = { variable = 'FLAPS HANDLE INDEX', type = SimConnectDataType.Int32, units = 'number' } + }, + function(context, data) + if data.flapsAvailable then + local index = data.index + if index < 0 then + index = 0 + end + + if index > 7 then + index = 7 + end + + SetState(context, tostring(index)) + else + SetState(context, 'notAvailable') + end + end) + end +) + + +-- Flaps (handle position - percentage) +RegisterFunction( + { + uid = 'flapsHandlePercentage', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Flaps (handle position - percentage)', + states = { + ['notAvailable'] = { displayName = 'Not available', default = LEDColor.Off, order = 1 }, + ['0To10'] = { displayName = '0% - 10%', default = LEDColor.Green, order = 2 }, + ['10To20'] = { displayName = '10% - 20%', default = LEDColor.Amber, order = 3 }, + ['20To30'] = { displayName = '20% - 30%', default = LEDColor.Amber, order = 4 }, + ['30To40'] = { displayName = '30% - 40%', default = LEDColor.Amber, order = 5 }, + ['40To50'] = { displayName = '40% - 50%', default = LEDColor.Amber, order = 6 }, + ['50To60'] = { displayName = '50% - 60%', default = LEDColor.Amber, order = 7 }, + ['60To70'] = { displayName = '60% - 70%', default = LEDColor.Amber, order = 8 }, + ['70To80'] = { displayName = '70% - 80%', default = LEDColor.Amber, order = 9 }, + ['80To90'] = { displayName = '80% - 90%', default = LEDColor.Amber, order = 9 }, + ['90To100'] = { displayName = '90% - 100%', default = LEDColor.Amber, order = 9 }, + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + flapsAvailable = { variable = 'FLAPS AVAILABLE', type = SimConnectDataType.Bool }, + position = { variable = 'FLAPS HANDLE PERCENT', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.flapsAvailable then + if data.position <= 9 then + SetState(context, '0To10') + elseif data.position >= 10 and data.position <= 19 then + SetState(context, '10To20') + elseif data.position >= 20 and data.position <= 29 then + SetState(context, '20To30') + elseif data.position >= 30 and data.position <= 39 then + SetState(context, '30To40') + elseif data.position >= 40 and data.position <= 49 then + SetState(context, '40To50') + elseif data.position >= 50 and data.position <= 59 then + SetState(context, '50To60') + elseif data.position >= 60 and data.position <= 69 then + SetState(context, '60To70') + elseif data.position >= 70 and data.position <= 79 then + SetState(context, '70To80') + elseif data.position >= 80 and data.position <= 89 then + SetState(context, '80To90') + elseif data.position >= 90 then + SetState(context, '90To100') + end + else + SetState(context, 'notAvailable') + end + end) + end +) + + +-- Spoilers +RegisterFunction( + { + uid = 'spoilers', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Spoilers', + states = { + notAvailable = { displayName = 'No spoilers', default = LEDColor.Off, order = 1 }, + retracted = { displayName = 'Retracted', default = LEDColor.Green, order = 2 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 3 }, + extended = { displayName = 'Extended', default = LEDColor.Red, order = 4 } + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + available = { variable = 'SPOILER AVAILABLE', type = SimConnectDataType.Bool }, + percentageExtended = { variable = 'SPOILERS HANDLE POSITION', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.available then + local extended = math.floor(data.percentageExtended) + + if extended >= 0 and extended <= 5 then + SetState(context, 'retracted') + elseif extended >= 95 and extended <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + else + SetState(context, 'notAvailable') + end + end) + end +) + + +-- Auto-spoilers armed +RegisterFunction( + { + uid = 'spoilersArmed', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Auto-spoilers armed', + states = { + notAvailable = { displayName = 'No spoilers', default = LEDColor.Off, order = 1 }, + on = { displayName = 'On', default = LEDColor.Red, order = 2 }, + off = { displayName = 'Off', default = LEDColor.Green, order = 3 } + } + }, + function(context) + SetState(context, 'notAvailable') + + OnSimConnect(context, + { + available = { variable = 'SPOILER AVAILABLE', type = SimConnectDataType.Bool }, + armed = { variable = 'SPOILERS ARMED', type = SimConnectDataType.Bool } + }, + function(context, data) + if data.available then + if data.armed then + SetState(context, 'on') + else + SetState(context, 'off') + end + else + SetState(context, 'notAvailable') + end + end) + end +) + + +-- Water rudder +RegisterFunction( + { + uid = 'waterRudder', + category = strings.Category.FSX.ControlSurfaces, + displayName = 'Water rudder', + states = { + retracted = { displayName = 'Retracted', default = LEDColor.Green, order = 1 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 2 }, + extended = { displayName = 'Extended', default = LEDColor.Red, order = 3 } + } + }, + function(context) + SetState(context, 'retracted') + + OnSimConnect(context, + { + position = { variable = 'WATER RUDDER HANDLE POSITION', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + local position = math.floor(data.position) + + if position >= 0 and position <= 5 then + SetState(context, 'retracted') + elseif position >= 95 and position <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + end) + end +) \ No newline at end of file diff --git a/G940LEDControl/Scripts/FSX/engines.lua b/G940LEDControl/Scripts/FSX/engines.lua new file mode 100644 index 0000000..0a540df --- /dev/null +++ b/G940LEDControl/Scripts/FSX/engines.lua @@ -0,0 +1,181 @@ +local strings = require './lib/strings' + + +-- Carb heat / engine anti-ice +RegisterFunction( + { + uid = 'engineAntiIce', + category = strings.Category.FSX.Engines, + displayName = 'Carb heat / engine anti-ice', + states = { + noEngines = { displayName = 'No engines', default = LEDColor.Off, order = 1 }, + all = { displayName = 'All', default = LEDColor.Red, order = 2 }, + partial = { displayName = 'Partial', default = LEDColor.Amber, order = 3 }, + none = { displayName = 'None', default = LEDColor.Green, order = 4 } + } + }, + function(context) + SetState(context, 'noEngines') + + OnSimConnect(context, + { + engineCount = { variable = 'NUMBER OF ENGINES', type = SimConnectDataType.Int32, units = 'number' }, + engine1 = { variable = 'ENG ANTI ICE:1', type = SimConnectDataType.Bool }, + engine2 = { variable = 'ENG ANTI ICE:2', type = SimConnectDataType.Bool }, + engine3 = { variable = 'ENG ANTI ICE:3', type = SimConnectDataType.Bool }, + engine4 = { variable = 'ENG ANTI ICE:4', type = SimConnectDataType.Bool } + }, + function(context, data) + if data.engineCount > 0 then + local antiIceCount = 0 + + if data.engine1 then antiIceCount = antiIceCount + 1 end + if data.engineCount >= 2 and data.engine2 then antiIceCount = antiIceCount + 1 end + if data.engineCount >= 3 and data.engine3 then antiIceCount = antiIceCount + 1 end + if data.engineCount >= 4 and data.engine4 then antiIceCount = antiIceCount + 1 end + + if antiIceCount == 0 then + SetState(context, 'none') + elseif antiIceCount == data.engineCount then + SetState(context, 'all') + else + SetState(context, 'partial') + end + else + SetState(context, 'noEngines') + end + end) + end +) + + +-- Engine +RegisterFunction( + { + uid = 'engine', + category = strings.Category.FSX.Engines, + displayName = 'Engine', + states = { + noEngines = { displayName = 'No engines', default = LEDColor.Off, order = 1 }, + allRunning = { displayName = 'All running', default = LEDColor.Green, order = 2 }, + partiallyRunning = { displayName = 'Partially running', default = LEDColor.Amber, order = 3 }, + allOff = { displayName = 'All off', default = LEDColor.Red, order = 4 }, + failed = { displayName = 'Engine failure', default = LEDColor.FlashingRedNormal, order = 5 }, + onFire = { displayName = 'On fire', default = LEDColor.FlashingRedFast, order = 6 }, + } + }, + function(context) + SetState(context, 'noEngines') + + OnSimConnect(context, + { + engineCount = { variable = 'NUMBER OF ENGINES', type = SimConnectDataType.Int32, units = 'number' }, + combustion1 = { variable = 'GENERAL ENG COMBUSTION:1', type = SimConnectDataType.Bool }, + combustion2 = { variable = 'GENERAL ENG COMBUSTION:2', type = SimConnectDataType.Bool }, + combustion3 = { variable = 'GENERAL ENG COMBUSTION:3', type = SimConnectDataType.Bool }, + combustion4 = { variable = 'GENERAL ENG COMBUSTION:4', type = SimConnectDataType.Bool }, + failed1 = { variable = 'ENG FAILED:1', type = SimConnectDataType.Bool }, + failed2 = { variable = 'ENG FAILED:2', type = SimConnectDataType.Bool }, + failed3 = { variable = 'ENG FAILED:3', type = SimConnectDataType.Bool }, + failed4 = { variable = 'ENG FAILED:4', type = SimConnectDataType.Bool }, + onfire1 = { variable = 'ENG ON FIRE:1', type = SimConnectDataType.Bool }, + onfire2 = { variable = 'ENG ON FIRE:2', type = SimConnectDataType.Bool }, + onfire3 = { variable = 'ENG ON FIRE:3', type = SimConnectDataType.Bool }, + onfire4 = { variable = 'ENG ON FIRE:4', type = SimConnectDataType.Bool } + }, + function(context, data) + if data.engineCount > 0 then + local runningCount = 0 + local hasFailed = false + local hasFire = false + + if data.combustion1 then runningCount = runningCount + 1 end + if data.failed1 then hasFailed = true end + if data.onfire1 then hasFire = true end + + if data.engineCount >= 2 and data.combustion2 then runningCount = runningCount + 1 end + if data.engineCount >= 2 and data.failed2 then hasFailed = true end + if data.engineCount >= 2 and data.onfire2 then hasFire = true end + + if data.engineCount >= 3 and data.combustion3 then runningCount = runningCount + 1 end + if data.engineCount >= 3 and data.failed3 then hasFailed = true end + if data.engineCount >= 3 and data.onfire3 then hasFire = true end + + if data.engineCount >= 4 and data.combustion4 then runningCount = runningCount + 1 end + if data.engineCount >= 4 and data.failed4 then hasFailed = true end + if data.engineCount >= 4 and data.onfire4 then hasFire = true end + + if hasFire then + SetState(context, 'onFire') + elseif hasFailed then + SetState(context, 'failed') + elseif runningCount == 0 then + SetState(context, 'allOff') + elseif runningCount == data.engineCount then + SetState(context, 'allRunning') + else + SetState(context, 'partiallyRunning') + end + else + SetState(context, 'noEngines') + end + end) + end +) + + + +-- Throttle +RegisterFunction( + { + uid = 'throttle', + category = strings.Category.FSX.Engines, + displayName = 'Throttle', + states = { + noEngines = { displayName = 'No engines', default = LEDColor.Off, order = 1 }, + off = { displayName = 'Off', default = LEDColor.Green, order = 2 }, + partial = { displayName = 'Partial', default = LEDColor.Amber, order = 3 }, + full = { displayName = 'Full', default = LEDColor.Red, order = 4 }, + reverse = { displayName = 'Reversed', default = LEDColor.FlashingAmberNormal, order = 5 } + } + }, + function(context) + SetState(context, 'noEngines') + + OnSimConnect(context, + { + engineCount = { variable = 'NUMBER OF ENGINES', type = SimConnectDataType.Int32, units = 'number' }, + position1 = { variable = 'GENERAL ENG THROTTLE LEVER POSITION:1', type = SimConnectDataType.Float64, units = 'percent' }, + position2 = { variable = 'GENERAL ENG THROTTLE LEVER POSITION:2', type = SimConnectDataType.Float64, units = 'percent' }, + position3 = { variable = 'GENERAL ENG THROTTLE LEVER POSITION:3', type = SimConnectDataType.Float64, units = 'percent' }, + position4 = { variable = 'GENERAL ENG THROTTLE LEVER POSITION:4', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.engineCount > 0 then + local totalPosition = 0 + local reverse = false + + if data.position1 < 0 then reverse = true else totalPosition = totalPosition + data.position1 end + if data.engineCount >= 2 and data.position2 < 0 then reverse = true else totalPosition = totalPosition + data.position2 end + if data.engineCount >= 3 and data.position3 < 0 then reverse = true else totalPosition = totalPosition + data.position3 end + if data.engineCount >= 4 and data.position4 < 0 then reverse = true else totalPosition = totalPosition + data.position4 end + + if reverse then + SetState(context, 'reverse') + else + local position = math.floor(totalPosition / data.engineCount) + + if position >= 0 and position <= 5 then + SetState(context, 'off') + elseif position >= 95 and position <= 100 then + SetState(context, 'full') + else + SetState(context, 'partial') + end + end + else + SetState(context, 'noEngines') + end + end) + end +) \ No newline at end of file diff --git a/G940LEDControl/Scripts/FSX/instruments.lua b/G940LEDControl/Scripts/FSX/instruments.lua new file mode 100644 index 0000000..a507bd0 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/instruments.lua @@ -0,0 +1,73 @@ +local basefunctions = require './lib/basefunctions' +local strings = require './lib/strings' + + +-- Pitot heat (on / off only) +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Instruments, + uid = 'pitotOnOff', + displayName = 'Pitot heat (on / off only)', + variable = 'PITOT HEAT' +}) + + +-- Pitot heat (including warnings) +RegisterFunction( + { + uid = 'pitotWarning', + category = strings.Category.FSX.Instruments, + displayName = 'Pitot heat (including warnings)', + states = { + ['off0'] = { displayName = 'Heat off - No ice', default = LEDColor.Red, order = 1 }, + ['off25To50'] = { displayName = 'Heat off - > 25% iced', default = LEDColor.FlashingAmberNormal, order = 2 }, + ['off50To75'] = { displayName = 'Heat off - > 50% iced', default = LEDColor.FlashingAmberFast, order = 3 }, + ['off75To100'] = { displayName = 'Heat off - > 75% iced', default = LEDColor.FlashingAmberFast, order = 4 }, + ['off100'] = { displayName = 'Heat off - Fully iced', default = LEDColor.FlashingRedFast, order = 5 }, + ['on0'] = { displayName = 'Heat on - No ice', default = LEDColor.FlashingRedNormal, order = 6 }, + ['on25To50'] = { displayName = 'Heat on - > 25% iced', default = LEDColor.Amber, order = 7 }, + ['on50To75'] = { displayName = 'Heat on - > 50% iced', default = LEDColor.Amber, order = 8 }, + ['on75To100'] = { displayName = 'Heat on - > 75% iced', default = LEDColor.Amber, order = 9 }, + ['on100'] = { displayName = 'Heat on - Fully iced', default = LEDColor.Green, order = 10 } + } + }, + function(context) + SetState(context, 'off0') + + OnSimConnect(context, + { + heat = { variable = 'PITOT HEAT', type = SimConnectDataType.Bool }, + ice = { variable = 'PITOT ICE PCT', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + local ice = math.floor(data.ice) + local prefix = 'off' + + if data.heat then + prefix = 'on' + end + + if ice >= 25 and ice <= 49 then + SetState(context, prefix..'25To50') + elseif ice >= 50 and ice <= 74 then + SetState(context, prefix..'50To75') + elseif ice >= 75 and ice <= 99 then + SetState(context, prefix..'75To100') + elseif ice == 100 then + SetState(context, prefix..'100') + else + SetState(context, prefix..'0') + end + end) + end +) + + + + + + + + + + + diff --git a/G940LEDControl/Scripts/FSX/lib/basefunctions.lua b/G940LEDControl/Scripts/FSX/lib/basefunctions.lua new file mode 100644 index 0000000..49a5fe8 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/lib/basefunctions.lua @@ -0,0 +1,49 @@ +local basefunctions = {} + +-- Required keys for info: +-- uid +-- category +-- displayName +-- variable (SimConnect boolean-compatible variable name) +-- +-- Optional keys: +-- inverted (Off is Green instead of Red) +basefunctions.RegisterOnOffFunction = function(info) + if info.inverted then + onOffStates = { + on = { displayName = 'On', default = LEDColor.Green, order = 1 }, + off = { displayName = 'Off', default = LEDColor.Red, order = 2 } + } + else + onOffStates = { + on = { displayName = 'On', default = LEDColor.Red, order = 1 }, + off = { displayName = 'Off', default = LEDColor.Green, order = 2 } + } + end + + RegisterFunction( + { + uid = info.uid, + category = info.category, + displayName = info.displayName, + states = onOffStates + }, + function(context) + SetState(context, 'on') + + OnSimConnect(context, + { + value = { variable = info.variable, type = SimConnectDataType.Bool } + }, + function(context, data) + if data.value then + SetState(context, 'on') + else + SetState(context, 'off') + end + end) + end + ) +end + +return basefunctions \ No newline at end of file diff --git a/G940LEDControl/Scripts/FSX/lib/strings.lua b/G940LEDControl/Scripts/FSX/lib/strings.lua new file mode 100644 index 0000000..e0e61ad --- /dev/null +++ b/G940LEDControl/Scripts/FSX/lib/strings.lua @@ -0,0 +1,16 @@ +local strings = {} + +strings.Category = {} + +strings.Category.FSX = {} +strings.Category.FSX.Default = 'Flight Simulator X' +strings.Category.FSX.AutoPilot = strings.Category.FSX.Default..' - Autopilot' +strings.Category.FSX.ControlSurfaces = strings.Category.FSX.Default..' - Control surfaces' +strings.Category.FSX.Engines = strings.Category.FSX.Default..' - Engines' +strings.Category.FSX.Instruments = strings.Category.FSX.Default..' - Instruments' +strings.Category.FSX.Lights = strings.Category.FSX.Default..' - Lights' +strings.Category.FSX.Panels = strings.Category.FSX.Default..' - Panels' +strings.Category.FSX.Radios = strings.Category.FSX.Default..' - Radios' +strings.Category.FSX.Systems = strings.Category.FSX.Default..' - Systems' + +return strings \ No newline at end of file diff --git a/G940LEDControl/Scripts/FSX/lights.lua b/G940LEDControl/Scripts/FSX/lights.lua new file mode 100644 index 0000000..b66d782 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/lights.lua @@ -0,0 +1,64 @@ +local strings = require './lib/strings' + +-- Lights +local function RegisterLightsFunction(functionUid, functionDisplayName, lightsMask) + RegisterFunction( + { + uid = functionUid, + category = strings.Category.FSX.Lights, + displayName = functionDisplayName, + states = { + on = { displayName = 'On', default = LEDColor.Green, order = 1 }, + off = { displayName = 'Off', default = LEDColor.Red, order = 2 } + } + }, + function(context) + SetState(context, 'on') + + OnSimConnect(context, + { + states = { variable = 'LIGHT ON STATES', type = SimConnectDataType.Int32, units = 'mask' } + }, + function(context, data) + if bit32.band(data.states, lightsMask) ~= 0 then + SetState(context, 'on') + else + SetState(context, 'off') + end + end) + end +) +end + + +local LightsMaskNav = 0x0001 +local LightsMaskBeacon = 0x0002 +local LightsMaskLanding = 0x0004 +local LightsMaskTaxi = 0x0008 +local LightsMaskStrobe = 0x0010 +local LightsMaskPanel = 0x0020 +local LightsMaskRecognition = 0x0040 +local LightsMaskWing = 0x0080 +local LightsMaskLogo = 0x0100 +local LightsMaskCabin = 0x0200 + +local LightsMaskAll = bit32.bor( + LightsMaskNav, + LightsMaskBeacon, + LightsMaskLanding, + LightsMaskTaxi, + LightsMaskStrobe, + LightsMaskPanel, + LightsMaskRecognition, + LightsMaskWing, + LightsMaskLogo, + LightsMaskCabin +) + + +RegisterLightsFunction('beaconLights', 'Beacon lights', LightsMaskBeacon) +RegisterLightsFunction('navLights', 'Nav lights', LightsMaskNav) +RegisterLightsFunction('strobeLights', 'Strobe lights', LightsMaskStrobe) +RegisterLightsFunction('taxiLights', 'Taxi lights', LightsMaskTaxi) +RegisterLightsFunction('recognitionLights', 'Recognition lights', LightsMaskRecognition) +RegisterLightsFunction('allLights', 'All lights', LightsMaskAll) diff --git a/G940LEDControl/Scripts/FSX/panels.lua b/G940LEDControl/Scripts/FSX/panels.lua new file mode 100644 index 0000000..591fce6 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/panels.lua @@ -0,0 +1,28 @@ +local strings = require './lib/strings' + + + +-- ATC panel +RegisterFunction( + { + uid = 'atcVisiblity', + category = strings.Category.FSX.Panels, + displayName = 'ATC panel', + states = { + hidden = { displayName = 'Hidden', default = LEDColor.Green, order = 1 }, + visible = { displayName = 'Visible', default = LEDColor.FlashingAmberNormal, order = 2 }, + } + }, + function(context) + SetState(context, 'hidden') + + OnTimer(context, 1000, + function(context) + if FSXWindowVisible('ATC Menu') then + SetState(context, 'visible') + else + SetState(context, 'hidden') + end + end) + end +) diff --git a/G940LEDControl/Scripts/FSX/radios.lua b/G940LEDControl/Scripts/FSX/radios.lua new file mode 100644 index 0000000..f730438 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/radios.lua @@ -0,0 +1,11 @@ +local basefunctions = require './lib/basefunctions' +local strings = require './lib/strings' + + +-- Avionics master +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Radios, + uid = 'avionicsMaster', + displayName = 'Avionics master', + variable = 'AVIONICS MASTER SWITCH' +}) diff --git a/G940LEDControl/Scripts/FSX/systems.lua b/G940LEDControl/Scripts/FSX/systems.lua new file mode 100644 index 0000000..0d4b623 --- /dev/null +++ b/G940LEDControl/Scripts/FSX/systems.lua @@ -0,0 +1,302 @@ +local basefunctions = require './lib/basefunctions' +local strings = require './lib/strings' + + +-- Battery master +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Systems, + uid = 'batteryMaster', + displayName = 'Battery Master', + variable = 'ELECTRICAL MASTER BATTERY' +}) + + +-- De-ice +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Systems, + uid = 'structuralDeIce', + displayName = "De-ice", + variable = 'STRUCTURAL DEICE SWITCH' +}) + + +-- Exit door +RegisterFunction( + { + uid = 'exitDoor', + category = strings.Category.FSX.Systems, + displayName = 'Exit door', + states = { + closed = { displayName = 'Closed', default = LEDColor.Green, order = 1 }, + between = { displayName = 'Opening / closing', default = LEDColor.Amber, order = 2 }, + open = { displayName = 'Open', default = LEDColor.Red, order = 3 } + } + }, + function(context) + SetState(context, 'closed') + + OnSimConnect(context, + { + canopyOpen = { variable = 'CANOPY OPEN', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.canopyOpen >= 0 and data.canopyOpen <= 5 then + SetState(context, 'closed') + elseif data.canopyOpen >= 95 and data.canopyOpen <= 100 then + SetState(context, 'open') + else + SetState(context, 'between') + end + end) + end +) + + +-- Landing gears +local function registerGearFunction(functionUid, functionDisplayName, variableName, isFloat) + RegisterFunction( + { + uid = functionUid, + category = strings.Category.FSX.Systems, + displayName = functionDisplayName, + states = { + notRetractable = { displayName = 'Not retractable', default = LEDColor.Off, order = 1 }, + retracted = { displayName = 'Retracted', default = LEDColor.Red, order = 2 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 3 }, + extended = { displayName = 'Extended', default = LEDColor.Green, order = 4 }, + speedExceeded = { displayName = 'Speed exceeded', default = LEDColor.FlashingAmberNormal, order = 5 }, + damageBySpeed = { displayName = 'Damage by speed', default = LEDColor.FlashingRedFast, order = 6 } + } + }, + function(context) + SetState(context, 'notRetractable') + + OnSimConnect(context, + { + isGearRetractable = { variable = 'IS GEAR RETRACTABLE', type = SimConnectDataType.Bool }, + percentageExtended = { variable = variableName, type = SimConnectDataType.Float64, units = 'percent' }, + damageBySpeed = { variable = 'GEAR DAMAGE BY SPEED', type = SimConnectDataType.Bool }, + speedExceeded = { variable = 'GEAR SPEED EXCEEDED', type = SimConnectDataType.Bool }, + }, + function(context, data) + if data.damageBySpeed then + SetState(context, 'damageBySpeed') + elseif data.speedExceeded then + SetState(context, 'speedExceeded') + elseif data.isGearRetractable then + local extended = data.percentageExtended + + if isFloat then + extended = extended * 100 + end + + extended = math.floor(extended) + if extended == 0 then + SetState(context, 'retracted') + elseif extended >= 95 and extended <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + else + SetState(context, 'notRetractable') + end + end) + end + ) +end + + +registerGearFunction('gear', 'Landing gear', 'GEAR TOTAL PCT EXTENDED', true) +registerGearFunction('leftGear', 'Left main landing gear', 'GEAR LEFT POSITION', false) +registerGearFunction('rightGear', 'Right main landing gear', 'GEAR RIGHT POSITION', false) +registerGearFunction('centerGear', 'Nose landing gear', 'GEAR CENTER POSITION', false) +registerGearFunction('tailGear', 'Tail landing gear', 'GEAR TAIL POSITION', false) + + +-- Parking brake +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Systems, + uid = 'parkingBrake', + displayName = 'Parking brake', + variable = 'BRAKE PARKING INDICATOR' +}) + + +-- Auto brake +RegisterFunction( + { + uid = 'autoBrake', + category = strings.Category.FSX.Systems, + displayName = 'Auto brake', + states = { + ['0'] = { displayName = 'Off / not available', default = LEDColor.Green, order = 1 }, + ['1'] = { displayName = '1', default = LEDColor.Amber, order = 2 }, + ['2'] = { displayName = '2', default = LEDColor.Amber, order = 3 }, + ['3'] = { displayName = '3', default = LEDColor.Amber, order = 4 }, + ['4'] = { displayName = '4', default = LEDColor.Red, order = 5 } + } + }, + function(context) + SetState(context, '0') + + OnSimConnect(context, + { + switch = { variable = 'AUTO BRAKE SWITCH CB', type = SimConnectDataType.Int32, units = 'number' } + }, + function(context, data) + local switch = 4 + + if data.switch >= 0 and data.switch <= 4 then + switch = data.switch + end + + SetState(context, tostring(switch)) + end) + end +) + + +-- Pressurization dump switch +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Systems, + uid = 'pressurizationDumpSwitch', + displayName = 'Pressurization dump switch', + variable = 'PRESSURIZATION DUMP SWITCH' +}) + + +-- Tail hook +RegisterFunction( + { + uid = 'tailHook', + category = strings.Category.FSX.Systems, + displayName = 'Tail hook', + states = { + retracted = { displayName = 'Retracted', default = LEDColor.Green, order = 1 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 2 }, + extended = { displayName = 'Extended', default = LEDColor.Red, order = 3 } + } + }, + function(context) + SetState(context, 'retracted') + + OnSimConnect(context, + { + position = { variable = 'TAILHOOK POSITION', type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.position >= 0 and data.position <= 5 then + SetState(context, 'retracted') + elseif data.position >= 95 and data.position <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + end) + end +) + + +-- Tail wheel lock +basefunctions.RegisterOnOffFunction({ + category = strings.Category.FSX.Systems, + uid = 'tailWheelLock', + displayName = 'Tail wheel lock', + variable = 'TAILWHEEL LOCK ON' +}) + + +-- Float (left) +local function RegisterFloatFunction(functionUid, functionDisplayName, variableName) + RegisterFunction( + { + uid = functionUid, + category = strings.Category.FSX.Systems, + displayName = functionDisplayName, + states = { + retracted = { displayName = 'Retracted', default = LEDColor.Red, order = 1 }, + between = { displayName = 'Extending / retracting', default = LEDColor.Amber, order = 2 }, + extended = { displayName = 'Extended', default = LEDColor.Green, order = 3 } + } + }, + function(context) + SetState(context, 'retracted') + + OnSimConnect(context, + { + position = { variable = variableName, type = SimConnectDataType.Float64, units = 'percent' } + }, + function(context, data) + if data.position >= 0 and data.position <= 5 then + SetState(context, 'retracted') + elseif data.position >= 95 and data.position <= 100 then + SetState(context, 'extended') + else + SetState(context, 'between') + end + end) + end + ) +end + +RegisterFloatFunction('floatLeft', 'Float (left)', 'RETRACT LEFT FLOAT EXTENDED') +RegisterFloatFunction('floatRight', 'Float (right)', 'RETRACT RIGHT FLOAT EXTENDED') + + +-- Fuel level +RegisterFunction( + { + uid = 'fuelLevel', + category = strings.Category.FSX.Systems, + displayName = 'Fuel level', + states = { + ['notAvailable'] = { displayName = 'Not available', default = LEDColor.Off, order = 1 }, + ['empty'] = { displayName = 'Empty', default = LEDColor.FlashingRedFast, order = 2 }, + ['0To1'] = { displayName = '< 1%', default = LEDColor.FlashingRedNormal, order = 3 }, + ['1To2'] = { displayName = '< 2%', default = LEDColor.FlashingRedNormal, order = 4 }, + ['2To5'] = { displayName = '< 5%', default = LEDColor.Red, order = 5 }, + ['5To10'] = { displayName = '< 10%', default = LEDColor.Amber, order = 6 }, + ['10To20'] = { displayName = '< 20%', default = LEDColor.Amber, order = 7 }, + ['20To50'] = { displayName = '< 50%', default = LEDColor.Green, order = 8 }, + ['50To75'] = { displayName = '< 75%', default = LEDColor.Green, order = 9 }, + ['75To100'] = { displayName = '75% - Full', default = LEDColor.Green, order = 10 } + } + }, + function(context) + SetState(context, '75To100') + + OnSimConnect(context, + { + capacity = { variable = 'FUEL TOTAL CAPACITY', type = SimConnectDataType.Float64, units = 'number' }, + quantity = { variable = 'FUEL TOTAL QUANTITY', type = SimConnectDataType.Float64, units = 'number' } + }, + function(context, data) + if data.capacity > 0 then + local percentage = math.ceil(data.quantity / data.capacity * 100) + + if percentage == 0 then + SetState(context, 'empty') + elseif percentage == 1 then + SetState(context, '0To1') + elseif percentage == 2 then + SetState(context, '1To2') + elseif percentage >= 3 and percentage <= 5 then + SetState(context, '2To5') + elseif percentage >= 6 and percentage <= 10 then + SetState(context, '5To10') + elseif percentage >= 11 and percentage <= 20 then + SetState(context, '10To20') + elseif percentage >= 21 and percentage <= 50 then + SetState(context, '20To50') + elseif percentage >= 51 and percentage <= 75 then + SetState(context, '50To75') + else + SetState(context, '75To100') + end + else + SetState(context, 'notAvailable') + end + end) + end +) \ No newline at end of file diff --git a/G940LEDControl/Scripts/G940LEDControl.Scripts.sublime-project b/G940LEDControl/Scripts/G940LEDControl.Scripts.sublime-project new file mode 100644 index 0000000..22aeefa --- /dev/null +++ b/G940LEDControl/Scripts/G940LEDControl.Scripts.sublime-project @@ -0,0 +1,9 @@ +{ + "folders": + [ + { + "path": ".", + "file_exclude_patterns": ["*.sublime-project"] + } + ] +} diff --git a/G940LEDControl/Units/FSXLEDFunction.pas b/G940LEDControl/Units/FSXLEDFunction.pas index a9bce87..638ee9b 100644 --- a/G940LEDControl/Units/FSXLEDFunction.pas +++ b/G940LEDControl/Units/FSXLEDFunction.pas @@ -1,6 +1,7 @@ unit FSXLEDFunction; interface + (* uses FSXLEDFunctionProvider, LEDFunction, @@ -337,9 +338,11 @@ type function GetWorkerClass: TCustomLEDMultiStateFunctionWorkerClass; override; end; + *) implementation +(* uses FSXLEDFunctionWorker, FSXResources, @@ -1086,6 +1089,6 @@ end; function TFSXATCVisibilityFunction.GetWorkerClass: TCustomLEDMultiStateFunctionWorkerClass; begin Result := TFSXATCVisibilityFunctionWorker; -end; +end;*) end. diff --git a/G940LEDControl/Units/FSXLEDFunctionProvider.pas b/G940LEDControl/Units/FSXLEDFunctionProvider.pas index 76782f0..d0306ef 100644 --- a/G940LEDControl/Units/FSXLEDFunctionProvider.pas +++ b/G940LEDControl/Units/FSXLEDFunctionProvider.pas @@ -4,79 +4,80 @@ interface uses Generics.Collections, System.SyncObjs, + System.Types, X2Log.Intf, + Lua, FSXLEDFunctionProviderIntf, FSXSimConnectIntf, LEDFunction, LEDFunctionIntf, - LEDStateIntf; + LEDStateIntf, + LuaLEDFunctionProvider; type - TCustomFSXFunction = class; - TCustomFSXFunctionList = TObjectList; + TFSXLEDFunctionWorker = class; - TFSXLEDFunctionProvider = class(TCustomLEDFunctionProvider, IFSXLEDFunctionProvider, IFSXSimConnectObserver) + TFSXLEDFunctionProvider = class(TCustomLuaLEDFunctionProvider, IFSXLEDFunctionProvider, IFSXSimConnectObserver) private FSimConnect: TInterfacedObject; FSimConnectLock: TCriticalSection; FProfileMenuSimConnect: IFSXSimConnectProfileMenu; protected - procedure RegisterFunctions; override; - function GetUID: string; override; - protected + function CreateLuaLEDFunction(AInfo: ILuaTable; AOnSetup: ILuaFunction): TCustomLuaLEDFunction; override; + + procedure InitInterpreter; override; + procedure ScriptOnSimConnect(Context: ILuaContext); + procedure ScriptFSXWindowVisible(Context: ILuaContext); + + procedure SetupWorker(AWorker: TFSXLEDFunctionWorker; AOnSetup: ILuaFunction); + { IFSXSimConnectObserver } procedure ObserveDestroy(Sender: IFSXSimConnect); { IFSXLEDFunctionProvider } procedure SetProfileMenu(AEnabled: Boolean; ACascaded: Boolean); public - constructor Create; + constructor Create(const AScriptFolders: TStringDynArray); destructor Destroy; override; function GetSimConnect: IFSXSimConnect; end; - TCustomFSXFunction = class(TCustomMultiStateLEDFunction) + TFSXLEDFunction = class(TCustomLuaLEDFunction) private FProvider: TFSXLEDFunctionProvider; - FDisplayName: string; - FUID: string; protected + function GetDefaultCategoryName: string; override; + + function GetWorkerClass: TCustomLEDMultiStateFunctionWorkerClass; override; procedure InitializeWorker(AWorker: TCustomLEDMultiStateFunctionWorker); override; property Provider: TFSXLEDFunctionProvider read FProvider; - protected - function GetCategoryName: string; override; - function GetDisplayName: string; override; - function GetUID: string; override; public - constructor Create(AProvider: TFSXLEDFunctionProvider; const ADisplayName, AUID: string); + constructor Create(AProvider: TFSXLEDFunctionProvider; AInfo: ILuaTable; AOnSetup: ILuaFunction); end; + TFSXDefinition = record + ID: Cardinal; + DataHandler: IFSXSimConnectDataHandler; + end; - TCustomFSXFunctionClass = class of TCustomFSXFunction; - - - TCustomFSXFunctionWorker = class(TCustomLEDMultiStateFunctionWorker) + TFSXLEDFunctionWorker = class(TCustomLuaLEDFunctionWorker) private - FDataHandler: IFSXSimConnectDataHandler; - FDefinitionID: Cardinal; + FDefinitions: TList; FSimConnect: IFSXSimConnect; protected - procedure RegisterVariables(ADefinition: IFSXSimConnectDefinition); virtual; abstract; - - procedure SetSimConnect(const Value: IFSXSimConnect); virtual; - - property DataHandler: IFSXSimConnectDataHandler read FDataHandler; - property DefinitionID: Cardinal read FDefinitionID; - property SimConnect: IFSXSimConnect read FSimConnect write SetSimConnect; + property Definitions: TList read FDefinitions; protected + function GetSimConnect: IFSXSimConnect; + procedure AddDefinition(ADefinition: IFSXSimConnectDefinition; ADataHandler: IFSXSimConnectDataHandler); + procedure HandleData(AData: Pointer); virtual; abstract; public constructor Create(const AProviderUID, AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string = ''); override; @@ -86,6 +87,7 @@ type implementation uses + System.Classes, System.SysUtils, X2Log.Global, @@ -98,100 +100,227 @@ uses type - TCustomFSXFunctionWorkerDataHandler = class(TInterfacedObject, IFSXSimConnectDataHandler) + TLuaSimConnectDataType = ( + // Native types + Float64, Float32, Int64, Int32, StringValue, + + // Preprocessed types (for scripting convenience) + Bool, + + // Structures + XYZ, LatLonAlt, Waypoint + ); + + + TLuaSimConnectVariable = record + Name: string; + DataType: TLuaSimConnectDataType; + end; + + + TFSXFunctionWorkerDataHandler = class(TInterfacedObject, IFSXSimConnectDataHandler) private - FWorker: TCustomFSXFunctionWorker; + FOnData: ILuaFunction; + FWorkerID: string; + FVariables: TList; protected { IFSXSimConnectDataHandler } procedure HandleData(AData: Pointer); - property Worker: TCustomFSXFunctionWorker read FWorker; + property OnData: ILuaFunction read FOnData; + property Variables: TList read FVariables; + property WorkerID: string read FWorkerID; public - constructor Create(AWorker: TCustomFSXFunctionWorker); + constructor Create(AVariables: TList; const AWorkerID: string; AOnData: ILuaFunction); + destructor Destroy; override; end; +const + LuaSimConnectDataTypes: array[TLuaSimConnectDataType] of string = + ( + 'Float64', 'Float32', 'Int64', 'Int32', 'String', + 'Bool', + 'XYZ', 'LatLonAlt', 'Waypoint' + ); + + +function GetDataType(const ATypeName: string; out ADataType: TLuaSimConnectDataType): Boolean; +var + dataType: TLuaSimConnectDataType; + +begin + for dataType := Low(TLuaSimConnectDataType) to High(TLuaSimConnectDataType) do + if SameText(ATypeName, LuaSimConnectDataTypes[dataType]) then + begin + ADataType := dataType; + Exit(True); + end; + + Result := False; +end; + { TFSXLEDFunctionProvider } -constructor TFSXLEDFunctionProvider.Create; +constructor TFSXLEDFunctionProvider.Create(const AScriptFolders: TStringDynArray); begin - inherited Create; - FSimConnectLock := TCriticalSection.Create; + + inherited Create(AScriptFolders); end; destructor TFSXLEDFunctionProvider.Destroy; begin - FreeAndNil(FSimConnectLock); - inherited Destroy; + + FreeAndNil(FSimConnectLock); end; -procedure TFSXLEDFunctionProvider.RegisterFunctions; +function TFSXLEDFunctionProvider.CreateLuaLEDFunction(AInfo: ILuaTable; AOnSetup: ILuaFunction): TCustomLuaLEDFunction; begin - { Systems } - RegisterFunction(TFSXBatteryMasterFunction.Create( Self, FSXFunctionDisplayNameBatteryMaster, FSXFunctionUIDBatteryMaster)); - RegisterFunction(TFSXDeIceFunction.Create( Self, FSXFunctionDisplayNameDeIce, FSXFunctionUIDDeIce)); - RegisterFunction(TFSXExitDoorFunction.Create( Self, FSXFunctionDisplayNameExitDoor, FSXFunctionUIDExitDoor)); - RegisterFunction(TFSXGearFunction.Create( Self, FSXFunctionDisplayNameGear, FSXFunctionUIDGear)); - RegisterFunction(TFSXLeftGearFunction.Create( Self, FSXFunctionDisplayNameLeftGear, FSXFunctionUIDLeftGear)); - RegisterFunction(TFSXRightGearFunction.Create( Self, FSXFunctionDisplayNameRightGear, FSXFunctionUIDRightGear)); - RegisterFunction(TFSXCenterGearFunction.Create( Self, FSXFunctionDisplayNameCenterGear, FSXFunctionUIDCenterGear)); - RegisterFunction(TFSXTailGearFunction.Create( Self, FSXFunctionDisplayNameTailGear, FSXFunctionUIDTailGear)); - RegisterFunction(TFSXParkingBrakeFunction.Create( Self, FSXFunctionDisplayNameParkingBrake, FSXFunctionUIDParkingBrake)); - RegisterFunction(TFSXAutoBrakeFunction.Create( Self, FSXFunctionDisplayNameAutoBrake, FSXFunctionUIDAutoBrake)); - RegisterFunction(TFSXPressDumpSwitchFunction.Create( Self, FSXFunctionDisplayNamePressDumpSwitch, FSXFunctionUIDPressDumpSwitch)); - RegisterFunction(TFSXTailHookFunction.Create( Self, FSXFunctionDisplayNameTailHook, FSXFunctionUIDTailHook)); - RegisterFunction(TFSXTailWheelLockFunction.Create( Self, FSXFunctionDisplayNameTailWheelLock, FSXFunctionUIDTailWheelLock)); - RegisterFunction(TFSXFloatLeftFunction.Create( Self, FSXFunctionDisplayNameFloatLeft, FSXFunctionUIDFloatLeft)); - RegisterFunction(TFSXFloatRightFunction.Create( Self, FSXFunctionDisplayNameFloatRight, FSXFunctionUIDFloatRight)); + Result := TFSXLEDFunction.Create(Self, AInfo, AOnSetup); +end; - { Instruments } - RegisterFunction(TFSXPitotOnOffFunction.Create( Self, FSXFunctionDisplayNamePitotOnOff, FSXFunctionUIDPitotOnOff)); - RegisterFunction(TFSXPitotWarningFunction.Create( Self, FSXFunctionDisplayNamePitotWarning, FSXFunctionUIDPitotWarning)); - { Engines } - RegisterFunction(TFSXEngineAntiIceFunction.Create( Self, FSXFunctionDisplayNameEngineAntiIce, FSXFunctionUIDEngineAntiIce)); - RegisterFunction(TFSXEngineFunction.Create( Self, FSXFunctionDisplayNameEngine, FSXFunctionUIDEngine)); - RegisterFunction(TFSXThrottleFunction.Create( Self, FSXFunctionDisplayNameThrottle, FSXFunctionUIDThrottle)); +procedure TFSXLEDFunctionProvider.InitInterpreter; +var + simConnectDataType: ILuaTable; + dataType: TLuaSimConnectDataType; - { Control surfaces } - RegisterFunction(TFSXFlapsFunction.Create( Self, FSXFunctionDisplayNameFlaps, FSXFunctionUIDFlaps)); - RegisterFunction(TFSXFlapsHandleIndexFunction.Create( Self, FSXFunctionDisplayNameFlapsHandleIndex, FSXFunctionUIDFlapsHandleIndex)); - RegisterFunction(TFSXFlapsHandlePercentageFunction.Create(Self, FSXFunctionDisplayNameFlapsHandlePercentage, FSXFunctionUIDFlapsHandlePercentage)); - RegisterFunction(TFSXSpoilersFunction.Create( Self, FSXFunctionDisplayNameSpoilers, FSXFunctionUIDSpoilers)); - RegisterFunction(TFSXSpoilersArmedFunction.Create( Self, FSXFunctionDisplayNameSpoilersArmed, FSXFunctionUIDSpoilersArmed)); - RegisterFunction(TFSXWaterRudderFunction.Create( Self, FSXFunctionDisplayNameWaterRudder, FSXFunctionUIDWaterRudder)); +begin + inherited InitInterpreter; - { Lights } - RegisterFunction(TFSXBeaconLightsFunction.Create( Self, FSXFunctionDisplayNameBeaconLights, FSXFunctionUIDBeaconLights)); - RegisterFunction(TFSXInstrumentLightsFunction.Create( Self, FSXFunctionDisplayNameInstrumentLights, FSXFunctionUIDInstrumentLights)); - RegisterFunction(TFSXLandingLightsFunction.Create( Self, FSXFunctionDisplayNameLandingLights, FSXFunctionUIDLandingLights)); - RegisterFunction(TFSXNavLightsFunction.Create( Self, FSXFunctionDisplayNameNavLights, FSXFunctionUIDNavLights)); - RegisterFunction(TFSXRecognitionLightsFunction.Create( Self, FSXFunctionDisplayNameRecognitionLights, FSXFunctionUIDRecognitionLights)); - RegisterFunction(TFSXStrobeLightsFunction.Create( Self, FSXFunctionDisplayNameStrobeLights, FSXFunctionUIDStrobeLights)); - RegisterFunction(TFSXTaxiLightsFunction.Create( Self, FSXFunctionDisplayNameTaxiLights, FSXFunctionUIDTaxiLights)); - RegisterFunction(TFSXAllLightsFunction.Create( Self, FSXFunctionDisplayNameAllLights, FSXFunctionUIDAllLights)); + Interpreter.RegisterFunction('OnSimConnect', ScriptOnSimConnect); + Interpreter.RegisterFunction('FSXWindowVisible', ScriptFSXWindowVisible); - { Autopilot } - RegisterFunction(TFSXAutoPilotFunction.Create( Self, FSXFunctionDisplayNameAutoPilot, FSXFunctionUIDAutoPilot)); - RegisterFunction(TFSXAutoPilotAltitudeFunction.Create( Self, FSXFunctionDisplayNameAutoPilotAltitude, FSXFunctionUIDAutoPilotAltitude)); - RegisterFunction(TFSXAutoPilotApproachFunction.Create( Self, FSXFunctionDisplayNameAutoPilotApproach, FSXFunctionUIDAutoPilotApproach)); - RegisterFunction(TFSXAutoPilotBackcourseFunction.Create( Self, FSXFunctionDisplayNameAutoPilotBackcourse, FSXFunctionUIDAutoPilotBackcourse)); - RegisterFunction(TFSXAutoPilotHeadingFunction.Create( Self, FSXFunctionDisplayNameAutoPilotHeading, FSXFunctionUIDAutoPilotHeading)); - RegisterFunction(TFSXAutoPilotNavFunction.Create( Self, FSXFunctionDisplayNameAutoPilotNav, FSXFunctionUIDAutoPilotNav)); - RegisterFunction(TFSXAutoPilotAirspeedFunction.Create( Self, FSXFunctionDisplayNameAutoPilotAirspeed, FSXFunctionUIDAutoPilotAirspeed)); + simConnectDataType := TLuaTable.Create; + for dataType := Low(TLuaSimConnectDataType) to High(TLuaSimConnectDataType) do + simConnectDataType.SetValue(LuaSimConnectDataTypes[dataType], LuaSimConnectDataTypes[dataType]); - { Radios } - RegisterFunction(TFSXAvionicsMasterFunction.Create( Self, FSXFunctionDisplayNameAvionicsMaster, FSXFunctionUIDAvionicsMaster)); + Interpreter.SetGlobalVariable('SimConnectDataType', simConnectDataType); +end; - { Fuel } - RegisterFunction(TFSXFuelFunction.Create( Self, FSXFunctionDisplayNameFuel, FSXFunctionUIDFuel)); - { ATC } - RegisterFunction(TFSXATCVisibilityFunction.Create(FSXProviderUID)); +procedure TFSXLEDFunctionProvider.ScriptOnSimConnect(Context: ILuaContext); +var + workerID: string; + variables: ILuaTable; + onData: ILuaFunction; + worker: TCustomLuaLEDFunctionWorker; + definition: IFSXSimConnectDefinition; + variable: TLuaKeyValuePair; + info: ILuaTable; + dataType: TLuaSimConnectDataType; + simConnectDataType: SIMCONNECT_DATAType; + units: string; + luaVariables: TList; + luaVariable: TLuaSimConnectVariable; + +begin + CheckParameters('OnSimConnect', Context.Parameters, [VariableString, VariableTable, VariableFunction]); + + workerID := Context.Parameters[0].AsString; + variables := Context.Parameters[1].AsTable; + onData := Context.Parameters[2].AsFunction; + + worker := FindWorker(workerID); + if not Assigned(worker) then + raise ELuaScriptError.Create('OnSimConnect: invalid context'); + + definition := GetSimConnect.CreateDefinition; + + luaVariables := TList.Create; + try + for variable in variables do + begin + if variable.Value.VariableType = VariableTable then + begin + info := variable.Value.AsTable; + if info.HasValue('variable') then + begin + luaVariable.Name := variable.Key.AsString; + units := ''; + simConnectDataType := SIMCONNECT_DATAType_FLOAT64; + + if info.HasValue('type') and GetDataType(info.GetValue('type').AsString, dataType) then + begin + luaVariable.DataType := dataType; + + case dataType of + Float32: simConnectDataType := SIMCONNECT_DATAType_FLOAT32; + Int64: simConnectDataType := SIMCONNECT_DATAType_INT64; + Int32, + Bool: + begin + simConnectDataType := SIMCONNECT_DATAType_INT32; + units := 'bool'; + end; + + // TODO change to STRINGV + StringValue: simConnectDataType := SIMCONNECT_DATAType_STRING256; + XYZ: simConnectDataType := SIMCONNECT_DATAType_XYZ; + LatLonAlt: simConnectDataType := SIMCONNECT_DATAType_LATLONALT; + Waypoint: simConnectDataType := SIMCONNECT_DATAType_WAYPOINT; + end; + + if info.HasValue('units') then + units := info.GetValue('units').AsString + else if not (dataType in [Bool, StringValue, XYZ, LatLonAlt, Waypoint]) then + raise ELuaScriptError.CreateFmt('OnSimConnect: missing units for variable %s', [variable.Key.AsString]); + end else + begin + if not info.HasValue('units') then + raise ELuaScriptError.CreateFmt('OnSimConnect: missing units or type for variable %s', [variable.Key.AsString]); + + units := info.GetValue('units').AsString; + end; + + luaVariables.Add(luaVariable); + definition.AddVariable(info.GetValue('variable').AsString, units, simConnectDataType); + end; + end; + end; + + (worker as TFSXLEDFunctionWorker).AddDefinition(definition, TFSXFunctionWorkerDataHandler.Create(luaVariables, worker.UID, onData)); + finally + FreeAndNil(luaVariables); + end; +end; + + +procedure TFSXLEDFunctionProvider.ScriptFSXWindowVisible(Context: ILuaContext); +const + ClassNameMainWindow = 'FS98MAIN'; + ClassNameChildWindow = 'FS98CHILD'; + ClassNameFloatWindow = 'FS98FLOAT'; + +var + windowTitle: string; + +begin + CheckParameters('FSXWindowVisible', Context.Parameters, [VariableString]); + windowTitle := Context.Parameters[0].AsString; + + Context.Result.Push( + { Docked } + WindowVisible(ClassNameChildWindow, windowTitle, ClassNameMainWindow, '') or + + { Undocked } + WindowVisible(ClassNameFloatWindow, windowTitle, '', '')); +end; + + +// #ToDo1 -oMvR: 4-6-2017: move up to LuaLEDFunctionProvider +procedure TFSXLEDFunctionProvider.SetupWorker(AWorker: TFSXLEDFunctionWorker; AOnSetup: ILuaFunction); +begin + try + AOnSetup.Call([AWorker.UID]); + except + on E:Exception do + TX2GlobalLog.Category('Lua').Exception(E); + end; end; @@ -245,95 +374,233 @@ end; -{ TCustomFSXFunction } -constructor TCustomFSXFunction.Create(AProvider: TFSXLEDFunctionProvider; const ADisplayName, AUID: string); +{ TFSXLEDFunction } +constructor TFSXLEDFunction.Create(AProvider: TFSXLEDFunctionProvider; AInfo: ILuaTable; AOnSetup: ILuaFunction); begin - inherited Create(AProvider.GetUID); + inherited Create(AProvider, AInfo, AOnSetup); FProvider := AProvider; - FDisplayName := ADisplayName; - FUID := AUID; end; -procedure TCustomFSXFunction.InitializeWorker(AWorker: TCustomLEDMultiStateFunctionWorker); -begin - (AWorker as TCustomFSXFunctionWorker).SimConnect := Provider.GetSimConnect; -end; - - -function TCustomFSXFunction.GetCategoryName: string; +function TFSXLEDFunction.GetDefaultCategoryName: string; begin Result := FSXCategory; end; -function TCustomFSXFunction.GetDisplayName: string; +function TFSXLEDFunction.GetWorkerClass: TCustomLEDMultiStateFunctionWorkerClass; begin - Result := FDisplayName; + Result := TFSXLEDFunctionWorker; end; -function TCustomFSXFunction.GetUID: string; +procedure TFSXLEDFunction.InitializeWorker(AWorker: TCustomLEDMultiStateFunctionWorker); +var + worker: TFSXLEDFunctionWorker; + begin - Result := FUID; + worker := (AWorker as TFSXLEDFunctionWorker); + worker.Provider := Provider; + + Provider.SetupWorker(worker, Setup); end; -{ TCustomFSXFunctionWorker } -constructor TCustomFSXFunctionWorker.Create(const AProviderUID, AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string); +{ TFSXLEDFunctionWorker } +constructor TFSXLEDFunctionWorker.Create(const AProviderUID, AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string); begin - { We can't pass ourselves as the Data Handler, as it would keep a reference to - this worker from the SimConnect interface. That'd mean the worker never - gets destroyed, and SimConnect never shuts down. Hence this proxy class. } - FDataHandler := TCustomFSXFunctionWorkerDataHandler.Create(Self); + FDefinitions := TList.Create; inherited Create(AProviderUID, AFunctionUID, AStates, ASettings, APreviousState); end; -destructor TCustomFSXFunctionWorker.Destroy; +destructor TFSXLEDFunctionWorker.Destroy; +var + simConnect: IFSXSimConnect; + definition: TFSXDefinition; + begin - if DefinitionID <> 0 then - SimConnect.RemoveDefinition(DefinitionID, DataHandler); + if Assigned(Provider) and (Definitions.Count > 0) then + begin + simConnect := (Provider as TFSXLEDFunctionProvider).GetSimConnect; + + for definition in Definitions do + simConnect.RemoveDefinition(definition.ID, definition.DataHandler); + end; + + FreeAndNil(FDefinitions); inherited Destroy; end; -procedure TCustomFSXFunctionWorker.SetSimConnect(const Value: IFSXSimConnect); -var - definition: IFSXSimConnectDefinition; - +function TFSXLEDFunctionWorker.GetSimConnect: IFSXSimConnect; begin - FSimConnect := Value; + if not Assigned(FSimConnect) then + FSimConnect := (Provider as TFSXLEDFunctionProvider).GetSimConnect; - if Assigned(SimConnect) then - begin - definition := SimConnect.CreateDefinition; - RegisterVariables(definition); - - FDefinitionID := SimConnect.AddDefinition(definition, DataHandler); - end; + Result := FSimConnect; end; -{ TCustomFSXFunctionWorkerDataHandler } -constructor TCustomFSXFunctionWorkerDataHandler.Create(AWorker: TCustomFSXFunctionWorker); +procedure TFSXLEDFunctionWorker.AddDefinition(ADefinition: IFSXSimConnectDefinition; ADataHandler: IFSXSimConnectDataHandler); +var + definition: TFSXDefinition; + +begin + definition.DataHandler := ADataHandler; + definition.ID := GetSimConnect.AddDefinition(ADefinition, ADataHandler); + + Definitions.Add(definition); +end; + + +{ TFSXFunctionWorkerDataHandler } +constructor TFSXFunctionWorkerDataHandler.Create(AVariables: TList; const AWorkerID: string; AOnData: ILuaFunction); begin inherited Create; - FWorker := AWorker; + FWorkerID := AWorkerID; + FOnData := AOnData; + + FVariables := TList.Create; + FVariables.AddRange(AVariables); end; -procedure TCustomFSXFunctionWorkerDataHandler.HandleData(AData: Pointer); +destructor TFSXFunctionWorkerDataHandler.Destroy; begin - Worker.HandleData(AData); + FreeAndNil(FVariables); + + inherited Destroy; end; -initialization - TLEDFunctionRegistry.Register(TFSXLEDFunctionProvider.Create); +procedure TFSXFunctionWorkerDataHandler.HandleData(AData: Pointer); +var + data: ILuaTable; + dataPointer: PByte; + variableIndex: Integer; + variable: TLuaSimConnectVariable; + value: string; + structure: ILuaTable; + flags: ILuaTable; + xyzData: ^SIMCONNECT_DATA_XYZ; + latLonAltData: ^SIMCONNECT_DATA_LATLONALT; + waypointData: ^SIMCONNECT_DATA_WAYPOINT; + +begin + data := TLuaTable.Create; + dataPointer := AData; + + for variableIndex := 0 to Pred(Variables.Count) do + begin + variable := Variables[variableIndex]; + + case variable.DataType of + Float64: + begin + data.SetValue(variable.Name, PDouble(dataPointer)^); + Inc(dataPointer, SizeOf(Double)); + end; + + Float32: + begin + data.SetValue(variable.Name, PSingle(dataPointer)^); + Inc(dataPointer, SizeOf(Single)); + end; + + Int64: + begin + data.SetValue(variable.Name, PInt64(dataPointer)^); + Inc(dataPointer, SizeOf(Int64)); + end; + + Int32: + begin + data.SetValue(variable.Name, PInteger(dataPointer)^); + Inc(dataPointer, SizeOf(Integer)); + end; + + StringValue: + begin + // TODO change to STRINGV + //SimConnect_RetrieveString() + + SetString(value, PChar(dataPointer), 256); + data.SetValue(variable.Name, value); + + Inc(dataPointer, 256); + end; + + Bool: + begin + data.SetValue(variable.Name, (PInteger(dataPointer)^ <> 0)); + Inc(dataPointer, SizeOf(Integer)); + end; + + XYZ: + begin + xyzData := AData; + + structure := TLuaTable.Create; + structure.SetValue('X', xyzData^.x); + structure.SetValue('Y', xyzData^.y); + structure.SetValue('Z', xyzData^.z); + + data.SetValue(variable.Name, structure); + Inc(dataPointer, SizeOf(SIMCONNECT_DATA_XYZ)); + end; + + LatLonAlt: + begin + latLonAltData := AData; + + structure := TLuaTable.Create; + structure.SetValue('Latitude', latLonAltData^.Latitude); + structure.SetValue('Longitude', latLonAltData^.Longitude); + structure.SetValue('Altitude', latLonAltData^.Altitude); + + data.SetValue(variable.Name, structure); + Inc(dataPointer, SizeOf(SIMCONNECT_DATA_LATLONALT)); + end; + + Waypoint: + begin + waypointData := AData; + + structure := TLuaTable.Create; + structure.SetValue('Latitude', waypointData^.Latitude); + structure.SetValue('Longitude', waypointData^.Longitude); + structure.SetValue('Altitude', waypointData^.Altitude); + structure.SetValue('KtsSpeed', waypointData^.ktsSpeed); + structure.SetValue('PercentThrottle', waypointData^.percentThrottle); + + flags := TLuaTable.Create; + flags.SetValue('SpeedRequested', (waypointData^.Flags and SIMCONNECT_WAYPOINT_SPEED_REQUESTED) <> 0); + flags.SetValue('ThrottleRequested', (waypointData^.Flags and SIMCONNECT_WAYPOINT_THROTTLE_REQUESTED) <> 0); + flags.SetValue('ComputeVerticalSpeed', (waypointData^.Flags and SIMCONNECT_WAYPOINT_COMPUTE_VERTICAL_SPEED) <> 0); + flags.SetValue('IsAGL', (waypointData^.Flags and SIMCONNECT_WAYPOINT_ALTITUDE_IS_AGL) <> 0); + flags.SetValue('OnGround', (waypointData^.Flags and SIMCONNECT_WAYPOINT_ON_GROUND) <> 0); + flags.SetValue('Reverse', (waypointData^.Flags and SIMCONNECT_WAYPOINT_REVERSE) <> 0); + flags.SetValue('WrapToFirst', (waypointData^.Flags and SIMCONNECT_WAYPOINT_WRAP_TO_FIRST) <> 0); + + structure.SetValue('Flags', flags); + + data.SetValue(variable.Name, structure); + Inc(dataPointer, SizeOf(SIMCONNECT_DATA_WAYPOINT)); + end; + end; + end; + + try + OnData.Call([WorkerID, data]); + except + on E:Exception do + TX2GlobalLog.Category('Lua').Exception(E); + end; +end; end. diff --git a/G940LEDControl/Units/FSXLEDFunctionWorker.pas b/G940LEDControl/Units/FSXLEDFunctionWorker.pas index f8f9303..3dfaa37 100644 --- a/G940LEDControl/Units/FSXLEDFunctionWorker.pas +++ b/G940LEDControl/Units/FSXLEDFunctionWorker.pas @@ -1,6 +1,7 @@ unit FSXLEDFunctionWorker; interface +(* uses OtlTaskControl, @@ -268,9 +269,10 @@ type constructor Create(const AProviderUID: string; const AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string = ''); override; destructor Destroy; override; end; - +*) implementation +(* uses System.Math, System.StrUtils, @@ -1181,6 +1183,6 @@ begin FVisible := visible; FOnStateChanged(visible); end; -end; +end;*) end. diff --git a/G940LEDControl/Units/FSXSimConnectClient.pas b/G940LEDControl/Units/FSXSimConnectClient.pas index a00c1ae..5100502 100644 --- a/G940LEDControl/Units/FSXSimConnectClient.pas +++ b/G940LEDControl/Units/FSXSimConnectClient.pas @@ -88,12 +88,12 @@ const type TFSXSimConnectDefinitionRef = class(TObject) private - FDefinition: IFSXSimConnectDefinitionAccess; + FDefinition: IFSXSimConnectDefinition; FDataHandlers: TInterfaceList; protected property DataHandlers: TInterfaceList read FDataHandlers; public - constructor Create(ADefinition: IFSXSimConnectDefinitionAccess); + constructor Create(ADefinition: IFSXSimConnectDefinition); destructor Destroy; override; function Attach(ADataHandler: IFSXSimConnectDataHandler): Integer; @@ -101,7 +101,7 @@ type procedure HandleData(AData: Pointer); - property Definition: IFSXSimConnectDefinitionAccess read FDefinition; + property Definition: IFSXSimConnectDefinition read FDefinition; end; @@ -145,11 +145,11 @@ type procedure TrySimConnect(const ALibraryName: string); overload; procedure RegisterDefinitions; - procedure RegisterDefinition(ADefinitionID: Cardinal; ADefinition: IFSXSimConnectDefinitionAccess); + procedure RegisterDefinition(ADefinitionID: Cardinal; ADefinition: IFSXSimConnectDefinition); procedure UpdateDefinition(ADefinitionID: Cardinal); procedure UnregisterDefinition(ADefinitionID: Cardinal); - function SameDefinition(ADefinition1, ADefinition2: IFSXSimConnectDefinitionAccess): Boolean; + function SameDefinition(ADefinition1, ADefinition2: IFSXSimConnectDefinition): Boolean; procedure UpdateProfileMenu; @@ -187,7 +187,7 @@ type TFSXSimConnectVariableList = TObjectList; - TFSXSimConnectDefinition = class(TInterfacedObject, IFSXSimConnectDefinition, IFSXSimConnectDefinitionAccess) + TFSXSimConnectDefinition = class(TInterfacedObject, IFSXSimConnectDefinition) private FSimConnect: IFSXSimConnect; FVariables: TFSXSimConnectVariableList; @@ -198,7 +198,6 @@ type { IFSXSimConnectDefinition } procedure AddVariable(AVariableName, AUnitsName: string; ADataType: SIMCONNECT_DATAType; AEpsilon: Single = 0); - { IFSXSimConnectDefinitionAccess } function GetVariableCount: Integer; function GetVariable(AIndex: Integer): IFSXSimConnectVariable; public @@ -520,6 +519,7 @@ var simObjectData: PSimConnectRecvSimObjectData; eventData: PSimConnectRecvEvent; definitionRef: TFSXSimConnectDefinitionRef; + simObjectDataByType: PSimConnectRecvSimObjectDataByType; begin Log.Verbose('Handling messages'); @@ -540,6 +540,18 @@ begin end; end; + SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE: + begin + simObjectDataByType := PSimConnectRecvSimObjectDataByType(data); + Log.Verbose(Format('Received Sim Object Data By Type message (definition = %d)', [simObjectDataByType^.dwDefineID])); + + if Definitions.ContainsKey(simObjectDataByType^.dwDefineID) then + begin + definitionRef := Definitions[simObjectDataByType^.dwDefineID]; + definitionRef.HandleData(@simObjectDataByType^.dwData); + end; + end; + SIMCONNECT_RECV_ID_EVENT: begin eventData := PSimConnectRecvEvent(data); @@ -610,7 +622,7 @@ begin end; -procedure TFSXSimConnectClient.RegisterDefinition(ADefinitionID: Cardinal; ADefinition: IFSXSimConnectDefinitionAccess); +procedure TFSXSimConnectClient.RegisterDefinition(ADefinitionID: Cardinal; ADefinition: IFSXSimConnectDefinition); var variableIndex: Integer; variable: IFSXSimConnectVariable; @@ -660,7 +672,7 @@ begin end; -function TFSXSimConnectClient.SameDefinition(ADefinition1, ADefinition2: IFSXSimConnectDefinitionAccess): Boolean; +function TFSXSimConnectClient.SameDefinition(ADefinition1, ADefinition2: IFSXSimConnectDefinition): Boolean; var variableIndex: Integer; variable1: IFSXSimConnectVariable; @@ -767,13 +779,13 @@ var addDefinition: TAddDefinitionValue; definitionID: Cardinal; definitionRef: TFSXSimConnectDefinitionRef; - definitionAccess: IFSXSimConnectDefinitionAccess; + definitionAccess: IFSXSimConnectDefinition; hasDefinition: Boolean; refCount: Integer; begin addDefinition := Msg.MsgData; - definitionAccess := (addDefinition.Definition as IFSXSimConnectDefinitionAccess); + definitionAccess := (addDefinition.Definition as IFSXSimConnectDefinition); hasDefinition := False; Log.Verbose('Received request to add a definition'); @@ -889,7 +901,7 @@ end; { TFSXSimConnectDefinitionRef } -constructor TFSXSimConnectDefinitionRef.Create(ADefinition: IFSXSimConnectDefinitionAccess); +constructor TFSXSimConnectDefinitionRef.Create(ADefinition: IFSXSimConnectDefinition); begin inherited Create; diff --git a/G940LEDControl/Units/FSXSimConnectIntf.pas b/G940LEDControl/Units/FSXSimConnectIntf.pas index ad094c6..51be233 100644 --- a/G940LEDControl/Units/FSXSimConnectIntf.pas +++ b/G940LEDControl/Units/FSXSimConnectIntf.pas @@ -39,12 +39,6 @@ type end; - IFSXSimConnectDefinition = interface - ['{F1EAB3B1-0A3D-4B06-A75F-823E15C313B8}'] - procedure AddVariable(AVariableName, AUnitsName: string; ADataType: SIMCONNECT_DATAType; AEpsilon: Single = 0); - end; - - IFSXSimConnectVariable = interface ['{A41AD003-77C0-4E34-91E3-B0BAADD08FCE}'] function GetVariableName: string; @@ -54,8 +48,10 @@ type end; - IFSXSimConnectDefinitionAccess = interface - ['{2592534C-0344-4442-8A5F-1AB34B96E1B5}'] + IFSXSimConnectDefinition = interface + ['{F1EAB3B1-0A3D-4B06-A75F-823E15C313B8}'] + procedure AddVariable(AVariableName, AUnitsName: string; ADataType: SIMCONNECT_DATAType; AEpsilon: Single = 0); + function GetVariableCount: Integer; function GetVariable(AIndex: Integer): IFSXSimConnectVariable; end; diff --git a/G940LEDControl/Units/LEDFunctionRegistry.pas b/G940LEDControl/Units/LEDFunctionRegistry.pas index a4605f7..0b7942b 100644 --- a/G940LEDControl/Units/LEDFunctionRegistry.pas +++ b/G940LEDControl/Units/LEDFunctionRegistry.pas @@ -13,24 +13,16 @@ type TLEDFunctionRegistry = class(TObject) private FProviders: TLEDFunctionProviderList; - protected - class function Instance: TLEDFunctionRegistry; - - procedure DoRegister(AProvider: ILEDFunctionProvider); - procedure DoUnregister(AProvider: ILEDFunctionProvider); - function DoFind(const AUID: string): ILEDFunctionProvider; - - function GetProviders: TLEDFunctionProviderList; public constructor Create; destructor Destroy; override; - class procedure Register(AProvider: ILEDFunctionProvider); - class procedure Unregister(AProvider: ILEDFunctionProvider); + procedure Register(AProvider: ILEDFunctionProvider); + procedure Unregister(AProvider: ILEDFunctionProvider); - class function Find(const AUID: string): ILEDFunctionProvider; + function Find(const AUID: string): ILEDFunctionProvider; - class function Providers: TLEDFunctionProviderList; + function Providers: TLEDFunctionProviderList; end; @@ -64,44 +56,7 @@ uses SysUtils; -var - RegistryInstance: TLEDFunctionRegistry; - - { TLEDFunctionRegistry } -class procedure TLEDFunctionRegistry.Register(AProvider: ILEDFunctionProvider); -begin - Instance.DoRegister(AProvider); -end; - - -class procedure TLEDFunctionRegistry.Unregister(AProvider: ILEDFunctionProvider); -begin - Instance.DoUnregister(AProvider); -end; - - -class function TLEDFunctionRegistry.Find(const AUID: string): ILEDFunctionProvider; -begin - Result := Instance.DoFind(AUID); -end; - - -class function TLEDFunctionRegistry.Providers: TLEDFunctionProviderList; -begin - Result := Instance.GetProviders; -end; - - -class function TLEDFunctionRegistry.Instance: TLEDFunctionRegistry; -begin - if not Assigned(RegistryInstance) then - RegistryInstance := TLEDFunctionRegistry.Create; - - Result := RegistryInstance; -end; - - constructor TLEDFunctionRegistry.Create; begin inherited Create; @@ -118,25 +73,25 @@ begin end; -procedure TLEDFunctionRegistry.DoRegister(AProvider: ILEDFunctionProvider); +procedure TLEDFunctionRegistry.Register(AProvider: ILEDFunctionProvider); begin FProviders.Add(AProvider); end; -procedure TLEDFunctionRegistry.DoUnregister(AProvider: ILEDFunctionProvider); +procedure TLEDFunctionRegistry.Unregister(AProvider: ILEDFunctionProvider); begin FProviders.Remove(AProvider); end; -function TLEDFunctionRegistry.DoFind(const AUID: string): ILEDFunctionProvider; +function TLEDFunctionRegistry.Find(const AUID: string): ILEDFunctionProvider; begin Result := FProviders.Find(AUID); end; -function TLEDFunctionRegistry.GetProviders: TLEDFunctionProviderList; +function TLEDFunctionRegistry.Providers: TLEDFunctionProviderList; begin Result := FProviders; end; @@ -208,9 +163,4 @@ begin Result := ((inherited GetCurrent) as ILEDFunctionProvider); end; - -initialization -finalization - FreeAndNil(RegistryInstance); - end. diff --git a/G940LEDControl/Units/LEDStateConsumer.pas b/G940LEDControl/Units/LEDStateConsumer.pas index 3f44ec4..f1d4d7a 100644 --- a/G940LEDControl/Units/LEDStateConsumer.pas +++ b/G940LEDControl/Units/LEDStateConsumer.pas @@ -11,6 +11,7 @@ uses LEDColorIntf, LEDFunctionIntf, + LEDFunctionRegistry, Profile; @@ -28,6 +29,7 @@ type FButtonColors: TInterfaceList; FHasTickTimer: Boolean; FLog: IX2Log; + FFunctionRegistry: TLEDFunctionRegistry; protected function Initialize: Boolean; override; procedure Cleanup; override; @@ -45,11 +47,12 @@ type procedure Update; virtual; abstract; property Log: IX2Log read FLog; + property FunctionRegistry: TLEDFunctionRegistry read FFunctionRegistry; protected procedure TMLoadProfile(var Msg: TOmniMessage); message TM_LOADPROFILE; procedure TMTick(var Msg: TOmniMessage); message TM_TICK; public - constructor Create(ALog: IX2Log); + constructor Create(ALog: IX2Log; AFunctionRegistry: TLEDFunctionRegistry); end; @@ -59,7 +62,6 @@ uses System.SysUtils, Winapi.Windows, - LEDFunctionRegistry, LEDStateIntf; @@ -82,11 +84,12 @@ type { TLEDStateConsumer } -constructor TLEDStateConsumer.Create(ALog: IX2Log); +constructor TLEDStateConsumer.Create(ALog: IX2Log; AFunctionRegistry: TLEDFunctionRegistry); begin inherited Create; FLog := ALog; + FFunctionRegistry := AFunctionRegistry; end; @@ -118,7 +121,7 @@ var begin Result := nil; - provider := TLEDFunctionRegistry.Find(AProfileButton.ProviderUID); + provider := FunctionRegistry.Find(AProfileButton.ProviderUID); if Assigned(provider) then begin ledFunction := provider.Find(AProfileButton.FunctionUID); diff --git a/G940LEDControl/Units/LuaLEDFunctionProvider.pas b/G940LEDControl/Units/LuaLEDFunctionProvider.pas new file mode 100644 index 0000000..9b43d1d --- /dev/null +++ b/G940LEDControl/Units/LuaLEDFunctionProvider.pas @@ -0,0 +1,752 @@ +unit LuaLEDFunctionProvider; + +interface +uses + System.Generics.Collections, + System.SysUtils, + System.Types, + + OtlTask, + OtlTaskControl, + X2Log.Intf, + + LEDFunction, + LEDFunctionIntf, + LEDStateIntf, + Lua; + +type + ELuaScriptError = class(Exception); + + ELuaScriptLoadError = class(ELuaScriptError) + private + FFilename: string; + public + constructor Create(const AMessage, AFilename: string); + + property Filename: string read FFilename; + end; + + TCustomLuaLEDFunctionWorker = class; + + + TCustomLuaLEDFunction = class(TCustomMultiStateLEDFunction) + private + FCategoryName: string; + FDisplayName: string; + FUID: string; + FScriptStates: ILuaTable; + FSetup: ILuaFunction; + protected + procedure RegisterStates; override; + + function GetDefaultCategoryName: string; virtual; + + { ILEDFunction } + function GetCategoryName: string; override; + function GetDisplayName: string; override; + function GetUID: string; override; + + property ScriptStates: ILuaTable read FScriptStates; + property Setup: ILuaFunction read FSetup; + public + constructor Create(AProvider: ILEDFunctionProvider; AInfo: ILuaTable; ASetup: ILuaFunction); + end; + + + TCustomLuaLEDFunctionProvider = class(TCustomLEDFunctionProvider) + private + FInterpreter: TLua; + FScriptFolders: TStringDynArray; + FWorkers: TDictionary; + FScriptLog: TObject; + protected + function CreateLuaLEDFunction(AInfo: ILuaTable; ASetup: ILuaFunction): TCustomLuaLEDFunction; virtual; abstract; + + procedure CheckParameters(const AFunctionName: string; AParameters: ILuaReadParameters; AExpectedTypes: array of TLuaVariableType); + procedure AppendVariable(ABuilder: TStringBuilder; AVariable: ILuaVariable); + procedure AppendTable(ABuilder: TStringBuilder; ATable: ILuaTable); + + procedure DoLog(AContext: ILuaContext; ALevel: TX2LogLevel); + procedure DoLogMessage(AContext: ILuaContext; ALevel: TX2LogLevel; const AMessage: string); + + procedure ScriptRegisterFunction(Context: ILuaContext); + procedure ScriptSetState(Context: ILuaContext); + procedure ScriptOnTimer(Context: ILuaContext); + procedure ScriptWindowVisible(Context: ILuaContext); + + function WindowVisible(const AClassName, AWindowTitle, AParentClassName, AParentWindowTitle: string): Boolean; + + procedure InitInterpreter; virtual; + procedure RegisterFunctions; override; + + procedure RegisterWorker(AWorker: TCustomLuaLEDFunctionWorker); + procedure UnregisterWorker(AWorker: TCustomLuaLEDFunctionWorker); + function FindWorker(const AUID: string): TCustomLuaLEDFunctionWorker; + + property Interpreter: TLua read FInterpreter; + property ScriptFolders: TStringDynArray read FScriptFolders; + property Workers: TDictionary read FWorkers; + public + constructor Create(const AScriptFolders: TStringDynArray); + destructor Destroy; override; + end; + + + TCustomLuaLEDFunctionWorker = class(TCustomLEDMultiStateFunctionWorker) + private + FProvider: TCustomLuaLEDFunctionProvider; + FUID: string; + FTasks: TList; + + procedure SetProvider(const Value: TCustomLuaLEDFunctionProvider); + protected + procedure AddTask(ATask: IOmniTaskControl); + + property Provider: TCustomLuaLEDFunctionProvider read FProvider write SetProvider; + property Tasks: TList read FTasks; + public + constructor Create(const AProviderUID, AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string = ''); override; + destructor Destroy; override; + + property UID: string read FUID; + end; + + +implementation +uses + System.Classes, + System.IOUtils, + System.Generics.Defaults, + System.Math, + System.StrUtils, + Winapi.Windows, + + Lua.API, + X2Log.Global, + + LEDColorIntf, + LEDState; + + +type + TLuaLogProc = reference to procedure(AContext: ILuaContext; ALevel: TX2LogLevel); + + TLuaLog = class(TPersistent) + private + FOnLog: TLuaLogProc; + protected + property OnLog: TLuaLogProc read FOnLog; + public + constructor Create(AOnLog: TLuaLogProc); + published + procedure Verbose(Context: ILuaContext); + procedure Info(Context: ILuaContext); + procedure Warning(Context: ILuaContext); + procedure Error(Context: ILuaContext); + end; + + + TLuaTimerTask = class(TOmniWorker) + private + FOnTimer: TProc; + protected + property OnTimer: TProc read FOnTimer; + public + constructor Create(AOnTimer: TProc); + + procedure Run; + end; + + +const + LuaLEDColors: array[TLEDColor] of string = + ( + 'Off', 'Green', 'Amber', 'Red', + 'FlashingGreenFast', 'FlashingGreenNormal', + 'FlashingAmberFast', 'FlashingAmberNormal', + 'FlashingRedFast', 'FlashingRedNormal' + ); + + +function GetLEDColor(const AValue: string; ADefault: TLEDColor = lcOff): TLEDColor; +var + color: TLEDColor; + +begin + for color := Low(TLEDColor) to High(TLEDColor) do + if SameText(AValue, LuaLEDColors[color]) then + exit(color); + + Result := ADefault; +end; + + + +{ TCustomLuaLEDFunctionProvider } +constructor TCustomLuaLEDFunctionProvider.Create(const AScriptFolders: TStringDynArray); +begin + FWorkers := TDictionary.Create; + FInterpreter := TLua.Create; + FScriptFolders := AScriptFolders; + FScriptLog := TLuaLog.Create(DoLog); + + InitInterpreter; + + inherited Create; +end; + + +destructor TCustomLuaLEDFunctionProvider.Destroy; +begin + inherited Destroy; + + FreeAndNil(FInterpreter); + FreeAndNil(FScriptLog); + FreeAndNil(FWorkers); +end; + + +procedure TCustomLuaLEDFunctionProvider.InitInterpreter; +var + requirePath: TStringBuilder; + scriptFolder: string; + table: ILuaTable; + color: TLEDColor; + +begin + requirePath := TStringBuilder.Create; + try + for scriptFolder in ScriptFolders do + begin + if requirePath.Length > 0 then + requirePath.Append(';'); + + requirePath.Append(IncludeTrailingPathDelimiter(scriptFolder)).Append('?;') + .Append(IncludeTrailingPathDelimiter(scriptFolder)).Append('?.lua'); + end; + + Interpreter.SetRequirePath(requirePath.ToString); + Interpreter.GetRequirePath; + finally + FreeAndNil(requirePath); + end; + + Interpreter.RegisterFunction('RegisterFunction', ScriptRegisterFunction); + Interpreter.RegisterFunction('SetState', ScriptSetState); + Interpreter.RegisterFunction('OnTimer', ScriptOnTimer); + Interpreter.RegisterFunction('WindowVisible', ScriptWindowVisible); + + Interpreter.RegisterFunctions(FScriptLog, 'Log'); + + table := TLuaTable.Create; + for color := Low(TLEDColor) to High(TLEDColor) do + table.SetValue(LuaLEDColors[color], LuaLEDColors[color]); + + Interpreter.SetGlobalVariable('LEDColor', table); +end; + + +procedure TCustomLuaLEDFunctionProvider.CheckParameters(const AFunctionName: string; AParameters: ILuaReadParameters; AExpectedTypes: array of TLuaVariableType); +const + VariableTypeName: array[TLuaVariableType] of string = + ( + 'None', 'Boolean', 'Integer', + 'Number', 'UserData', 'String', + 'Table', 'Function' + ); + +var + parameterIndex: Integer; + +begin + if AParameters.Count < Length(AExpectedTypes) then + raise ELuaScriptError.CreateFmt('%s: expected at least %d parameter%s', [AFunctionName, Length(AExpectedTypes), IfThen(Length(AExpectedTypes) <> 1, 's', '')]); + + for parameterIndex := 0 to High(AExpectedTypes) do + if AParameters[parameterIndex].VariableType <> AExpectedTypes[parameterIndex] then + raise ELuaScriptError.CreateFmt('%s: expected %s for parameter %d, got %s', + [AFunctionName, VariableTypeName[AExpectedTypes[parameterIndex]], + Succ(parameterIndex), VariableTypeName[AParameters[parameterIndex].VariableType]]); +end; + + +procedure TCustomLuaLEDFunctionProvider.AppendVariable(ABuilder: TStringBuilder; AVariable: ILuaVariable); +begin + case AVariable.VariableType of + VariableBoolean: + if AVariable.AsBoolean then + ABuilder.Append('true') + else + ABuilder.Append('false'); + + VariableTable: + AppendTable(ABuilder, AVariable.AsTable); + else + ABuilder.Append(AVariable.AsString); + end; +end; + + +procedure TCustomLuaLEDFunctionProvider.AppendTable(ABuilder: TStringBuilder; ATable: ILuaTable); +var + firstItem: Boolean; + item: TLuaKeyValuePair; + +begin + ABuilder.Append('{ '); + firstItem := True; + + for item in ATable do + begin + if firstItem then + firstItem := False + else + ABuilder.Append(', '); + + AppendVariable(ABuilder, item.Key); + ABuilder.Append(' = '); + AppendVariable(ABuilder, item.Value); + end; + + ABuilder.Append(' }'); +end; + + +procedure TCustomLuaLEDFunctionProvider.DoLog(AContext: ILuaContext; ALevel: TX2LogLevel); +var + msg: TStringBuilder; + parameter: ILuaVariable; + +begin + msg := TStringBuilder.Create; + try + for parameter in AContext.Parameters do + begin + AppendVariable(msg, parameter); + msg.Append(' '); + end; + + DoLogMessage(AContext, ALevel, msg.ToString); + finally + FreeAndNil(msg); + end; +end; + + +procedure TCustomLuaLEDFunctionProvider.DoLogMessage(AContext: ILuaContext; ALevel: TX2LogLevel; const AMessage: string); +var + debug: lua_Debug; + fileName: string; + +begin + fileName := 'Lua'; + + if Interpreter.HasState and (lua_getstack(Interpreter.State, 1, debug) <> 0) then + begin + lua_getinfo(Interpreter.State, 'Sl', debug); + fileName := fileName + ' - ' + string(debug.source) + end; + + TX2GlobalLog.Log(ALevel, AMessage, filename); +end; + + +procedure TCustomLuaLEDFunctionProvider.ScriptRegisterFunction(Context: ILuaContext); +var + info: ILuaTable; + setup: ILuaFunction; + +begin + CheckParameters('RegisterFunction', Context.Parameters, [VariableTable, VariableFunction]); + + info := Context.Parameters[0].AsTable; + setup := Context.Parameters[1].AsFunction; + + if not info.HasValue('uid') then + raise ELuaScriptError.Create('RegisterFunction: "uid" value is required'); + + DoLogMessage(Context, TX2LogLevel.Info, Format('Registering function: %s', [info.GetValue('uid').AsString])); + RegisterFunction(CreateLuaLEDFunction(info, setup)); +end; + + +procedure TCustomLuaLEDFunctionProvider.ScriptSetState(Context: ILuaContext); +var + workerID: string; + worker: TCustomLuaLEDFunctionWorker; + stateUID: string; + +begin + CheckParameters('SetState', Context.Parameters, [VariableString, VariableString]); + + workerID := Context.Parameters[0].AsString; + stateUID := Context.Parameters[1].AsString; + + worker := FindWorker(workerID); + if not Assigned(worker) then + raise ELuaScriptError.Create('SetState: invalid context'); + + DoLogMessage(Context, TX2LogLevel.Info, Format('Setting state for %s to: %s', [worker.GetFunctionUID, stateUID])); + worker.SetCurrentState(stateUID); +end; + + +procedure TCustomLuaLEDFunctionProvider.ScriptOnTimer(Context: ILuaContext); +var + workerID: string; + interval: Integer; + timerCallback: ILuaFunction; + worker: TCustomLuaLEDFunctionWorker; + +begin + CheckParameters('OnTimer', Context.Parameters, [VariableString, VariableNumber, VariableFunction]); + + workerID := Context.Parameters[0].AsString; + interval := Context.Parameters[1].AsInteger; + timerCallback := Context.Parameters[2].AsFunction; + + worker := FindWorker(workerID); + if not Assigned(worker) then + raise ELuaScriptError.Create('OnTimer: invalid context'); + + DoLogMessage(Context, TX2LogLevel.Info, Format('Adding timer for %s, interval: %d', [worker.GetFunctionUID, interval])); + worker.AddTask(CreateTask(TLuaTimerTask.Create( + procedure + begin + try + timerCallback.Call([workerID]); + except + on E:Exception do + TX2GlobalLog.Category('Lua').Exception(E); + end; + end)) + .SetTimer(1, MSecsPerSec, @TLuaTimerTask.Run) + .Run); +end; + + +procedure TCustomLuaLEDFunctionProvider.ScriptWindowVisible(Context: ILuaContext); +var + className: string; + windowTitle: string; + parentClassName: string; + parentWindowTitle: string; + +begin + if Context.Parameters.Count = 0 then + raise ELuaScriptError.Create('WindowVisible: expected at least 1 parameter'); + + className := ''; + windowTitle := ''; + parentClassName := ''; + parentWindowTitle := ''; + + if Context.Parameters.Count >= 1 then className := Context.Parameters[0].AsString; + if Context.Parameters.Count >= 2 then windowTitle := Context.Parameters[1].AsString; + if Context.Parameters.Count >= 3 then parentClassName := Context.Parameters[2].AsString; + if Context.Parameters.Count >= 4 then parentWindowTitle := Context.Parameters[3].AsString; + + Context.Result.Push(WindowVisible(className, windowTitle, parentClassName, parentWindowTitle)); +end; + + +function TCustomLuaLEDFunctionProvider.WindowVisible(const AClassName, AWindowTitle, AParentClassName, AParentWindowTitle: string): Boolean; + + function GetNilPChar(const AValue: string): PChar; + begin + if Length(AValue) > 0 then + Result := PChar(AValue) + else + Result := nil; + end; + +var + parentWindow: THandle; + childWindow: THandle; + window: THandle; + +begin + Result := False; + + if (Length(AParentClassName) > 0) or (Length(AParentWindowTitle) > 0) then + begin + parentWindow := FindWindow(GetNilPChar(AParentClassName), GetNilPChar(AParentWindowTitle)); + if parentWindow <> 0 then + begin + childWindow := FindWindowEx(parentWindow, 0, GetNilPChar(AClassName), GetNilPChar(AWindowTitle)); + Result := (childWindow <> 0) and IsWindowVisible(childWindow); + end; + end else + begin + window := FindWindow(GetNilPChar(AClassName), GetNilPChar(AWindowTitle)); + Result := (window <> 0) and IsWindowVisible(window); + end; +end; + + + +procedure TCustomLuaLEDFunctionProvider.RegisterFunctions; +var + scriptFolder: string; + scriptFile: string; + +begin + for scriptFolder in ScriptFolders do + if ForceDirectories(scriptFolder) then + for scriptFile in TDirectory.GetFiles(ScriptFolder, '*.lua') do + try + Interpreter.LoadFromFile(scriptFile); + except + on E:Exception do + Exception.RaiseOuterException(ELuaScriptLoadError.Create(E.Message, scriptFile)); + end; +end; + + +procedure TCustomLuaLEDFunctionProvider.RegisterWorker(AWorker: TCustomLuaLEDFunctionWorker); +begin + Workers.Add(AWorker.UID, AWorker); +end; + + +procedure TCustomLuaLEDFunctionProvider.UnregisterWorker(AWorker: TCustomLuaLEDFunctionWorker); +begin + Workers.Remove(AWorker.UID); +end; + + +function TCustomLuaLEDFunctionProvider.FindWorker(const AUID: string): TCustomLuaLEDFunctionWorker; +begin + if not Workers.TryGetValue(AUID, Result) then + Result := nil; +end; + + + +{ TCustomLuaLEDFunction } +constructor TCustomLuaLEDFunction.Create(AProvider: ILEDFunctionProvider; AInfo: ILuaTable; ASetup: ILuaFunction); +begin + FCategoryName := GetDefaultCategoryName; + FDisplayName := 'Unknown function'; + FSetup := ASetup; + + FUID := AInfo.GetValue('uid').AsString; + + if AInfo.HasValue('category') then + FCategoryName := AInfo.GetValue('category').AsString; + + if AInfo.HasValue('displayName') then + FDisplayName := AInfo.GetValue('displayName').AsString; + + FScriptStates := nil; + if AInfo.HasValue('states') then + FScriptStates := AInfo.GetValue('states').AsTable; + + // #ToDo1 -oMvR: 28-5-2017: application filter? + + inherited Create(AProvider.GetUID); +end; + + +function TCustomLuaLEDFunction.GetCategoryName: string; +begin + Result := FCategoryName; +end; + + +function TCustomLuaLEDFunction.GetDisplayName: string; +begin + Result := FDisplayName; +end; + + +function TCustomLuaLEDFunction.GetUID: string; +begin + Result := FUID; +end; + + +procedure TCustomLuaLEDFunction.RegisterStates; +type + TOrderedLEDState = record + Order: Integer; + State: ILEDState; + end; + +var + states: TList; + scriptState: TLuaKeyValuePair; + displayName: string; + defaultColor: TLEDColor; + info: ILuaTable; + state: TOrderedLEDState; + +begin + if not Assigned(ScriptStates) then + exit; + + states := TList.Create; + try + for scriptState in ScriptStates do + begin + state.Order := 0; + + displayName := scriptState.Key.AsString; + defaultColor := lcOff; + + if scriptState.Value.VariableType = VariableTable then + begin + info := scriptState.Value.AsTable; + if info.HasValue('displayName') then + displayName := info.GetValue('displayName').AsString; + + if info.HasValue('default') then + defaultColor := GetLEDColor(info.GetValue('default').AsString); + + if info.HasValue('order') then + state.Order := info.GetValue('order').AsInteger; + end; + + state.State := TLEDState.Create(scriptState.Key.AsString, displayName, defaultColor); + states.Add(state) + end; + + states.Sort(TDelegatedComparer.Create( + function(const Left, Right: TOrderedLEDState): Integer + begin + Result := CompareValue(Left.Order, Right.Order); + if Result = 0 then + Result := CompareText(Left.State.GetDisplayName, Right.State.GetDisplayName); + end)); + + for state in states do + RegisterState(state.State); + finally + FreeAndNil(states); + end; +end; + + +function TCustomLuaLEDFunction.GetDefaultCategoryName: string; +begin + Result := 'Other'; +end; + + +{ TCustomLuaLEDFunctionWorker } +constructor TCustomLuaLEDFunctionWorker.Create(const AProviderUID, AFunctionUID: string; AStates: ILEDMultiStateFunction; ASettings: ILEDFunctionWorkerSettings; const APreviousState: string); +var + workerGUID: TGUID; + +begin + if CreateGUID(workerGUID) <> 0 then + RaiseLastOSError; + + FUID := GUIDToString(workerGUID); + + inherited Create(AProviderUID, AFunctionUID, AStates, ASettings, APreviousState); +end; + +destructor TCustomLuaLEDFunctionWorker.Destroy; +var + task: IOmniTaskControl; + +begin + if Assigned(Tasks) then + begin + for task in Tasks do + begin + task.Stop; + task.WaitFor(INFINITE); + end; + + FreeAndNil(FTasks); + end; + + SetProvider(nil); + + inherited Destroy; +end; + + +procedure TCustomLuaLEDFunctionWorker.AddTask(ATask: IOmniTaskControl); +begin + if not Assigned(Tasks) then + FTasks := TList.Create; + + Tasks.Add(ATask); +end; + + +procedure TCustomLuaLEDFunctionWorker.SetProvider(const Value: TCustomLuaLEDFunctionProvider); +begin + if Value <> FProvider then + begin + if Assigned(FProvider) then + FProvider.UnregisterWorker(Self); + + FProvider := Value; + + if Assigned(FProvider) then + FProvider.RegisterWorker(Self); + end; +end; + + +{ TLuaLog } +constructor TLuaLog.Create(AOnLog: TLuaLogProc); +begin + inherited Create; + + FOnLog := AOnLog; +end; + + +procedure TLuaLog.Verbose(Context: ILuaContext); +begin + OnLog(Context, TX2LogLevel.Verbose); +end; + + +procedure TLuaLog.Info(Context: ILuaContext); +begin + OnLog(Context, TX2LogLevel.Info); +end; + + +procedure TLuaLog.Warning(Context: ILuaContext); +begin + OnLog(Context, TX2LogLevel.Warning); +end; + + +procedure TLuaLog.Error(Context: ILuaContext); +begin + OnLog(Context, TX2LogLevel.Error); +end; + + +{ TLuaTimerTask } +constructor TLuaTimerTask.Create(AOnTimer: TProc); +begin + inherited Create; + + FOnTimer := AOnTimer; +end; + + +procedure TLuaTimerTask.Run; +begin + FOnTimer(); +end; + +{ ELuaScriptLoadError } +constructor ELuaScriptLoadError.Create(const AMessage, AFilename: string); +begin + inherited Create(AMessage); + + FFilename := AFilename; +end; + +end. diff --git a/G940LEDControl/Units/StaticLEDFunction.pas b/G940LEDControl/Units/StaticLEDFunction.pas index c3cb7df..076b4e2 100644 --- a/G940LEDControl/Units/StaticLEDFunction.pas +++ b/G940LEDControl/Units/StaticLEDFunction.pas @@ -114,8 +114,4 @@ begin Result := FState; end; - -initialization - TLEDFunctionRegistry.Register(TStaticLEDFunctionProvider.Create); - end. diff --git a/G940LEDControl/XSD/SimBaseDocument.settings.xml b/G940LEDControl/XSD/SimBaseDocument.settings.xml index 10e213f..20c2026 100644 --- a/G940LEDControl/XSD/SimBaseDocument.settings.xml +++ b/G940LEDControl/XSD/SimBaseDocument.settings.xml @@ -1,2 +1,2 @@ -SingleF:\Development\G940\G940LEDControl\Units\SimBaseDocumentXMLBinding.pas +Single..\Units\SimBaseDocumentXMLBinding.pas diff --git a/G940LEDControl/XSD/SimBaseDocument.xsd b/G940LEDControl/XSD/SimBaseDocument.xsd index f7996de..66360dd 100644 --- a/G940LEDControl/XSD/SimBaseDocument.xsd +++ b/G940LEDControl/XSD/SimBaseDocument.xsd @@ -1,6 +1,4 @@ - - diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..30ace6a --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..58a32bd --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# G940 LED Control + +Main website: https://g940.x2software.net/ + +Source code: https://git.x2software.net/delphi/g940ledcontrol
+Mirror: https://github.com/PsychoMark/G940LEDControl + +Documentation: http://g940ledcontrol.readthedocs.io/en/latest/ \ No newline at end of file diff --git a/Setup/G940LEDControl.iss b/Setup/G940LEDControl.iss index c872426..29c686a 100644 --- a/Setup/G940LEDControl.iss +++ b/Setup/G940LEDControl.iss @@ -33,6 +33,10 @@ Source: "..\G940LEDControl\Bin\LogiJoystickDLL.dll"; DestDir: "{app}"; Flags: ig Source: "..\G940LEDControl\Bin\FSX-SimConnect.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "..\G940LEDControl\Bin\FSXSP2-SimConnect.dll"; DestDir: "{app}"; Flags: ignoreversion Source: "..\G940LEDControl\Bin\FSX-SE-SimConnect.dll"; DestDir: "{app}"; Flags: ignoreversion +Source: "..\G940LEDControl\Scripts\*.lua"; DestDir: "{app}\Scripts"; Flags: ignoreversion recursesubdirs + +[Dirs] +Name: "{userappdata}\G940LEDControl\Scripts\FSX" [Icons] Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExeName}"