1
0
mirror of https://github.com/medigor/example-native-api-rs.git synced 2025-06-25 00:47:09 +02:00

добавил пример внешнего события

This commit is contained in:
medigor
2025-05-18 22:23:21 +03:00
parent bab1edf67a
commit ebd1b6ff9a
9 changed files with 196 additions and 15 deletions

View File

@ -25,7 +25,7 @@
* [addin1.rs](src/addin1.rs) - реализация компоненты с помощью низкоуровнего интерфейса, причем весь код безопасный. * [addin1.rs](src/addin1.rs) - реализация компоненты с помощью низкоуровнего интерфейса, причем весь код безопасный.
* [addin2.rs](src/addin2.rs) - упрощенный вариант, используется другой трейт. * [addin2.rs](src/addin2.rs) - упрощенный вариант, используется другой трейт.
### [conf1c](conf1c) - конфигурация 1С (выгрузка из конфигуратора 8.3.22), минимальный тестовый код. ### [conf1c](conf1c) - конфигурация 1С (выгрузка из конфигуратора 8.3.23), минимальный тестовый код.
* [DataProcessors/Обработка1/Forms/Форма/Ext/Form/Module.bsl](conf1c/DataProcessors/Обработка1/Forms/Форма/Ext/Form/Module.bsl) - тесты для ручного запуска. * [DataProcessors/Обработка1/Forms/Форма/Ext/Form/Module.bsl](conf1c/DataProcessors/Обработка1/Forms/Форма/Ext/Form/Module.bsl) - тесты для ручного запуска.
## Разработка ## Разработка

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<Configuration uuid="72b21170-d6cc-48ee-8426-d69353f61fd5"> <Configuration uuid="72b21170-d6cc-48ee-8426-d69353f61fd5">
<InternalInfo> <InternalInfo>
<xr:ContainedObject> <xr:ContainedObject>
@ -36,7 +36,7 @@
<Synonym/> <Synonym/>
<Comment/> <Comment/>
<NamePrefix/> <NamePrefix/>
<ConfigurationExtensionCompatibilityMode>Version8_3_22</ConfigurationExtensionCompatibilityMode> <ConfigurationExtensionCompatibilityMode>Version8_3_23</ConfigurationExtensionCompatibilityMode>
<DefaultRunMode>ManagedApplication</DefaultRunMode> <DefaultRunMode>ManagedApplication</DefaultRunMode>
<UsePurposes> <UsePurposes>
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value> <v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
@ -193,6 +193,14 @@
<app:functionality>Videoconferences</app:functionality> <app:functionality>Videoconferences</app:functionality>
<app:use>false</app:use> <app:use>false</app:use>
</app:functionality> </app:functionality>
<app:functionality>
<app:functionality>NFC</app:functionality>
<app:use>false</app:use>
</app:functionality>
<app:functionality>
<app:functionality>DocumentScanning</app:functionality>
<app:use>false</app:use>
</app:functionality>
</UsedMobileApplicationFunctionalities> </UsedMobileApplicationFunctionalities>
<StandaloneConfigurationRestrictionRoles/> <StandaloneConfigurationRestrictionRoles/>
<MobileApplicationURLs/> <MobileApplicationURLs/>
@ -210,6 +218,7 @@
<ModalityUseMode>DontUse</ModalityUseMode> <ModalityUseMode>DontUse</ModalityUseMode>
<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode> <SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
<InterfaceCompatibilityMode>Taxi</InterfaceCompatibilityMode> <InterfaceCompatibilityMode>Taxi</InterfaceCompatibilityMode>
<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
<CompatibilityMode>Version8_3_22</CompatibilityMode> <CompatibilityMode>Version8_3_22</CompatibilityMode>
<DefaultConstantsForm/> <DefaultConstantsForm/>
</Properties> </Properties>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<DataProcessor uuid="33179d0b-730e-44f5-b20c-1af11f7f1f60"> <DataProcessor uuid="33179d0b-730e-44f5-b20c-1af11f7f1f60">
<InternalInfo> <InternalInfo>
<xr:GeneratedType name="DataProcessorObject.Обработка1" category="Object"> <xr:GeneratedType name="DataProcessorObject.Обработка1" category="Object">

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<Form uuid="24033a67-5ef1-4265-9a88-eb7f279ce1cb"> <Form uuid="24033a67-5ef1-4265-9a88-eb7f279ce1cb">
<Properties> <Properties>
<Name>Форма</Name> <Name>Форма</Name>

View File

@ -1,7 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcssch="http://v8.1c.ru/8.1/data-composition-system/schema" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcssch="http://v8.1c.ru/8.1/data-composition-system/schema" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<AutoSaveDataInSettings>Use</AutoSaveDataInSettings> <AutoSaveDataInSettings>Use</AutoSaveDataInSettings>
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/> <AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/>
<Events>
<Event name="ExternalEvent">ВнешнееСобытие</Event>
</Events>
<ChildItems> <ChildItems>
<InputField name="ИмяФайла" id="19"> <InputField name="ИмяФайла" id="19">
<DataPath>ИмяФайла</DataPath> <DataPath>ИмяФайла</DataPath>
@ -31,6 +34,11 @@
<CommandName>Form.Command.Тест4</CommandName> <CommandName>Form.Command.Тест4</CommandName>
<ExtendedTooltip name="Тест4РасширеннаяПодсказка" id="27"/> <ExtendedTooltip name="Тест4РасширеннаяПодсказка" id="27"/>
</Button> </Button>
<Button name="ТестВнешнееСобытие" id="28">
<Type>UsualButton</Type>
<CommandName>Form.Command.ТестВнешнееСобытие</CommandName>
<ExtendedTooltip name="ТестВнешнееСобытиеРасширеннаяПодсказка" id="29"/>
</Button>
</ChildItems> </ChildItems>
<Attributes> <Attributes>
<Attribute name="Объект" id="1"> <Attribute name="Объект" id="1">
@ -119,5 +127,20 @@
</ToolTip> </ToolTip>
<Action>Тест4</Action> <Action>Тест4</Action>
</Command> </Command>
<Command name="ТестВнешнееСобытие" id="5">
<Title>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Тест внешнее событие</v8:content>
</v8:item>
</Title>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Тест внешнее событие</v8:content>
</v8:item>
</ToolTip>
<Action>ТестВнешнееСобытие</Action>
</Command>
</Commands> </Commands>
</Form> </Form>

View File

@ -1,4 +1,14 @@
 
&НаКлиенте
Перем КомпонентаДляВнешнегоСобытия;
&НаКлиенте
Перем СчетчикВнешнихСобытий;
&НаКлиенте
Перем ДатаНачалаСобытий;
&НаКлиенте &НаКлиенте
Процедура Тест1(Команда) Процедура Тест1(Команда)
Тест1НаСервере(ИмяФайла); Тест1НаСервере(ИмяФайла);
@ -149,3 +159,37 @@
Сообщить(СтрШаблон("Длительность: %1 мс", Конец - Начало)); Сообщить(СтрШаблон("Длительность: %1 мс", Конец - Начало));
КонецПроцедуры КонецПроцедуры
&НаКлиенте
Асинх Процедура ТестВнешнееСобытие(Команда)
Если Не Ждать ПодключитьВнешнююКомпонентуАсинх(ИмяФайла, "Test", ТипВнешнейКомпоненты.Native, ТипПодключенияВнешнейКомпоненты.НеИзолированно) Тогда
ВызватьИсключение "Не удалось подключить";
КонецЕсли;
КомпонентаДляВнешнегоСобытия = Новый ("AddIn.Test.Class2");
СчетчикВнешнихСобытий = 0;
ДатаНачалаСобытий = ТекущаяУниверсальнаяДатаВМиллисекундах();
Элементы.ТестВнешнееСобытие.Доступность = Ложь;
Ждать КомпонентаДляВнешнегоСобытия.StartTimerAsync(1000);
КонецПроцедуры
&НаКлиенте
Асинх Процедура ВнешнееСобытие(Источник, Событие, Данные)
Если Источник = "Class2" И Событие = "Timer" Тогда
СчетчикВнешнихСобытий = СчетчикВнешнихСобытий + 1;
Сообщить(СтрШаблон("%1 мс, внешнее событие № %2, данные: %3", ТекущаяУниверсальнаяДатаВМиллисекундах() - ДатаНачалаСобытий, СчетчикВнешнихСобытий, Данные));
Если СчетчикВнешнихСобытий = 5 Тогда
Ждать КомпонентаДляВнешнегоСобытия.StopTimerAsync();
КонецЕсли;
ИначеЕсли Источник = "Class2" И Событие = "TimerShutdown" Тогда
КомпонентаДляВнешнегоСобытия = Неопределено;
Сообщить(СтрШаблон("%1 мс, TimerShutdown", ТекущаяУниверсальнаяДатаВМиллисекундах() - ДатаНачалаСобытий));
Элементы.ТестВнешнееСобытие.Доступность = Истина;
КонецЕсли;
КонецПроцедуры

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<HomePageWorkArea xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <HomePageWorkArea xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<WorkingAreaTemplate>TwoColumnsEqualWidth</WorkingAreaTemplate> <WorkingAreaTemplate>TwoColumnsEqualWidth</WorkingAreaTemplate>
<LeftColumn> <LeftColumn>
<Item> <Item>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.15"> <MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.16">
<Language uuid="e3ac9659-5250-4530-9ca6-3f4f4ef6413a"> <Language uuid="e3ac9659-5250-4530-9ca6-3f4f4ef6413a">
<Properties> <Properties>
<Name>Русский</Name> <Name>Русский</Name>

View File

@ -1,12 +1,42 @@
use addin1c::{name, AddinResult, CStr1C, MethodInfo, Methods, PropInfo, SimpleAddin, Variant}; use std::{
error::Error,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
use addin1c::{
cstr1c, name, AddinResult, CStr1C, CString1C, Connection, MethodInfo, Methods, PropInfo,
SimpleAddin, Variant,
};
pub struct Addin2 { pub struct Addin2 {
last_error: Option<Box<dyn Error>>,
prop1: i32, prop1: i32,
connection: Option<&'static Connection>,
timer_enabled: Arc<AtomicBool>,
thread_handle: Option<JoinHandle<()>>,
} }
impl Addin2 { impl Addin2 {
pub fn new() -> Addin2 { pub fn new() -> Addin2 {
Addin2 { prop1: 0 } Addin2 {
last_error: None,
prop1: 0,
connection: None,
timer_enabled: Arc::new(AtomicBool::new(false)),
thread_handle: None,
}
}
fn last_error(&mut self, value: &mut Variant) -> AddinResult {
match &self.last_error {
Some(err) => value.set_str1c(err.to_string()).map_err(|e| e.into()),
None => value.set_str1c("").map_err(|e| e.into()),
}
} }
fn method1(&mut self, param: &mut Variant, ret_value: &mut Variant) -> AddinResult { fn method1(&mut self, param: &mut Variant, ret_value: &mut Variant) -> AddinResult {
@ -29,6 +59,48 @@ impl Addin2 {
Ok(()) Ok(())
} }
fn start_timer(&mut self, duration: &mut Variant, _ret_value: &mut Variant) -> AddinResult {
let Some(connection) = self.connection else {
return Err("Нет интерфейса".into());
};
let duration = duration.get_i32()?;
let duration = duration.try_into()?;
if let Some(handle) = self.thread_handle.as_ref() {
if !handle.is_finished() {
return Err("Timer is started".into());
}
}
self.timer_enabled.store(true, Ordering::Relaxed);
let enabled = self.timer_enabled.clone();
connection.set_event_buffer_depth(100);
let handle = thread::spawn(move || {
let mut counter = 0;
loop {
thread::sleep(Duration::from_millis(duration));
if enabled.load(Ordering::Relaxed) {
counter += 1;
connection.external_event(
cstr1c!("Class2"),
cstr1c!("Timer"),
CString1C::new(&format!("{counter}")),
);
} else {
break;
}
}
connection.external_event(cstr1c!("Class2"), cstr1c!("TimerShutdown"), cstr1c!(""));
});
self.thread_handle = Some(handle);
Ok(())
}
fn stop_timer(&mut self, _ret_value: &mut Variant) -> AddinResult {
self.timer_enabled.store(false, Ordering::Relaxed);
Ok(())
}
fn set_prop1(&mut self, value: &Variant) -> AddinResult { fn set_prop1(&mut self, value: &Variant) -> AddinResult {
self.prop1 = value.get_i32()?; self.prop1 = value.get_i32()?;
Ok(()) Ok(())
@ -40,11 +112,29 @@ impl Addin2 {
} }
} }
impl Drop for Addin2 {
fn drop(&mut self) {
self.timer_enabled.store(false, Ordering::Relaxed);
if let Some(handle) = self.thread_handle.take() {
let _ = handle.join();
}
}
}
impl SimpleAddin for Addin2 { impl SimpleAddin for Addin2 {
fn name() -> &'static CStr1C { fn name() -> &'static CStr1C {
name!("Class2") name!("Class2")
} }
fn init(&mut self, interface: &'static Connection) -> bool {
self.connection = Some(interface);
true
}
fn save_error(&mut self, err: Option<Box<dyn Error>>) {
self.last_error = err;
}
fn methods() -> &'static [MethodInfo<Self>] { fn methods() -> &'static [MethodInfo<Self>] {
&[ &[
MethodInfo { MethodInfo {
@ -55,14 +145,29 @@ impl SimpleAddin for Addin2 {
name: name!("Method2"), name: name!("Method2"),
method: Methods::Method2(Self::method2), method: Methods::Method2(Self::method2),
}, },
MethodInfo {
name: name!("StartTimer"),
method: Methods::Method1(Self::start_timer),
},
MethodInfo {
name: name!("StopTimer"),
method: Methods::Method0(Self::stop_timer),
},
] ]
} }
fn properties() -> &'static [PropInfo<Self>] { fn properties() -> &'static [PropInfo<Self>] {
&[PropInfo { &[
name: name!("Prop1"), PropInfo {
getter: Some(Self::get_prop1), name: name!("Prop1"),
setter: Some(Self::set_prop1), getter: Some(Self::get_prop1),
}] setter: Some(Self::set_prop1),
},
PropInfo {
name: name!("LastError"),
getter: Some(Self::last_error),
setter: None,
},
]
} }
} }