text
stringlengths
14
6.51M
unit MFichas.Model.Pagamento.Interfaces; interface uses MFichas.Model.Entidade.VENDAPAGAMENTOS, MFichas.Model.Entidade.VENDA, ORMBR.Container.ObjectSet.Interfaces; type iModelPagamento = interface; iModelPagamentoMetodos = interface; iModelPagamentoMetodosProcessar = interface; iModelPagamentoMetodosEstornar = interface; iModelPagamento = interface ['{ACB3004A-9D8D-4F6F-B6D0-50CC3674C34D}'] function Dinheiro : iModelPagamentoMetodos; function CartaoDeDebito : iModelPagamentoMetodos; function CartaoDeCredito: iModelPagamentoMetodos; function DAO : iContainerObjectSet<TVENDAPAGAMENTOS>; function EntidadeDeVenda: TVENDA; end; iModelPagamentoMetodos = interface ['{9A230FEB-97DC-4F2E-B9B6-3DAFCDE5EE98}'] function Processar: iModelPagamentoMetodosProcessar; function Estornar : iModelPagamentoMetodosEstornar; function &End : iModelPagamento; end; iModelPagamentoMetodosProcessar = interface ['{97CF1411-282E-4D57-BD30-26BC69C64064}'] function SetValor(AValue: Currency): iModelPagamentoMetodosProcessar; function &End : iModelPagamentoMetodos; end; iModelPagamentoMetodosEstornar = interface ['{97CF1411-282E-4D57-BD30-26BC69C64064}'] function SetValor(AValue: Currency): iModelPagamentoMetodosEstornar; function &End : iModelPagamentoMetodos; end; { FPagamento .Metodos .Dinheiro .Executar SetValor() .&End .&End .CartaoDeCredito .Executar .SetValor() .&End .&End .CartaoDeDebito .Executar .SetValor() .&End .&End } implementation end.
unit QueryCard_Form; (*----------------------------------------------------------------------------- Unit Name: enNewQueryCard Author: Инишев Дмитрий & Михаил Морозов Purpose: Новая карточка запросов History: $Id: QueryCard_Form.pas,v 1.34 2013/08/07 10:24:16 morozov Exp $ $Log: QueryCard_Form.pas,v $ Revision 1.34 2013/08/07 10:24:16 morozov {RequestLink:429695931} Revision 1.33 2013/05/31 06:07:28 lulin - портируем под XE4. Revision 1.32 2013/04/24 09:35:57 lulin - портируем. Revision 1.31 2012/05/25 12:13:41 lulin - не падаем на ReadOnly теге. Revision 1.30 2012/04/13 18:24:43 lulin {RequestLink:237994598} Revision 1.29 2012/03/21 11:18:03 lulin {RequestLink:349114873} Revision 1.28 2011/11/16 17:35:57 lulin {RequestLink:232098711} Revision 1.27 2011/10/31 15:33:28 lulin {RequestLink:294589844} Revision 1.26 2011/10/14 16:37:03 lulin {RequestLink:265397719}. Revision 1.25 2011/08/31 19:32:41 lulin {RequestLink:280006084}. Revision 1.24 2011/07/20 11:17:09 lulin {RequestLink:228688745}. Revision 1.23 2011/06/28 19:19:56 lulin {RequestLink:254944102}. Revision 1.22 2011/06/23 15:31:36 lulin {RequestLink:254944102}. Revision 1.21 2011/05/19 12:19:08 lulin {RequestLink:266409354}. Revision 1.20 2011/04/19 16:49:41 lulin {RequestLink:264373571}. Revision 1.19 2011/03/30 13:46:43 lulin {RequestLink:259180243}. Revision 1.18 2011/03/18 13:01:54 lulin {RequestLink:228691765}. Revision 1.17 2011/03/11 18:05:11 lulin {RequestLink:228688510}. - впихиваем БП в специально подготовленный контейнер. Revision 1.16 2011/03/05 16:44:58 lulin {RequestLink:228688510}. Revision 1.15 2011/03/05 14:41:39 lulin {RequestLink:228688510}. Revision 1.14 2011/02/24 13:57:44 lulin {RequestLink:182157315}. Revision 1.13 2011/02/14 15:18:25 lulin {RequestLink:231670346}. Revision 1.12 2010/12/23 14:20:56 lulin {RequestLink:248195558}. Revision 1.11 2010/12/23 12:53:22 lulin {RequestLink:248194836}. Revision 1.10 2010/12/22 18:26:05 lulin {RequestLink:242845936}. Revision 1.9 2010/12/09 13:30:35 lulin - все новшества показываем и в неконсольной оболочке тоже. Revision 1.8 2010/11/01 17:20:15 lulin {RequestLink:237994238}. - передаём ссылку на "модель". - делаем, чтобы собирались другие проекты. Revision 1.7 2010/11/01 13:20:52 lulin {RequestLink:237994238}. Revision 1.6 2010/09/21 12:57:59 oman - fix: {RequestLink:234366672} Revision 1.5 2010/09/09 11:18:32 lulin {RequestLink:197496539}. Revision 1.4 2010/09/08 17:45:09 lulin {RequestLink:197496539}. Revision 1.208 2010/07/02 18:20:10 lulin {RequestLink:207389954}. - переносим на модель КЗ. Revision 1.207 2010/04/26 17:19:37 lulin {RequestLink:159352361}. - вычищаем код старого стиля. Revision 1.206 2009/12/09 13:11:31 lulin {RequestLink:124453871}. Revision 1.205 2009/12/07 19:09:44 lulin - удалил ненужный модуль. Revision 1.204 2009/11/30 18:32:56 lulin - убрал излишний контейнер данных. Revision 1.203 2009/11/30 08:57:14 oman - fix: {RequestLink:172365361} Revision 1.202 2009/11/26 11:44:11 oman - new: Search {RequestLink:121157219} Revision 1.201 2009/11/18 13:06:09 lulin - используем базовые параметры операции. Revision 1.200 2009/11/12 14:32:37 lulin - убираем возможность менять список параметров. Revision 1.199 2009/11/11 18:48:07 lulin - убираем генерацию идентификаторов операций. Revision 1.198 2009/11/10 12:29:23 lulin - перестаём выливать идентификаторы внутренних операций. Revision 1.197 2009/11/06 13:06:29 lulin - избавился от ручной передачи параметров через поле Data. Revision 1.196 2009/11/05 14:59:51 lulin - закончены разборки с параметрами внутренних операций. Revision 1.195 2009/11/05 11:41:44 oman - new: {RequestLink:121160631} Revision 1.194 2009/11/02 09:25:00 oman - new: {RequestLink:136253296} Revision 1.193 2009/10/29 14:35:47 lulin - вторая волна компании по борьбе со старыми внутренними операциями. Revision 1.192 2009/10/26 09:23:55 oman - fix: {RequestLink:121160631} Revision 1.191 2009/10/16 15:14:41 lulin {RequestLink:159360578}. №52. Revision 1.190 2009/10/16 13:26:54 oman - new: Переносим на модель {RequestLink:164596503} Revision 1.189 2009/10/13 15:50:18 lulin {RequestLink:166855739}. Revision 1.188 2009/10/02 16:48:58 lulin - избавляемся от неоправданного вызова операции с параметрами. Revision 1.187 2009/09/24 10:12:50 lulin - вычищаем ненужный параметр операции. Revision 1.186 2009/09/22 14:49:23 lulin - переносим модуль поиска на модель. Revision 1.185 2009/09/22 07:32:06 oman - fix: Заготовки - {RequestLink:96482372} Revision 1.184 2009/09/22 07:22:59 oman - fix: Заготовки - {RequestLink:96482372} Revision 1.183 2009/09/11 16:46:20 lulin - удаляем ненужные операции. - правим модель за Ромой. - исправляем кривизну использования форм. Revision 1.182 2009/09/03 18:49:13 lulin - реструктуризируем поиски и удаляем ненужное. Revision 1.181 2009/09/03 13:26:17 lulin - делаем прецеденты более изолированными друг от друга. Revision 1.180 2009/08/26 08:15:25 lulin - декорируем имена операций, чтобы можно было искать. - bug fix: не собирались мониторинги. Revision 1.179 2009/08/11 17:03:50 lulin - прикручиваем обработку ссылок к Сравнению редакций. Revision 1.178 2009/08/10 13:09:33 lulin - готовимся к выводу имени документа в заголовок окна. Revision 1.177 2009/07/31 17:30:07 lulin - убираем мусор. Revision 1.176 2009/07/23 13:42:29 lulin - переносим процессор операций туда куда надо. Revision 1.175 2009/07/11 09:24:48 lulin - избавляемся от лишнего дёрганья счётчиков ссылок. Revision 1.174 2009/06/02 13:47:58 lulin [$148574526]. Revision 1.173 2009/06/01 11:16:30 lulin [$148572848]. Revision 1.172 2009/05/29 17:18:17 lulin [$142610853]. Revision 1.171 2009/04/16 05:30:05 oman Не собирались мониторинги Revision 1.170 2009/04/09 14:12:49 lulin [$140837386]. №15. Revision 1.169 2009/04/08 11:18:47 oman - new: В JumpTo подаем не состояние мыши а желаемое поведение - [$140287160] Revision 1.168 2009/04/02 15:28:15 lulin - [$98828322]. Позволяем по-честному запрашивать иконки для любых параграфов. Revision 1.167 2009/03/05 10:12:03 lulin - <K>: 138547857. Не вовремя очищали чудо "менеджер". Revision 1.166 2009/03/04 13:32:47 lulin - <K>: 137470629. Генерируем идентификаторы типов с модели и убираем их из общей помойки. Revision 1.165 2009/02/10 19:04:03 lulin - <K>: 133891247. Вычищаем морально устаревший модуль. Revision 1.164 2009/01/27 12:36:22 lulin - <K>: 136251752. Revision 1.163 2009/01/27 07:57:49 lulin - <K>: 135607658. Revision 1.162 2009/01/12 15:58:38 lulin - <K>: 133138664. № 22. Revision 1.161 2009/01/11 10:44:22 lulin - <K>: 134709278. Пытаемся выживать в сложных условиях. Revision 1.160 2008/12/29 16:41:04 lulin - <K>: 134316705. Revision 1.159 2008/12/29 10:55:01 oman - fix: Не собиралось (К-122675365) Revision 1.158 2008/12/29 10:48:40 lulin - bug fix: не собиралось. Revision 1.157 2008/12/24 19:49:51 lulin - <K>: 121153186. Revision 1.156 2008/12/23 06:37:12 oman - new: В кэше превью различаем из какой зоны было оно вызвано (К-122675365) Revision 1.155 2008/12/19 15:43:09 migel - fix: F1Prime останется в памяти после выхода из него (К: 131793204). Revision 1.154 2008/12/05 07:35:34 lulin - чистка кода и перегенерация. Revision 1.153 2008/09/30 16:12:46 lulin - <K>: 120718188. Revision 1.152 2008/09/25 15:43:11 lulin - <K>: 118394577. Revision 1.151 2008/07/22 12:48:54 mmorozov - new: ссылки на разделы справки для Инфарм (K<96484593>); Revision 1.150 2008/06/18 13:27:53 oman - fix: Пытаемся сбрасывать успешно найденную опечатку (cq29204) Revision 1.149 2008/06/18 11:20:12 oman - fix: Пользуем более правильное исключение (cq29204) Revision 1.148 2008/06/18 10:43:09 oman - new: Переделка исправления опечаток (cq29204) Revision 1.147 2008/06/07 17:31:38 lulin - рисуем таблицу тегов на модели. Revision 1.146 2008/05/26 11:46:23 mmorozov - format code; Revision 1.145 2008/05/16 15:58:12 lulin - cleanup. Revision 1.144 2008/05/16 15:21:13 lulin - рисуем на модели. Revision 1.143 2008/05/16 10:57:21 lulin - переименованы константы. Revision 1.142 2008/05/08 04:58:23 mmorozov - rename: QueryInfo -> SearchInfo; Revision 1.141 2008/05/05 12:05:49 mmorozov - new: показ документа в извлечениях доступен только после поиска в котором выбрано значение реквизита "Раздел\Тема" (CQ: OIT5-9285, 9656). Revision 1.140 2008/04/29 07:05:53 mmorozov - new: регистрация события - "Проверить условия подключения к услуге Правовая поддержка онлайн"; Revision 1.139 2008/04/14 13:43:54 lulin - <K>: 89096854. Revision 1.138 2008/03/12 09:36:03 oman - new: Заготовки для ПЛП - пытаемся открываться Revision 1.137 2008/03/12 08:28:37 oman - new: Заготовки для ПЛП - типы форм Revision 1.136 2008/03/12 07:51:30 oman - new: Заготовки для поиска лекарственного препарата (ПЛП) Revision 1.135 2008/03/06 18:50:25 lulin - <K> 86477264. Revision 1.134 2008/03/06 11:52:39 lulin - <K>: 86476694. Revision 1.133 2008/01/10 07:23:08 oman Переход на новый адаптер Revision 1.130.2.4 2007/12/26 12:43:13 mmorozov - MERGE WITH HEAD; Revision 1.130.2.3 2007/12/11 09:32:08 mmorozov - MERGE WITH HEAD; Revision 1.130.2.2 2007/11/23 10:41:26 oman cleanup Revision 1.130.2.1 2007/11/22 13:20:25 oman Перепиливаем на новый адаптер Revision 1.131 2007/12/10 12:51:07 mmorozov - new: реализуем шаблон publisher\subscriber при редактировании настроек, замены настроек (переключения конфигураций), настройке панелей инструментов (в рамках CQ: OIT5-27823); Revision 1.132 2007/12/25 11:32:04 mmorozov - new: подписка на обновление данных приложения (CQ: OIT5-27823); Revision 1.131 2007/12/10 12:51:07 mmorozov - new: реализуем шаблон publisher\subscriber при редактировании настроек, замены настроек (переключения конфигураций), настройке панелей инструментов (в рамках CQ: OIT5-27823); Revision 1.130 2007/11/01 13:21:15 oman - fix: Создаваемую ленту могли трактовать как модифицируемую - fix: При удалении ленты очищали создаваемую (cq27269) Revision 1.129 2007/10/05 13:08:28 lulin - bug fix: падали при нажатии Ввода вне ссылки (CQ OIT5-26930). Revision 1.128 2007/09/13 10:51:34 lulin - bug fix: не собирался Немезис с новой веткой. Revision 1.127 2007/09/10 14:19:59 lulin - bug fix: падала КЗ ППР при переключении баз (CQ OIT5-26548). Revision 1.126 2007/08/28 10:33:48 oman - new: Ссылка на правила работы В ППР (cq26503) Revision 1.125 2007/08/14 14:29:57 lulin - оптимизируем перемещение блоков памяти. Revision 1.124 2007/08/09 11:26:05 oman - fix: Убираем удвоенный && из сообщения (cq26313) Revision 1.123 2007/07/18 15:07:04 lulin - выпрямляем зависимости. Схема документа, теперь не зависит от Эвереста. Revision 1.122 2007/06/20 12:06:10 lulin - вычищены ненужные методы (<K>-20219395). Revision 1.121 2007/06/15 12:44:18 lulin - переименован метод - для читабельности (<K>-19759257). Revision 1.120 2007/06/14 07:40:18 lulin - теперь в метод проверки того заполнено поле или нет подается базовый контрол (<K>-18677854). Revision 1.119 2007/06/13 17:18:22 lulin - метод переехал в общую библиотеку (<K>-18677805). Revision 1.118 2007/06/13 15:13:57 lulin - метод переименован в соответствии с тем, что он делает (<K>-18219651). Revision 1.117 2007/06/13 14:00:17 lulin - вычищена ненужная локальная переменная (<K>-18219525). Revision 1.116 2007/06/13 13:51:04 lulin - метод переехал с интерфейса в глобальную область (<K>-18219517). Revision 1.115 2007/06/08 12:15:18 lulin - избавился от прямого обращения к тегу с контролом модели (<K>-17335138). Revision 1.114 2007/06/05 12:26:05 oman - fix: Перед посылкой на проверку подключения очищаем текст запроса (cq25518) Revision 1.113 2007/06/04 10:43:15 oman - fix: Для правовой поддержки неправильно ставили начальный фокус (cq25528) Revision 1.112 2007/05/30 14:18:45 lulin - с менеджера поиска вычищено ненужное свойство (<K>-14516583). Revision 1.111 2007/05/30 12:41:33 oman - fix: Контанта для гиперссылки типа "внешняя операция" берем из общего мести Revision 1.110 2007/05/23 15:46:39 lulin - переименовываем метод прятанья выпавшего контрола в соответствии с тем, что он делает (<K>-13239271). Revision 1.109 2007/05/22 11:11:52 lulin - изменен тип имени контрола. Revision 1.108 2007/05/22 10:57:46 oman - fix: Даже если в результате очистки КЗ не меняется требуем перерисовку, иначе не восстанавливались SHapesPainted Revision 1.107 2007/05/17 14:23:15 oman - new: При посылке проверки статуса подключения правовой поддержки выводим всплывающее окно (cq25300) Revision 1.106 2007/05/16 14:36:08 oman Читаем историю контекста из единого места Revision 1.105 2007/04/19 06:26:22 oman - fix: При посылке запроса на условия подключения не портим признак измененности. Revision 1.104 2007/04/16 09:20:34 oman - new: Атрибут EMail для Правовой поддержки пришем/читаем в историю (cq24416) Revision 1.103 2007/04/13 13:05:34 oman - fix: Используем именованную константу Revision 1.102 2007/04/13 08:08:07 oman - new: Новый реквизит - e-mail и новый гиперлинк - проверка подключения к ПП (cq24926, 24416) Revision 1.101 2007/04/05 13:42:51 lulin - избавляемся от лишних преобразований строк. Revision 1.100 2007/04/05 07:58:27 lulin - избавляемся от лишних преобразований строк при записи в настройки. Revision 1.99 2007/03/28 14:51:20 oman - new: Избавляемся от ContextParams в КЗ (cq24456) Revision 1.98 2007/03/27 11:59:33 oman Переводим тэг атрибутов на константную строку Revision 1.97 2007/03/20 08:52:05 lulin - не теряем кодировку при присваивании заголовков форм. Revision 1.96 2007/03/16 16:57:16 lulin - избавляемся от излишнего копирования и преобразования строк. Revision 1.95 2007/03/14 15:36:48 lulin - cleanup. Revision 1.94 2007/02/28 14:17:48 lulin - переводим на строки с кодировкой. Revision 1.93 2007/02/14 17:49:30 lulin - избавляемся от использования стандартных строк. Revision 1.92 2007/02/14 16:51:00 lulin - избавляемся от использования стандартных строк. Revision 1.91 2007/02/13 14:33:31 lulin - cleanup. Revision 1.90 2007/02/12 18:55:51 lulin - переводим на строки с кодировкой. Revision 1.89 2007/02/12 18:45:01 lulin - переводим на строки с кодировкой. Revision 1.88 2007/02/09 16:05:53 mmorozov - не собирались мониторинги; Revision 1.87 2007/02/07 17:48:54 lulin - избавляемся от копирования строк при чтении из настроек. Revision 1.86 2007/02/05 09:07:26 lulin - bug fix: не собирались мониторинги. Revision 1.85 2007/02/02 13:23:58 lulin - упрощаем преобразование строк. Revision 1.84 2007/02/02 08:39:24 lulin - переводим на строки с кодировкой. Revision 1.83 2007/01/26 15:53:10 lulin - убрана ненужная внутренняя операция. Revision 1.82 2007/01/20 15:30:33 lulin - разделяем параметры операции для выполнения и для тестирования. Revision 1.81 2007/01/19 09:47:25 lulin - выделяем интерфейс параметров для создания формы. Revision 1.80 2007/01/17 14:03:08 lulin - вычищены последние нефиксированные параметры в тестах операций. Revision 1.79 2006/12/29 12:15:50 lulin - удален ненужный модуль. Revision 1.78 2006/12/13 14:19:33 oman - fix: Приводим поведение PhoneReq по аналогии с DateReq (cq23855) Revision 1.77 2006/12/13 09:30:35 mmorozov - new: возможность указывать фиксированный размер для зон стыковки панелей инструментов формы, в рамках работы над CQ: OIT5-13323; Revision 1.76 2006/12/10 14:24:09 lulin - не грузим список картинок каждый раз, когда открываем КЗ. Revision 1.75 2006/12/05 14:16:03 lulin - контрол переехал в визуальную библиотеку. Revision 1.74 2006/11/24 16:04:55 lulin - удален ненужный компонент. Revision 1.73 2006/11/20 12:12:10 oman Merge from B_NEMESIS_6_4 Revision 1.72 2006/11/17 13:13:54 mmorozov MERGE WITH B_NEMESIS_6_4 ( bugfix: при измении тематик (добавлении/удалении/изменении), в процессе работы с ПРАЙМ, автоматом не вызывался метод выливки папок (CQ: OIT5-23672)); Revision 1.71 2006/11/15 08:12:37 oman Merge from B_NEMESIS_6_4 Revision 1.70 2006/11/10 16:00:02 oman Merge from B_NEMESIS_6_4 Revision 1.69 2006/11/03 09:46:20 oman Merge with B_NEMESIS_6_4_0 Revision 1.68.2.3.2.4 2006/11/20 12:09:05 oman - fix: При переключении конфигураций, если были инвалидные поля в КЗ, то не переносились даже валидные значения (cq23691) Revision 1.68.2.3.2.3 2006/11/17 13:02:58 mmorozov - bugfix: при измении тематик (добавлении/удалении/изменении), в процессе работы с ПРАЙМ, автоматом не вызывался метод выливки папок (CQ: OIT5-23672); Revision 1.68.2.3.2.2 2006/11/15 08:04:11 oman - fix: Чистим ссылку на DocumentContainer (cq23630) Revision 1.68.2.3.2.1 2006/11/10 10:05:34 oman - fix: Пропадала операция "Вставить" (cq23581) Revision 1.68.2.3 2006/10/24 09:46:54 oman - fix: В КЗ при возврате по истории оставались мусорные поля - теперь пустые поля удаляются _перед_ сохранением (cq23114) Revision 1.68.2.2 2006/10/24 09:43:54 oman no message Revision 1.68.2.1 2006/10/23 05:51:19 lulin - переход по ссылке переделан с обработки мыши на специально для этого выделенное событие. - вычищены ненужные операции. Revision 1.68 2006/10/06 10:09:41 lulin - убрано использование "скрытого" свойства. Revision 1.67 2006/10/04 09:49:51 oman - fix: Для КЗ ПП ФИО и телефон по умолчанию не кладем в Undo (cq22838) Revision 1.66 2006/10/04 08:56:00 oman - fix: Мусор после очистки КЗ (если были многострочные атрибуты) (cq22823) Revision 1.65 2006/09/29 08:33:24 lulin - для отладочных целей добавлена операция "Показывать спецсимволы". Revision 1.64 2006/09/21 10:21:51 oman - new beh: При открытии КЗ ПП если заполнены реквизиты ФИО/телефон - ставимся на текст запроса (cq22667) Revision 1.63 2006/09/19 12:29:15 oman - new: Вызов хелпа для предварительного ответа на консультацию (cq22633) Revision 1.62 2006/09/18 11:33:40 oman -new: для КЗ ПП сохраняем ФИО и телефон послу успешной посылки в настройки и восстанавливаем их при открытии (cq22612) Revision 1.61 2006/09/18 09:08:41 oman - fix: Корректная проверка правильности ввода - fix: Корректное ограничение на длину полей cleanup (ненужные операции/сообщения/проверки) Revision 1.60 2006/09/14 14:16:27 oman - new: Изменения в КЗ ПП (cq22535) Revision 1.59 2006/09/11 14:02:16 oman - new: Схлопывание подсказки в ППР (cq21474) - fix: Более корректная работа с гиперссылками в КЗ. Revision 1.58 2006/09/05 10:05:11 oman - fix: Не формировалось превью, при компиляции с выключенными Assert (cq22460) Revision 1.57 2006/07/31 15:04:22 mmorozov - new: измерения открытия основного меню (CQ: OIT500021555); Revision 1.56 2006/07/27 13:39:21 mmorozov - new: замеры открытия списка после поиска (CQ: OIT500021557); - rename: интерфейсы профайлеров, некторые методы, константы; Revision 1.55 2006/07/27 11:20:58 mmorozov - new: замеры времени открытия карточки запроса (CQ: OIT500021553); Revision 1.54 2006/07/20 18:28:07 lulin - убран лишний параметр. Revision 1.53 2006/07/20 17:35:07 lulin - убраны параметры по умолчанию. Revision 1.52 2006/06/19 07:19:10 oman - fix: AV при переключении на другую форму при выпавшем комбобоксе (cq21364) Revision 1.51 2006/06/16 10:44:38 oman - fix: После переключения баз для КЗ внутри сборки зачем-то убивался Query => AV. По словам Д. Инишева код левый и ненужный, посему вытерт (cq21353) Revision 1.50 2006/06/16 09:23:48 oman - fix: Отсутствовал признак посланности консультации для истории - не все учел... (cq21330) Revision 1.49 2006/06/16 07:45:41 oman - fix: В карточку выбора дат отдавался реквизит, который после переключения баз становился дохлым => имели AV (cq21336) Revision 1.48 2006/06/15 08:35:48 oman - fix: Отсутствовал признак посланности консультации для истории (cq21330) Revision 1.47 2006/06/08 14:41:49 dinishev Bug fix: сохранялись данные для откакти при заполнении КЗ значениями по умолчнанию или загруженными значениями Revision 1.46 2006/06/08 07:38:08 oman - fix: Замена ImageList на PngImgList - может перестанет ломаться картинка под W95 Revision 1.45 2006/05/30 15:21:35 dinishev Remove procedure nsMakeImageListWrapper Revision 1.44 2006/05/25 08:19:50 oman - fix: Тип сообщений (cq21081) Revision 1.43 2006/05/25 06:39:47 oman - fix: Убрана зависимость l3 от vt. Новая функция nsMakeImageListWrapper для получения правильной реализации Il3ImageList Revision 1.42 2006/05/24 15:48:51 dinishev Cleanup Revision 1.41 2006/05/23 07:29:57 mmorozov - change: переход от операции enSystemopWriteBackSettingsExecute к перекрытию DoWriteBackSettings для сохранения в настройки перед переключением конфигураций и открытием диалога настроек; Revision 1.40 2006/05/22 12:11:42 dinishev Bug fix: неодинаковое поведение пунктов выпадающего меню и главного меню Revision 1.39 2006/05/19 13:09:24 dinishev Cleanup Revision 1.38 2006/05/19 10:11:46 oman - fix: Реанимировал печать для новостной ленты (cq20984) Revision 1.37 2006/05/16 10:28:12 dinishev Bug fix: не компилировалось Revision 1.36 2006/05/05 10:55:24 dinishev _CleanUp Revision 1.35 2006/05/03 12:25:34 dinishev Более корректная обработка сообщений о недоступности сервера консультаций Revision 1.34 2006/04/28 12:29:13 dinishev Подправлено название страницы в Help'е Revision 1.33 2006/04/21 13:47:22 dinishev Вызов справки для новой КЗ Revision 1.32 2006/04/21 12:12:15 dinishev Bug fix: была возможность сохранить запрос в утилите заказа рассылки с пустым именем Revision 1.31 2006/04/19 13:59:34 oman - new beh: перекладываем StdStr в _StdRes Revision 1.30 2006/04/11 14:17:08 dinishev Bug fix: отъехала выдача сообщений об ошибках в новых КЗ и утилите заказа рассылки. Revision 1.29 2006/04/10 14:38:53 dinishev Bug fix: отъехала выдача сообщений о пустых полях в тулзе заказа рассылки Revision 1.28 2006/04/07 13:50:54 dinishev Поддержка свойства k2_tiCardType - типа КЗ Revision 1.27 2006/04/07 08:25:24 mmorozov - приведение к общему знаменателю Поиска с правовой поддержкой, Запроса на консультацию, Консультации; Revision 1.26 2006/04/05 15:57:12 dinishev no message Revision 1.25 2006/04/05 15:47:02 dinishev Bug fix: даже в случае ошибки выполнялся запрос Revision 1.24 2006/04/04 12:28:30 dinishev Проверка на повтороную передачу запроса Revision 1.23 2006/04/03 15:52:55 dinishev Новая КЗ Revision 1.22 2006/03/31 07:42:33 lulin - изменен тип параметров, подаваемый в Execte операции. Revision 1.21 2006/03/30 15:31:43 lulin - изменен тип параметров в _OnTest. Revision 1.20 2006/03/30 14:01:56 lulin - операция инициализации разделена на две - с параметрами и без - для того, чтобы в итоге избавится от первой. Revision 1.19 2006/03/28 15:08:47 dinishev Bug fix: Иногда не при возврате по истории приходила пустая КЗ интеллектуального поиска Revision 1.18 2006/03/22 11:12:24 dinishev Bug fix: не сохраненный открывался запрос из дерева Revision 1.17 2006/03/22 07:30:08 oman - new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr) Revision 1.16 2006/03/21 15:03:56 oman - new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr) Revision 1.15 2006/03/16 15:24:15 dinishev Bug fix: при повторном вызове новой КЗ появлялось пустое окно Revision 1.14 2006/03/15 15:04:11 dinishev Проверка запроса на пустое значение Revision 1.13 2006/03/10 13:44:23 dinishev Подключение новой КЗ Revision 1.12 2006/02/10 14:51:18 mmorozov - change: vcm_opVisible -> vcm_opEnabled; Revision 1.11 2006/02/10 11:16:00 dinishev Cleanup Revision 1.10 2005/12/28 18:20:13 dinishev Bug fix: после обновления при возврате по истории приходила некорректная КЗ Revision 1.9 2005/12/14 11:19:17 dinishev Cleanup: remove hint Revision 1.8 2005/12/12 17:15:54 dinishev Bug fix: считывалась не вся история ввода контекста Revision 1.7 2005/12/08 13:23:54 oman - new behavior: rename System_BeforeActiveConfigChange => System_WriteBackSettings - заточка перед рефакторингом настроек Revision 1.6 2005/12/06 06:57:34 dinishev Cleanup Revision 1.5 2005/12/02 22:50:26 lulin - запретил напрямую присваивать TextSource документ - присваивать можно только контейнер. Revision 1.4 2005/11/29 08:40:40 lulin - удалил старую КЗ. Revision 1.3 2005/11/23 10:18:51 lulin - обертка над нодой карточки вынесена в отдельный модуль. Revision 1.2 2005/11/22 17:01:19 lulin - класс-обертка над нодой для реализации документа выделен в отдельный модуль. Revision 1.1 2005/11/17 05:46:17 dinishev _Move to directory 'Search' Revision 1.61 2005/11/14 18:37:44 lulin - теперь при заборе в буфер обмена в него кладется контейнер документа, а не TextSource - должно починить ошибку CQ OIT5-17870. Revision 1.60 2005/11/10 15:52:49 dinishev Bug fix: подправлена реакция на большие кнопки Revision 1.59 2005/11/09 18:45:26 dinishev Подправлено обновление Revision 1.58 2005/11/08 15:11:15 mmorozov bugfix: избавляемся от неосвобожденных объектов; Revision 1.57 2005/11/08 13:17:38 mmorozov - форматирование кода; Revision 1.56 2005/11/04 16:49:45 dinishev Нажатия Enter приводит к открытию окна выбора или запуску поиска (в зависимости от реквизита) Revision 1.55 2005/10/20 12:59:23 lulin - bug fix: избавился от AV при вставке полей в КЗ. Revision 1.54 2005/10/18 17:18:55 dinishev Bug fix: полноразмерная картинка в КЗ с комментарием Revision 1.53 2005/10/14 13:33:10 dinishev Lock/Unlock для долгих операций Revision 1.52 2005/10/14 09:14:18 dinishev Убираем ссылку на View Revision 1.51 2005/10/13 17:25:08 dinishev Попытка отвязать модель от редактора и привязать её к DocumentContainer Revision 1.50 2005/10/12 16:43:22 dinishev Предварительные изменения для корректной обработки события обновления Revision 1.49 2005/10/12 14:04:05 dinishev Bug fix: проверка в пункте меню "Развернуть/свернуть" на возможность сворачивания панели Revision 1.48 2005/10/12 05:05:00 lulin - при создании контейнера сразу подаем ему документ. Revision 1.47 2005/10/11 17:07:55 dinishev Bug fix: AV при попытке сохранить редактируемый запрос в F1Prime Revision 1.46 2005/10/11 14:49:10 dinishev Новый процессор для исправления ошибки с вставкой лишних полей из буфера Revision 1.45 2005/10/11 08:40:24 lulin - cleanup. Revision 1.44 2005/10/11 07:56:07 dinishev Bug fix: на полях не имеющих логической операции при вызове контекстного меню возникало AV Revision 1.43 2005/10/10 17:09:56 dinishev Bug fix: неправильно обрабатывалось состояние пункта "Копировать" над полем с календарем. Revision 1.42 2005/10/10 11:43:22 lulin - cleanup: используем интерфейсы из правильной библиотеки. Revision 1.41 2005/10/06 17:48:25 dinishev Не копировалась история ввода во вторичные поля + не всегда срабатывало заполнение истрии Revision 1.40 2005/10/06 16:16:20 dinishev _CleanUp Revision 1.39 2005/10/05 17:36:16 dinishev Контекстные меню Revision 1.38 2005/10/03 16:58:23 dinishev Контекстные меню Revision 1.37 2005/09/27 15:05:49 dinishev Bug fix: отъехали кнопки копирования/вставки в редакторе Revision 1.36 2005/09/22 08:32:03 dinishev Bug fix: AV при возврате из режима предварительного просмотра и выхода из тулзы Revision 1.35 2005/09/16 15:03:14 dinishev Первое приближение обработки гиперссылок + автоматическое формирование значений + проверка E-mail Revision 1.34 2005/09/14 12:23:32 lulin - КЗ сделана "белой". Revision 1.33 2005/09/09 16:07:20 lulin - вернул заливку цветом. Revision 1.32 2005/09/09 14:27:48 lulin - временно убрана заливка серым КЗ и двойная буферизация. Revision 1.31 2005/09/07 09:08:29 dinishev Remove interface InevInputListner Revision 1.30 2005/09/02 14:51:54 dinishev Загрузка и сохранение КЗ (в частности запроса) из истории Revision 1.29 2005/09/02 09:44:00 dinishev Bug fix: не компилировалось Revision 1.28 2005/09/02 09:22:09 dinishev Загрузка/сохранения настроек панелей + сохранение истории ввода Revision 1.27 2005/09/01 14:48:45 dinishev no message *) interface {$Include nsDefine.inc } uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, OvcBase, l3InternalInterfaces, afwControl, l3ProgressComponent, l3InterfacedComponent, afwInterfaces, afwNavigation, k2Interfaces, evEditor, evCustomTextSource, evTunedEditor, evCustomEditor, evEditorWindow, evInternalInterfaces, evQueryCardInt, evMultiSelectEditorWindow, evEditorWithOperations, evEditorWindowTextSource, evQueryCardEditor, nevBase, nevTools, eeTextSource, eeTextSourceExport, vtPngImgList, lgTypes, vcmBase, vcmForm, vcmInterfaces, vcmEntityForm, vcmEntities, vcmComponent, vcmBaseEntities, vcmExternalInterfaces, nscTextSource, nsQueryInterfaces, nsQueryAttribute, nsManagers, evTextSource, afwControlPrim, afwBaseControl, nevControl, evCustomEditorWindowModelPart, SearchUnit, PrimQueryCard_Form, evCustomEditorWindowPrim, evCustomEditorModelPart, PrimQueryCardOptions_Form, evCustomEditorWindow ; type TenQueryCard = class(TvcmEntityFormRef) Entities : TvcmEntities; TextSource: TevTextSource; Editor: TevQueryCardEditor; procedure TextSourceDocumentChanged(aSender: TObject; const anOldDocument, aNewDocument: Ik2Tag); procedure TextSourceGetControlItemImg(aSender: TObject; const aControl: TnevControlInfo; out theImageInfo: TnevControlImageInfo); function EditorJumpTo(Sender : TObject; anEffects : TafwJumpToEffects; const aMoniker : IevMoniker): Boolean; procedure vcmEntityFormLoadState(const aState: IvcmBase; aStateType: TvcmStateType; var Loaded: Boolean); procedure vcmEntityFormSaveState(out aState: IvcmBase; aStateType: TvcmStateType; var Saved: Boolean); procedure vcmEntityFormChangedDataSource(aSender: TObject; const aOld, aNew: IvcmFormDataSource; const aFromHistory: Boolean); procedure EditorAfterFirstPaint(Sender: TObject); private { Private declarations } f_QueryCard : IevQueryCard; {-} f_Update : Boolean; {-} function IsQueryCardSupportFormSets: Boolean; {* - Поддерживает ли форма сборки. } function GetQueryType: TlgQueryType; {* - В зависимости от UserType возвращаем тип запроса. } procedure ReadDocument; {-} procedure HandleException(anException: EqaException); override; {-} procedure SaveConsultationCreditnails; override; {-} procedure LoadConsultationCreditnails; override; {-} function CalcUserNameSettings: TafwSettingID; {-} function CalcUserPhoneCodeSettings: TafwSettingID; {-} function CalcUserPhoneNumberSettings: TafwSettingID; {-} function CalcEMailSettings: TafwSettingID; {-} protected // protected methods procedure MakeSearchManager(const aQuery: IQuery); {-} procedure DoInit(aFormHistory : Boolean); override; {-} procedure OnDateQuery(const aValue: IqaDateReqDataHolder); {-} procedure OnNeedExecQuery(Sender: TObject); {-} procedure OnModifiedChanged(Sender: TObject); {-} procedure Cleanup; override; {-} procedure CleanDependencies; override; {$IfDef vcmUseSettings} protected procedure FinishDataUpdate; override; {* вызывает по окончании обновления } protected // IafwSettingsReplaceListener procedure SettingsReplaceStart; override; {* - перед заменой настроек. } {$EndIf vcmUseSettings} end; implementation uses Types, ActiveX, StrUtils, afwFacade, l3Tree, l3Nodes, l3Base, l3Memory, l3InterfacesMisc, l3Types, l3Interfaces, l3String, k2Tags, vtUtils, evdTypes, evEvdDataObject, evControlContainerEX, //evQueryCardModelEX, evControlParaConst, evQueryDocumentContainer, evParaTools, evControlParaTools, nevInternalInterfaces, nevGUIInterfaces, nevNavigation, DataAdapter, nsTypes, {$IFDEF Monitorings} nsPostingsLine, Printers, nsPostingsTreeSingle, {$ENDIF Monitorings} nsQuery, nsQueryUtils, nsDocumentPreview, nsHAFPainter, nsbQueryUtils, nsTreeStruct, nsAttributeTreeCacheNew, nsConst, nsSettings, nsFixedHAFMacroReplacer, vcmEntitiesCollectionItem, vcmOperationsCollectionItem, ConsultingUnit, DynamicTreeUnit, ExternalOperationUnit, StdRes, SearchRes, DebugStr, SearchInterfaces, {$If not Defined(Admin) AND not Defined(Monitorings)} BaseSearchInterfaces, nsContextHistory, nsLogEvent, LoggingUnit, {$IfEnd} ReqRow_Const, PrimQueryCard_utqcAttributeSearch_UserType, PrimQueryCard_utqcPostingOrder_UserType, PrimQueryCard_utqcLegislationReview_UserType, PrimQueryCard_utqcSendConsultation_UserType, PrimQueryCard_utqcInpharmSearch_UserType, f1QueryDocumentContainer, MainMenuNewRes, ControlsBlock_Const ; const cOldUserTypes = [utqcAttributeSearch, utqcPostingOrder, utqcLegislationReview, utqcInpharmSearch]; {$R *.DFM} {$If not defined(Admin) AND not defined(Monitorings)} type TnsSendTestRequestToLegalAdviceEvent = class(TnsLogEvent) public // public methods class procedure Log; end;//TnsSendTestRequestToLegalAdviceEvent {$IfEnd} //not Admin AND not Monitorings procedure TenQueryCard.MakeSearchManager(const aQuery: IQuery); {-} {$If not Defined(Admin) AND not Defined(Monitorings)} var l_ContextHistory: InsContextSearchHistory; {$IfEnd} begin {$If not Defined(Admin) AND not Defined(Monitorings)} if UserType = utqcInpharmSearch then l_ContextHistory := nsGetContextHistory(ns_chkInpharm) else l_ContextHistory := nsGetContextHistory(ns_chkDocument); {$IfEnd} f_MgrSearch := TqaMgrSearch.Make(aQuery, GetQueryType, nsCStr(CurUserType.Name), OnDateQuery, OnNeedExecQuery, OnModifiedChanged {$If not Defined(Admin) AND not Defined(Monitorings)} , l_ContextHistory {$IfEnd} ); end; procedure TenQueryCard.DoInit(aFormHistory : Boolean); {-} begin inherited; f_Update := False; if not IsQueryCardSupportFormSets then begin MakeSearchManager(nil); {$IFDEF Monitorings} TnsPostingsTreeSingle.Instance.MgrSearch := f_MgrSearch; {$ENDIF Monitorings} if not aFormHistory then ReadDocument; end;//not IsQueryCardSupportFormSets end; {$IfDef vcmUseSettings} procedure TenQueryCard.SettingsReplaceStart; // override; {* - для перекрытия в потомках, процедура вызывается перед переключением конфигураций, открытием диалога настроек. } begin Self.WriteMgrSettings; end; {$EndIf vcmUseSettings} procedure TenQueryCard.Cleanup; begin if Assigned(f_MgrSearch) then begin { Свернутость/Развернутость узлов } Self.WriteMgrSettings; if l3SystemDown then // <K: 138547857> f_MgrSearch.Clear; // <К: 131793204> {$IFDEF Monitorings} TnsPostingsTreeSingle.Instance.MgrSearch := nil; // http://mdp.garant.ru/pages/viewpage.action?pageId=294589844 {$ENDIF Monitorings} f_MgrSearch := nil; f_QueryCard := nil; end;//if Assigned(f_MgrSearch) then inherited; end; {$IfDef vcmUseSettings} procedure TenQueryCard.FinishDataUpdate; //override; {* вызывает по окончании обновления } begin inherited; Editor.TextSource.Lock(Self); try if Assigned(f_MgrSearch) then begin f_Update := True; try f_QueryCard := nil; Self.WriteMgrSettings; f_MgrSearch.InitUpdate; ReadDocument; finally f_Update := False; end;//try..finally end;//Assigned(f_MgrSearch) finally Editor.TextSource.UnLock(Self); end;//try..finally end; {$EndIf vcmUseSettings} function TenQueryCard.GetQueryType: TlgQueryType; begin Result := lg_qtNone; case UserType of utqcAttributeSearch : Result := lg_qtAttribute; utqcPostingOrder : Result := lg_qtPostingOrder; utqcLegislationReview : Result := lg_qtLegislationReview; utqcSendConsultation : Result := lg_qtSendConsultation; utqcInpharmSearch : Result := lg_qtInpharmSearch; end; end; procedure TenQueryCard.TextSourceDocumentChanged(aSender: TObject; const anOldDocument, aNewDocument: Ik2Tag); var l_QueryContainer : InevQueryDocumentContainer; begin if (Editor <> nil) then begin IevQueryCardEditor(Editor).ClearCardCache; if l3IOk(Editor.TextSource.DocumentContainer. QueryInterface(InevQueryDocumentContainer, l_QueryContainer)) then l_QueryContainer.ReleaseListners; if (aNewDocument <> nil) AND aNewDocument.IsValid then begin f_QueryCard := TevControlContainerEX.Make; f_QueryCard.LinkListner(f_MgrSearch As IevAdapterModel); f_QueryCard.LinkView(l_QueryContainer); if (f_MgrSearch <> nil) then begin f_MgrSearch.CreateTree(f_QueryCard); f_MgrSearch.ReadSettings; end; end; //(aNewDocument <> nil)... end;//Editor <> nil end;//TextSourceDocumentChanged procedure TenQueryCard.TextSourceGetControlItemImg(aSender: TObject; const aControl: TnevControlInfo; out theImageInfo: TnevControlImageInfo); var l_ControlType : TevControlType; begin if aControl.rControl.InheritsFrom(k2_idControlsBlock) then l_ControlType := ev_ctCollapsedPanel else l_ControlType := TevControlType(aControl.rControl.IntA[k2_tiType]); Case l_ControlType of ev_ctCalEdit: begin theImageInfo.rImageList := vtMakeImageListWrapper(nsSearchRes.ImageList16x16); theImageInfo.rFirstIndex := 1; end;//ev_ctCalEdit ev_ctPictureLabel: begin theImageInfo.rImageList := vtMakeImageListWrapper(nsSearchRes.ImageList); if l3Same(aControl.rControl.Owner.Owner.PCharLenA[k2_tiReqID], 'AT_CHECK_LAW_SUPPORT_AVAILABLE', true) then theImageInfo.rFirstIndex := 2 else theImageInfo.rFirstIndex := 0; end;//ev_ctPictureLabel ev_ctCollapsedPanel: begin if (dmMainMenuNew <> nil) then begin theImageInfo.rImageList := vtMakeImageListWrapper(dmMainMenuNew.ilSmallIcons); theImageInfo.rFirstIndex := -1; end;//dmMainMenuNew <> nil end;//ev_ctCollapsedPanel else begin theImageInfo.rImageList := vtMakeImageListWrapper(dmStdRes.SmallImageList); theImageInfo.rFirstIndex := -1; end;//else end;//Case l_ControlType end; function TenQueryCard.EditorJumpTo(Sender : TObject; anEffects : TafwJumpToEffects; const aMoniker : IevMoniker): Boolean; var l_HyperLink : IevHyperlink; l_Control : IevEditorControl; l_Req : IevComboReq; l_Para : InevPara; l_DescReq: Ik2Tag; l_Desc: IevDescriptionReq; l_DocID: LongWord; l_Modified: Boolean; l_QueryToSend: IQuery; begin Result := False; if Supports(aMoniker, IevHyperlink, l_HyperLink) then try if l_HyperLink.Exists then begin Assert(l_HyperLink.Address{$IfDef XE4}.rTafwAddress{$EndIf}.TypeID = CI_ExternalOperation,'Wrong hyperlink type'); if l_HyperLink.Para.QT(InevPara, l_Para) then try l_DocID := l_HyperLink.Address{$IfDef XE4}.rTafwAddress{$EndIf}.DocID; if (l_DocID = EOI_OPEN_ATTRIBUTE_CARD) then begin if l_Para.QT(IevEditorControl, l_Control) then try if Supports(l_Control.Req, IevComboReq, l_Req) then try if l_Control.Enabled then l_Req.HyperLinkClick; Result := True; finally l_Req := nil; end;//try..finally finally l_Control := nil; end;//try..finally end//l_DocID = EOI_OPEN_ATTRIBUTE_CARD else if l_DocID = EOI_SHOW_HELP_TOPIC then with f_MgrSearch.QueryCard, Application.HelpSystem do case CardType of ev_qtConsultations: ShowTopicHelp(cHelpConsultingRules, ''); ev_qtAttributeSearch: ShowTopicHelp(cHelpAttributeRules, ''); ev_qtInpharm: ShowTopicHelp(cHelpSearchInpharm, ''); else Assert(False); end//case CardType of else if l_DocID = EOI_SHOW_LC_HELP then Application.HelpSystem.ShowTopicHelp('page-man-search-req-fields.htm#law_calendar', '') else if l_DocID = EOI_CHANGE_COLLAPSED then begin if evInPara(l_Para,k2_idReqRow,l_DescReq) and l_DescReq.IsValid then with l_DescReq.Attr[k2_tiReqID] do if IsValid then begin l_Desc := f_MgrSearch.QueryCard.FindDescriptionReq(AsPCharLen); if Assigned(l_Desc) then l_Desc.Collapsed := not l_Desc.Collapsed; Result := True; end; end else if (l_DocID = EOI_CHECK_LEGAL_ADVISE_AVAILABLE) and (f_MgrSearch.QueryCard.CardType = ev_qtConsultations) and Ask(qr_CheckLegalAdviseAvailable) then begin if not defDataAdapter.ConsultationManager.CheckConsultingAvailable then Say(war_NoSubscription, [defDataAdapter.GetDealerInfo]) else begin l_Modified := f_MgrSearch.Modified; try f_MgrSearch.Save(True); f_MgrSearch.Query.Clone(l_QueryToSend); try SaveContextNew(l_QueryToSend, nsCStr(AT_LAW_SUPPORT_TEXT), vcmCStr(str_CheckLegalAdviseAvailable), True); try {$If not defined(Admin) AND not defined(Monitorings)} TnsSendTestRequestToLegalAdviceEvent.Log; {$IfEnd} l_QueryToSend.SendQuery; Say(inf_ConsultationSuccessCheck); except on ENoConnection do Say(war_NoConnectionOnSend, [defDataAdapter.GetDealerInfo]); on ENoSubscription do Say(war_NoSubscription, [defDataAdapter.GetDealerInfo]); end;//try..except finally l_QueryToSend := nil end; finally f_MgrSearch.Modified := l_Modified; end; end;//if not defDataAdapter.ConsultationManager.CheckConsultingAvailable end;//if (l_DocID = 7) and (f_MgrSearch.QueryCard.CardType = ev_qtConsultations) and... finally l_Para := nil; end;//try..finally end;//l_HyperLink.Exists finally l_HyperLink := nil; end;//try..finally end; procedure TenQueryCard.OnDateQuery(const aValue: IqaDateReqDataHolder); begin {$IFDEF Monitorings} Assert(false); {$ELSE} TdmStdRes.DateQuery(Self.As_IvcmEntityForm, aValue); {$ENDIF Monitorings} end; procedure TenQueryCard.vcmEntityFormLoadState(const aState: IvcmBase; aStateType: TvcmStateType; var Loaded: Boolean); var l_History : IqaHistory; begin if (aStateType = vcm_stContent) and not IsQueryCardSupportFormSets then begin { История присутствует } if Supports(aState, IqaHistory, l_History) then begin try { Если было обновление данных, то ничего не делаем } if not l_History.DataReset then begin f_MgrSearch.FromHistory := True; //Чтобы не грузить лишнее f_MgrSearch.Query := l_History.Query; f_MgrSearch.FromHistory := False; if (f_MgrSearch.QueryCard.CardType = ev_qtConsultations) then f_MgrSearch.Modified := l_History.ConsultationSended {$IFDEF Monitorings} else f_MgrSearch.Modified := TnsPostingsTreeSingle.Instance.OldModifed; {$ELSE Monitorings} ; {$ENDIF Monitorings} end//if not l_History.DataReset then { Открываем форму как последную открытую } else FinishDataUpdate; finally l_History := nil; end;//if Supports(aState, IasHistory, l_History) then end//if Supports(aState, IasHistory, l_History) then { История отсутствует читаем настройки по "Развернутости групп" по умолчанию } else if Assigned(f_MgrSearch) then f_MgrSearch.ReadSettings; end; end; procedure TenQueryCard.vcmEntityFormSaveState(out aState: IvcmBase; aStateType: TvcmStateType; var Saved: Boolean); var l_IHistory : IqaHistory; l_THistory : TqaHistory; begin // Закроем все открытые комбобоксы. if (f_MgrSearch.QueryCard <> nil) then (f_MgrSearch.QueryCard As InevControlListner).HideDroppedControl(True); if not IsQueryCardSupportFormSets and (aStateType = vcm_stContent) then begin { Запишем настройки "Развернутости групп" по умолчанию } Self.WriteMgrSettings; l_THistory := TqaHistory.Create{(Self)}; try if Supports(l_THistory, IqaHistory, l_IHistory) then try if f_MgrSearch.Modified then Saved := f_MgrSearch.Save(True) else Saved := True; if Saved then begin l_IHistory.Query := f_MgrSearch.Query; if (f_MgrSearch.QueryCard <> nil) AND (f_MgrSearch.QueryCard.CardType = ev_qtConsultations) then l_IHistory.ConsultationSended := not f_MgrSearch.Modified; aState := l_IHistory as IvcmBase; end; finally l_IHistory := nil; end; finally vcmFree(l_THistory); end; end; end; procedure TenQueryCard.OnNeedExecQuery(Sender: TObject); begin if Assigned(Aggregate) then Aggregate.Operation(TdmStdRes.opcode_Result_OkExt); end; procedure TenQueryCard.ReadDocument; begin if f_Update then TextSource.DocumentContainer := nil; //Пока приходится "грохать" DocumentContainer. TextSource.DocumentContainer := Tf1QueryDocumentContainer.Make(GetQueryType, f_MgrSearch As IevAdapterModel); if not TextSource.Document.TagType.Prop[k2_tiBackColor].ReadOnly then TextSource.Document.Attr[k2_tiBackColor] := nil; if f_MgrSearch.QueryCard.CardType = ev_qtConsultations then LoadConsultationCreditnails; end; procedure TenQueryCard.vcmEntityFormChangedDataSource(aSender: TObject; const aOld, aNew: IvcmFormDataSource; const aFromHistory: Boolean); begin if (dsQuery <> nil) then begin Editor.TextSource.Lock(Self); try f_MgrSearch := nil; MakeSearchManager(dsQuery.Query); if not aFromHistory then ReadDocument else begin if (f_QueryCard <> nil) then begin f_MgrSearch.CreateTree(f_QueryCard); if (f_MgrSearch.QueryCard.CardType = ev_qtConsultations) then f_MgrSearch.Modified := not dsQuery.IsQuerySaved; end;//f_QueryCard <> nil end;//not aFromHistory finally Editor.TextSource.UnLock(Self); end;//try..finally end;//dsQuery <> nil end;//vcmEntityFormChangedDataSource function TenQueryCard.IsQueryCardSupportFormSets: Boolean; begin Result := not (UserType in cOldUserTypes); end;//IsQueryCardSupportFormSets procedure TenQueryCard.OnModifiedChanged(Sender: TObject); begin if (dsQuery <> nil) then dsQuery.IsQuerySaved := not f_MgrSearch.Modified; end; procedure TenQueryCard.EditorAfterFirstPaint(Sender: TObject); begin {$IfDef vcmUseProfilers} ProfilersManager.QueryCard.Finish; {$EndIf vcmUseProfilers} end; procedure TenQueryCard.HandleException(anException: EqaException); var l_CardType : TevQueryType; l_ReqName : Il3CString; begin l_CardType := f_MgrSearch.QueryCard.CardType; if ((l_CardType = ev_qtConsultations) or (l_CardType = ev_qtSearchWithLawSupport)) and (anException is EqaRequiredValue) then begin l_ReqName := anException.ErrorControl.Req.ReqName; if (l3Same(l_ReqName, AT_CONSULTATION_TEXT)) or (l3Same(l_ReqName, AT_LAW_SUPPORT_TEXT)) then Say(inf_QueryTextIsEmpy) else if (l3Same(l_ReqName, AT_USER_NAME)) or (l3Same(l_ReqName, AT_USER_PHONE)) then Say(err_UserCredinailsIsEmpy) else MessageDlg(nsCStr(StringReplace(anException.Message,'&&','&',[rfReplaceAll])), 'TenQueryCard.HandleException', mtError); end//l_CardType = ev_qtConsultations.. else if not (anException is EqaSilentAbort) then MessageDlg(nsCStr(StringReplace(anException.Message,'&&','&',[rfReplaceAll])), 'TenQueryCard.HandleException', mtError); end; procedure TenQueryCard.LoadConsultationCreditnails; var l_Req : IqaReq; l_PhoneReq : IqaPhoneReq; l_FocusControl : IevEditorControlField; l_S : Il3CString; l_Pack : InevOp; begin l_FocusControl := nil; l_Pack := Editor.Processor.StartOp(0, True); try l_Pack.SaveUndo := False; with afw.Application.PermanentSettings do begin l_Req := f_MgrSearch.FindAttr(nsCStr(AT_USER_NAME)); if (l_Req <> nil) then begin l_S := LoadString(CalcUserNameSettings); l_Req.EditorReq.FirstField.Text := l_S; if l3IsNil(l_S) then l_FocusControl := l_Req.EditorReq.FirstField; end;//l_Req <> nil l_Req := f_MgrSearch.FindAttr(nsCStr(AT_USER_PHONE)); if (l_Req <> nil) and Supports(l_Req, IqaPhoneReq, l_PhoneReq) then begin l_S := LoadString(CalcUserPhoneCodeSettings); l_PhoneReq.Code := l_S; if l3IsNil(l_S) and (l_FocusControl = nil) then l_FocusControl := l_Req.EditorReq.FirstField; l_S := LoadString(CalcUserPhoneNumberSettings); l_PhoneReq.Number := l_S; if l3IsNil(l_S) and (l_FocusControl = nil) then l_FocusControl := (l_Req.EditorReq.FirstField as IevEditorPhoneField).GetOtherField; end;//l_Req <> nil l_Req := f_MgrSearch.FindAttr(nsCStr(AT_EMAIL)); if (l_Req <> nil) then begin l_S := LoadString(CalcEMailSettings); l_Req.EditorReq.FirstField.Text := l_S; if l3IsNil(l_S) and (l_FocusControl = nil) then l_FocusControl := l_Req.EditorReq.FirstField; end;//l_Req <> nil end;//afw.Application.Settings finally l_Pack := nil; end;//try..finally if l_FocusControl = nil then l_FocusControl := f_MgrSearch.FindAttr(nsCStr(AT_LAW_SUPPORT_TEXT)).EditorReq.FirstField; l_FocusControl.Req.SetFocus(l_FocusControl, True); end; procedure TenQueryCard.SaveConsultationCreditnails; var l_Req: IqaReq; l_PhoneReq: IqaPhoneReq; begin with afw.Application.PermanentSettings do begin l_Req := f_MgrSearch.FindAttr(nsCStr(AT_USER_NAME)); if Assigned(l_Req) then SaveString(CalcUserNameSettings, l_Req.GetReqAsString(nil)); l_Req := f_MgrSearch.FindAttr(nsCStr(AT_USER_PHONE)); if Assigned(l_Req) and Supports(l_Req, IqaPhoneReq, l_PhoneReq) then begin SaveString(CalcUserPhoneCodeSettings, l_PhoneReq.Code); SaveString(CalcUserPhoneNumberSettings, l_PhoneReq.Number); end;//Assigned(l_Req) l_Req := f_MgrSearch.FindAttr(nsCStr(AT_EMAIL)); if Assigned(l_Req) then SaveString(CalcEMailSettings, l_Req.GetReqAsString(nil)); end;//with afw.Application.Settings end; function TenQueryCard.CalcUserNameSettings: TafwSettingID; begin Result := pi_ConsultationAttributes+'/'+AT_USER_NAME; end; function TenQueryCard.CalcUserPhoneCodeSettings: TafwSettingID; begin Result := pi_ConsultationAttributes+'/'+AT_USER_PHONE+'/Code'; end; function TenQueryCard.CalcUserPhoneNumberSettings: TafwSettingID; begin Result := pi_ConsultationAttributes+'/'+AT_USER_PHONE+'/Number'; end; function TenQueryCard.CalcEMailSettings: TafwSettingID; begin Result := pi_ConsultationAttributes+'/'+AT_EMAIL; end; {$If not defined(Admin) AND not defined(Monitorings)} { TnsSendTestRequestToLegalAdviceEvent } class procedure TnsSendTestRequestToLegalAdviceEvent.Log; begin GetLogger.AddEvent(LE_SEND_TEST_REQUEST_TO_LEGAL_ADVISE, MakeParamsList); end; {$IfEnd} //not Admin AND not Monitorings procedure TenQueryCard.CleanDependencies; //http://mdp.garant.ru/pages/viewpage.action?pageId=429695931 begin inherited; f_MgrSearch := nil; f_QueryCard := nil; end; end.
(* _______________________________________________________________________ | | | CONFIDENTIAL MATERIALS | | | | These materials include confidential and valuable trade secrets owned | | by JP Software Inc. or its suppliers, and are provided to you under | | the terms of a non-disclosure agreement. These materials may not be | | transmitted or divulged to others or received, viewed, or used by | | others in any way. All source code, source code and technical | | documentation, and related notes, are unpublished materials, except | | to the extent that they are in part legally available as published | | works from other suppliers, and use of a copyright notice below does | | not imply publication of these materials. | | | | This notice must remain as part of these materials and must not be | | removed. | | | | Unpublished work, Copyright 1988, 1989, 1990, 1991, J.P. Software | | Inc., All Rights Reserved. Portions Copyright 1985, 1987, Borland | | International Inc. | |_______________________________________________________________________| *) { Screen Routines Copyright (c) 1985,87 by Borland International, Inc. ( from the Editor Toolbox Version 4 ) Modified for 4HELP by Ross Neilson Wentworth } {$I-} {$R-} {$V-} {$S-} unit SInst; {-Fast screen writing routines for installation programs} interface uses tpCrt, {screen routines - standard unit} Dos; {dos calls - standard unit} const Defnorows = 25; {Default number of rows/physical screen} Defnocols = 80; {Default number of cols/physical screen} type ScreenBuffer = array[0..1999] of Word; {Structure of video memory} WindowRec = record TopRow, LeftCol, Width, Height : Byte; Contents : array[0..1999] of Integer; end; WindowPtr = ^WindowRec; var RetraceMode : Boolean; {Check for snow on color cards?} LoColor, {LOw video} TiColor, {TItle / high video} ChColor, {CHanged keystrokes} EdColor, {keystroke being EDited / reverse video} CfColor : Byte; {ConFlicting keystrokes} procedure RestoreScreen; {-Clean up screen at end of program} procedure SetColor(TheColor : Byte); {-set both textcolor and textbackground} procedure MakeBox(Left, Top, Right, Bottom, Attr : Byte); {-Draw a box on the screen} procedure SaveWindow(var WP : WindowPtr; Left, Top, Right, Bottom : Byte; Alloc : Boolean); {-Save a window} procedure RestoreWindow(var WP : WindowPtr; DeAlloc : Boolean); {-Restore a previously saved window and dispose of memory allocated to it} procedure SinstGetScreenMode(ForceMono : boolean); {-determine screen address and colors} {==========================================================================} implementation procedure RestoreScreen; {-Clean up screen at end of program} begin {RestoreScreen} NormVideo; (* !!! *) Window(1, 1, ScreenWidth, ScreenHeight); ClrScr; end; {RestoreScreen} procedure SetColor(TheColor : Byte); {-Set both textcolor and textbackground} begin TextColor(TheColor and $F); TextBackground(TheColor shr 4); end; {SetColor} procedure MakeBox(Left, Top, Right, Bottom, Attr : Byte); {-Draw a box on the screen} var Row : Byte; Span : String[80]; SLen : Byte absolute Span; const Upright : string[1] = #179; begin {MakeBox} SLen := Pred(Right-Left); FillChar(Span[1], SLen, #196); {Top} FastWrite( #218+Span+#191, Top, Left, Attr); {Bottom} FastWrite(#192+Span+#217, Bottom, Left, Attr); {Middle} for Row := Succ(Top) to Pred(Bottom) do begin FastWrite(Upright, Row, Left, Attr); FastWrite(UpRight, Row, Right, Attr); end; end; {MakeBox} procedure SaveWindow(var WP : WindowPtr; Left, Top, Right, Bottom : Byte; Alloc : Boolean); {-Save a window} var Ofst : Word; W, H, I : Integer; begin {SaveWindow} W := Succ(Right-Left); H := Succ(Bottom-Top); if Alloc then GetMem(WP, (W*H) shl 1 + 4); with WP^ do begin Width := W; Height := H; TopRow := Top; LeftCol := Left; for I := 0 to Pred(H) do begin Ofst := ( ((Pred(Top)+I) * ScreenWidth) + Pred(Left) ) shl 1; MoveScreen(Mem[VideoSegment:Ofst], Contents[I*W], W); end; end; end; {SaveWindow} procedure RestoreWindow(var WP : WindowPtr; DeAlloc : Boolean); {-Restore a previously saved window and dispose of memory allocated to it} var I : Integer; Ofst : Word; begin {RestoreWindow} with WP^ do begin for I := 0 to Pred(Height) do begin Ofst := ( ((Pred(TopRow)+I) * ScreenWidth) + Pred(LeftCol) ) shl 1; MoveScreen(Contents[I*Width], Mem[VideoSegment:Ofst], Width); end; if DeAlloc then begin Freemem(WP, (Width*Height) shl 1 + 4); WP := Nil; end; end; end; {RestoreWindow} procedure SinstGetScreenMode(ForceMono : boolean); {-determine screen address and colors} procedure ChooseColorSet(Mono : Boolean); begin if Mono then begin LoColor := $07; TiColor := $0F; ChColor := $0F; EdColor := $70; CfColor := $70; end else begin LoColor := $07; TiColor := $0E; ChColor := $0F; EdColor := $1E; CfColor := $4F; end; end; begin {EdGetScreenMode} If CurrentMode < 2 Then TextMode (CurrentMode + 2); Retracemode := (CurrentMode <> 7); if Retracemode then begin {Color card} Retracemode := Not (CurrentDisplay In[EGA,VGA]); ChooseColorSet((CurrentMode <> 3) or ForceMono) end else begin {Monochrome} ChooseColorSet(True); end; end; {EdGetScreenMode} begin end. 
unit midi.output; interface uses System.Math, WinApi.Windows; type TMIDIOutput = class private _queue: THANDLE; _timer: THANDLE; _period: DWORD; _steps: integer; procedure Tick; public constructor Create; destructor Destroy; override; procedure SetTimer(period: integer); procedure SetTempo(tempo: integer); procedure Start; procedure Stop; end; implementation { TMIDIOutput } procedure TimerCallback(parameter: Pointer; timerOrWaitFired: boolean); stdcall; var output: TMIDIOutput; begin output := TMIDIOutput(parameter); output.Tick; end; constructor TMIDIOutput.Create; begin _queue := CreateTimerQueue; _period := 1; _steps := 16; end; destructor TMIDIOutput.Destroy; var completion: THandle; begin completion := CreateEvent(nil, false, false, nil); DeleteTimerQueueEx(_queue, completion); WaitForSingleObject(completion, INFINITE); CloseHandle(completion); inherited; end; procedure TMIDIOutput.SetTempo(tempo: integer); var period: single; begin period := 1000.0 * 60.0 * 4.0 / tempo / _steps; _period := floor(period); end; procedure TMIDIOutput.SetTimer(period: integer); begin _period := period; end; procedure TMIDIOutput.Start; begin CreateTimerQueueTimer(_timer, _queue, TimerCallback, self, _period, _period, WT_EXECUTEDEFAULT); end; procedure TMIDIOutput.Stop; var completion: THANDLE; begin if _timer <> INVALID_HANDLE_VALUE then begin completion := CreateEvent(nil, false, false, nil); DeleteTimerQueueTimer(_queue, _timer, completion); WaitForSingleObject(completion, INFINITE); CloseHandle(completion); end; end; procedure TMIDIOutput.Tick; begin // end; end.
unit DW.OSLog.Mac; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // DW DW.OSLog; type /// <remarks> /// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS /// </remarks> TPlatformOSLog = record public class procedure Log(const ALogType: TLogType; const AMsg: string); static; end; implementation uses // RTL System.SysUtils, // macOS Macapi.Helpers, Macapi.ObjCRuntime; const libFoundation = '/System/Library/Frameworks/Foundation.framework/Foundation'; type PNSString = Pointer; procedure NSLog(format: PNSString); cdecl; varargs; external libFoundation name _PU + 'NSLog'; { TPlatformOSLog } class procedure TPlatformOSLog.Log(const ALogType: TLogType; const AMsg: string); begin NSLog(StringToID(cLogTypeCaptions[ALogType] + ': ' + AMsg)); end; end.
unit DirectStuff; interface uses Windows, DirectDraw, Direct3D; {$IFOPT C+} function DDR( Value : HRESULT ) : HRESULT; var ddRes : HRESULT; {$ENDIF} // DirectX Version Specific Type Setup type IDirectDraw = IDirectDraw7; IDirectSurface = IDirectDrawSurface7; IDirectPalette = IDirectDrawPalette; IDirectClipper = IDirectDrawClipper; type TDirectSurfaceDesc = TDDSurfaceDesc2; TDirectSurfaceCaps = TDDSCaps2; TDirectDrawCaps = TDDCaps; TDirectBltFX = TDDBLTFX; TDirectOverlayFX = TDDOverlayFX; // procedure InitRecord( var aRecord; Size : cardinal ); function ClearSurface( Surface : IDirectSurface; Color : dword ) : boolean; implementation uses SysUtils; // Misc Stuff function ClearSurface( Surface : IDirectSurface; Color : dword ) : boolean; var BltFx : TDirectBltFX; begin assert( Surface <> nil, 'Invalid surface!!' ); InitRecord( BltFx, sizeof(BltFx) ); BltFx.dwFillColor := Color; Result := DDR( Surface.Blt( nil, nil, nil, DDBLT_COLORFILL or DDBLT_WAIT, @BltFx ) ) = DD_OK; end; procedure InitRecord( var aRecord; Size : cardinal ); var dwSize : dword absolute aRecord; begin ZeroMemory( @aRecord, Size ); dwSize := Size; end; {$IFOPT C+} function DDR( Value : HRESULT ) : HRESULT; begin Result := Value; if Value <> DD_OK then begin OutputDebugString( pchar( 'DDError: ' + IntToStr( Result ) ) ); raise Exception.Create( ErrorString( Result ) ); end; end; {$ELSE} function DDR( Value : HRESULT ) : HRESULT; begin Result := Value; end; {$ENDIF} end.
UNIT TIME; INTERFACE uses crt,dos,general; function JOUR(dayofweek:word):string; function MOIS(month:word):string; function HMS(hour,minute,seconde:word):string; function JMA(year,month,day:word):string; function NBREJOUR(year,month:word):integer; function JOURDESEMAINE(year,month,day:word):word; procedure JOURPRECEDANT(var year,month,day,dayofweek:word); procedure JOURSUIVANT(var year,month,day,dayofweek:word); procedure MOISPRECEDANT(var year,month:word); procedure MOISSUIVANT(var year,month:word); IMPLEMENTATION FUNCTION JOUR(dayofweek:word):string; {*******************************************************} { Renvoie jour de semaine en lettres {*******************************************************} begin case dayofweek of 0:jour:='Dimanche'; 1:jour:='Lundi'; 2:jour:='Mardi'; 3:jour:='Mercredi'; 4:jour:='Jeudi'; 5:jour:='Vendredi'; 6:jour:='Samedi'; end; end; FUNCTION MOIS(month:word):string; {*******************************************************} { Renvoie mois de l'ann‚e en lettres {*******************************************************} begin case month of 1:mois:='Janvier'; 2:mois:='F‚vrier'; 3:mois:='Mars'; 4:mois:='Avril'; 5:mois:='Mai'; 6:mois:='Juin'; 7:mois:='Juillet'; 8:mois:='Aout'; 9:mois:='Septembre'; 10:mois:='Octobre'; 11:mois:='Novembre'; 12:mois:='D‚cembre'; end; end; FUNCTION HMS(hour,minute,seconde:word):string; {*******************************************************} {Renvoie chaine dans format HH:MM, HH:MM,SS, MM:SS {selon la valeur de HH,MM,SS (Heure/Minute/Seconde) {*******************************************************} var s:string; begin if hour<24 then s:=FILLZERO(hour,2)+':'; s:=s+FILLZERO(minute,2); if seconde<60 then s:=s+':'+FILLZERO(seconde,2); hms:=s; end; FUNCTION JMA(year,month,day:word):string; {*******************************************************} { Renvoie chaine avec DD/MM/YYYY (Jour/Mois/Ann‚e) {*******************************************************} begin jma:=FILLZERO(day,2)+'/'+FILLZERO(month,2)+'/'+FILLZERO(year,4); end; FUNCTION NBREJOUR(year,month:word):integer; {*******************************************************} { Renvoie nombre de jours dans month de year {*******************************************************} begin case month of 1,3,5,7,8,10,12:nbrejour:=31; 4,6,9,11:nbrejour:=30; 2:begin if year mod 4=0 then nbrejour:=29 else nbrejour:=28; end; end; end; FUNCTION JOURDESEMAINE(year,month,day:word):word; {*******************************************************} { Renvoie jourdesemain(0-6) du day/month/year { Jour de r‚f‚rence:1 janvier 0000=vendredi { Ann‚e 0=ann‚e bissextile {*******************************************************} var i,j:longint; function decalagebi(year,month:word):integer; begin if (year mod 4=0) and (month<3) then decalagebi:=(year div 4) else decalagebi:=1+(year div 4); end; begin if (day<1) or (day>NBREJOUR(year,month)) then begin writeln('Erreur: Le ',day,'/',month,'/',year,' n''existe pas.'); halt; end; { i=nbre jours d‚calage/1 janvier 0000 } case month of 1:i:=0; 2:i:=31; 3:i:=59; 4:i:=90; 5:i:=120; 6:i:=151; 7:i:=181; 8:i:=212; 9:i:=243; 10:i:=273; 11:i:=304; 12:i:=334; end; j:=year; i:=j*365+i+day-1+decalagebi(year,month); i:=i mod 7; jourdesemaine:=(5+i) mod 7 end; PROCEDURE JOURPRECEDANT(var year,month,day,dayofweek:word); {*******************************************************} {*******************************************************} begin dec(day); if day<1 then begin dec(month); if month<1 then begin dec(year);month:=12;day:=31; end else day:=NBREJOUR(year,month); end; dayofweek:=JOURDESEMAINE(year,month,day); end; PROCEDURE JOURSUIVANT(var year,month,day,dayofweek:word); {*******************************************************} {*******************************************************} begin inc(day); if day>NBREJOUR(year,month) then begin day:=1;inc(month); if month>12 then begin inc(year);month:=1; end; end; dayofweek:=JOURDESEMAINE(year,month,day); end; PROCEDURE MOISPRECEDANT(var year,month:word); {*******************************************************} {*******************************************************} begin dec(month); if month<1 then begin dec(year);month:=12; end; end; PROCEDURE MOISSUIVANT(var year,month:word); {*******************************************************} {*******************************************************} begin inc(month); if month>12 then begin inc(year);month:=1; end; end; end.
// This unit is the manager to all block releated in the game. // Esta unit gere tudo o que tem a ver com blocos no jogo. unit BlockManager; interface // Uses GlobalVariables to have access to the global variables... // Uses GlobalVaraibles para ter acesso ás variavels globais... uses crt, GlobalVariables; // This renders a specific block. // Aqui renderizamos um bloco especifico. Procedure Render(x, y, tc, bc : Integer; simbol : char); // Using this method you can add more blocks to the game. // There is a proxy for this method called setBlock on the LevelManager Unit. // Usando este procedimento podemos adicionar um novo bloco ao jogo. // Existe uma proxy para esta funcao presente na Unit LevelManager chamada setBlock. Procedure setLibBlock(IDs, tc, bc : Integer; n : String; s : char; isCollidable : boolean); // This method adds a Temporary block to the map. // Esta funcao adiciona um bloco temporario ao mapa. Procedure setBlockTempAt(x, y : Integer; block : blockType); // This method adds a game block to the map. // Esta funcao adiciona um bloco ao mapa. Procedure setBlockAt(x, y, ID : Integer); // This method gets us the block at a certain location on the map. // Esta funcao retorna o bloco presente numa certa localizacao no mapa. Function getBlockAt(x, y : Integer) : blockType; // This method gets us the block text color at a certain location on the map. // Esta funcao retorna a cor do texto de um bloco presente numa certa localizacao no mapa. Function getBlockTColor(x, y : Integer): Integer; // This method gets us the block background color at a certain location on the map. // Esta funcao retorna a cor de fundo de um bloco presente numa certa localizacao no mapa. Function getBlockBColor(x, y : Integer): Integer; // This method gets us the block name at a certain location on the map. // Esta funcao retorna o nome de um bloco presente numa certa localizacao no mapa. Function getBlockName(x, y : Integer): String; // This method gets us the block simbol at a certain location on the map. // Esta funcao retorna o simbolo de um bloco presente numa certa localizacao no mapa. Function getBlockSimbol(x, y : Integer): Char; // This method tells us if the block is collidable // Esta funcao informa-nos se um bloco é colidivel. Function isBlockCollidable(x, y : Integer): boolean; // This procedures gives an action to a block, like teleporting and what so ever. // Este procedimento dá uma acao a um bloco como teleports e etc's. Procedure setBlockAction(x, y, tx, ty, tl : Integer); // This procedure removes the action of a block. // Este procedimento remove a acao de um bloco. Procedure removeBlockAction(x, y : Integer); // This opens a door. // Aqui abrimos uma porta. Procedure openDoor(x, y : Integer); // This fechamos a door. // Aqui fechamos uma porta. Procedure closeDoor(x, y : Integer); implementation // This renders a specific block. // Aqui renderizamos um bloco especifico. Procedure Render(x, y, tc, bc : Integer; simbol : char); Begin GotoXY(screen.x + x, screen.y + y); TextBackground(bc); TextColor(tc); write(simbol); TextBackground(0); TextColor(10); GotoXY(2, screen.y + screen.height + 1); End; // Using this method you can add more blocks to the game. // There is a proxy for this method called setBlock on the LevelManager Unit. // Usando este procedimento podemos adicionar um novo bloco ao jogo. // Existe uma proxy para esta funcao presente na Unit LevelManager chamada setBlock. Procedure setLibBlock(IDs, tc, bc : Integer; n : String; s : char; isCollidable : boolean); Begin With blocks[IDs] do Begin ID := IDs; tColor := tc; bColor := bc; collidable := isCollidable; Name := n; Simbol := s; action.useAction := false; End; End; // This method adds a Temporary block to the map. // Esta funcao adiciona um bloco temporario ao mapa. Procedure setBlockTempAt(x, y : Integer; block : blockType); Begin worldBlocks[x + y * screen.width] := block; End; // This method adds a game block to the map. // Esta funcao adiciona um bloco ao mapa. Procedure setBlockAt(x, y, ID : Integer); Begin worldBlocks[x + y * screen.width] := blocks[ID]; End; // This method gets us the block at a certain location on the map. // Esta funcao retorna o bloco presente numa certa localizacao no mapa. Function getBlockAt(x, y : Integer) : blockType; Begin getBlockAt := worldBlocks[x + y * screen.width]; End; // This method gets us the block text color at a certain location on the map. // Esta funcao retorna a cor do texto de um bloco presente numa certa localizacao no mapa. Function getBlockTColor(x, y : Integer): Integer; Begin getBlockTColor := getBlockAt(x, y).tColor; End; // This method gets us the block background color at a certain location on the map. // Esta funcao retorna a cor de fundo de um bloco presente numa certa localizacao no mapa. Function getBlockBColor(x, y : Integer): Integer; Begin getBlockBColor := getBlockAt(x, y).bColor; End; // This method gets us the block name at a certain location on the map. // Esta funcao retorna o nome de um bloco presente numa certa localizacao no mapa. Function getBlockName(x, y : Integer): String; Begin getBlockName := getBlockAt(x, y).name; End; // This method gets us the block simbol at a certain location on the map. // Esta funcao retorna o simbolo de um bloco presente numa certa localizacao no mapa. Function getBlockSimbol(x, y : Integer): Char; Begin getBlockSimbol := getBlockAt(x, y).Simbol; End; // This method tells us if the block is collidable // Esta funcao informa-nos se um bloco é colidivel. Function isBlockCollidable(x, y : Integer): boolean; Begin isBlockCollidable := getBlockAt(x, y).collidable; End; // This procedures gives an action to a block, like teleporting and what so ever. // Este procedimento dá uma acao a um bloco como teleports e etc's. Procedure setBlockAction(x, y, tx, ty, tl : Integer); var temp : blocktype; Begin temp := getBlockAt(x, y); With temp.action do Begin x := tx; y := ty; level := tl; useAction := true; End; setBlockTempAt(x, y, temp); End; // This procedure removes the action of a block. // Este procedimento remove a acao de um bloco. Procedure removeBlockAction(x, y : Integer); Begin With getBlockAt(x, y).action do Begin useAction := false; End; End; // This opens a door. // Aqui abrimos uma porta. Procedure openDoor(x, y : Integer); var door1, door2 : blockType; Begin door1 := getBlockAt(x, y); door2 := getBlockAt(x, y + 1); if (door2.name = 'SDoor') then Begin With door1 do Begin Render(x, y, 0, 0, ' '); Render(door.xt, door.yt, tColor, bColor, simbol); door.opened := true; collidable := false; End; With door2 do Begin Render(x, y + 1, 0, 0, ' '); Render(door.xt, door.yt, tColor, bColor, simbol); door.opened := true; collidable := false; End; setBlockTempAt(x, y, door1); setBlockTempAt(x, y + 1, door2); End Else Begin door2 := getBlockAt(x + 1, y); With door1 do Begin Render(x, y, 0, 0, ' '); Render(door.xt, door.yt, tColor, bColor, simbol); door.opened := true; collidable := false; End; With door2 do Begin Render(x + 1, y, 0, 0, ' '); Render(door.xt, door.yt, tColor, bColor, simbol); door.opened := true; collidable := false; End; setBlockTempAt(x, y, door1); setBlockTempAt(x + 1, y, door2); End; End; // This fechamos a door. // Aqui fechamos uma porta. Procedure closeDoor(x, y : Integer); var door1, door2 : blockType; Begin door1 := getBlockAt(x, y); door2 := getBlockAt(x, y + 1); if (door2.name = 'SDoor') then Begin With door1 do Begin Render(x, y, tColor, bColor, simbol); Render(door.xt, door.yt, getBlockTColor(door.xt, door.yt), getBlockBColor(door.xt, door.yt), getBlockSimbol(door.xt, door.yt)); door.opened := false; collidable := true; End; With door2 do Begin Render(x, y + 1, tColor, bColor, simbol); Render(door.xt, door.yt, getBlockTColor(door.xt, door.yt), getBlockBColor(door.xt, door.yt), getBlockSimbol(door.xt, door.yt)); door.opened := false; collidable := true; End; setBlockTempAt(x, y, door1); setBlockTempAt(x, y + 1, door2); End Else Begin door2 := getBlockAt(x + 1, y); With door1 do Begin Render(x, y, tColor, bColor, simbol); Render(door.xt, door.yt, getBlockTColor(door.xt, door.yt), getBlockBColor(door.xt, door.yt), getBlockSimbol(door.xt, door.yt)); door.opened := false; collidable := true; End; With door2 do Begin Render(x + 1, y, tColor, bColor, simbol); Render(door.xt, door.yt, getBlockTColor(door.xt, door.yt), getBlockBColor(door.xt, door.yt), getBlockSimbol(door.xt, door.yt)); door.opened := false; collidable := true; End; setBlockTempAt(x, y, door1); setBlockTempAt(x + 1, y, door2); End; End; end.
unit ExcludedTestsFolders; {* Папки тестов исключаемые из запуска } // Модуль: "w:\common\components\rtl\Garant\DUnitTuning\ExcludedTestsFolders.pas" // Стереотип: "SimpleClass" // Элемент модели: "TExcludedTestsFolders" MUID: (4C9386230151) {$Include w:\common\components\rtl\Garant\DUnitTuning\tfwDefine.inc} interface {$If Defined(nsTest) AND NOT Defined(NotTunedDUnit)} uses l3IntfUses , l3StringList ; type TExcludedTestsFolders = class(Tl3StringList) {* Папки тестов исключаемые из запуска } public class function Exists: Boolean; class function Instance: TExcludedTestsFolders; {* Метод получения экземпляра синглетона TExcludedTestsFolders } end;//TExcludedTestsFolders {$IfEnd} // Defined(nsTest) AND NOT Defined(NotTunedDUnit) implementation {$If Defined(nsTest) AND NOT Defined(NotTunedDUnit)} uses l3ImplUses , SysUtils , l3Base //#UC START# *4C9386230151impl_uses* //#UC END# *4C9386230151impl_uses* ; var g_TExcludedTestsFolders: TExcludedTestsFolders = nil; {* Экземпляр синглетона TExcludedTestsFolders } procedure TExcludedTestsFoldersFree; {* Метод освобождения экземпляра синглетона TExcludedTestsFolders } begin l3Free(g_TExcludedTestsFolders); end;//TExcludedTestsFoldersFree class function TExcludedTestsFolders.Exists: Boolean; begin Result := g_TExcludedTestsFolders <> nil; end;//TExcludedTestsFolders.Exists class function TExcludedTestsFolders.Instance: TExcludedTestsFolders; {* Метод получения экземпляра синглетона TExcludedTestsFolders } begin if (g_TExcludedTestsFolders = nil) then begin l3System.AddExitProc(TExcludedTestsFoldersFree); g_TExcludedTestsFolders := Create; end; Result := g_TExcludedTestsFolders; end;//TExcludedTestsFolders.Instance {$IfEnd} // Defined(nsTest) AND NOT Defined(NotTunedDUnit) end.
unit FrameHelper; interface uses Classes; type TFrameHelper = class(TComponent) private FOnDestroy: TNotifyEvent; FOnCreate: TNotifyEvent; procedure SetOnCreate(const Value: TNotifyEvent); procedure SetOnDestroy(const Value: TNotifyEvent); protected procedure Loaded; override; public procedure BeforeDestruction; override; published property OnCreate : TNotifyEvent read FOnCreate write SetOnCreate; property OnDestroy : TNotifyEvent read FOnDestroy write SetOnDestroy; end; implementation uses Threading; { TFrameHelper } procedure TFrameHelper.Loaded; begin inherited; TTask.Run(procedure begin TThread.Queue(TThread.Current,procedure begin if Assigned(FOnCreate) and not (csDesigning in ComponentState) then FOnCreate(self); end); end); end; procedure TFrameHelper.BeforeDestruction; begin if Assigned(FOnDestroy)and not (csDesigning in ComponentState) then FOnDestroy(self); inherited; end; procedure TFrameHelper.SetOnCreate(const Value: TNotifyEvent); begin FOnCreate := Value; end; procedure TFrameHelper.SetOnDestroy(const Value: TNotifyEvent); begin FOnDestroy := Value; end; end.
unit K365824453; {* [Requestlink:365824453] } // Модуль: "w:\archi\source\projects\Archi\Tests\K365824453.pas" // Стереотип: "TestCase" // Элемент модели: "TK365824453" MUID: (4FC4B03C0085) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3IntfUses {$If NOT Defined(NoScripts)} , ArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ; type TK365824453 = class({$If NOT Defined(NoScripts)} TArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ) {* [Requestlink:365824453] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK365824453 {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) implementation {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3ImplUses , TestFrameWork //#UC START# *4FC4B03C0085impl_uses* //#UC END# *4FC4B03C0085impl_uses* ; {$If NOT Defined(NoScripts)} function TK365824453.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'TableBoundariesAlignment'; end;//TK365824453.GetFolder function TK365824453.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4FC4B03C0085'; end;//TK365824453.GetModelElementGUID initialization TestFramework.RegisterTest(TK365824453.Suite); {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) end.
unit fmuEJReports; interface uses // VCL Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, // This untPages, untDriver, ComCtrls, Spin; type { TfmEKLZReportInSessionsRange } TfmEJReports = class(TPage) Memo: TMemo; btnGetEKLZDepartmentReportInSessionsRange: TBitBtn; btnStop: TBitBtn; btnGetEKLZSessionReportInSessionsRange: TBitBtn; btnGetEKLZDepartmentReportInDatesRange: TBitBtn; btnGetEKLZSessionReportInDatesRange: TBitBtn; lblReportType: TLabel; lblDepartment: TLabel; lblFirstSessionNumber: TLabel; lblLastSessionNumber: TLabel; lblStartDate: TLabel; dtpFirstSessionDate: TDateTimePicker; lblEndDate: TLabel; dtpLastSessionDate: TDateTimePicker; cbReportType: TComboBox; seDepartment: TSpinEdit; seFirstSessionNumber: TSpinEdit; seLastSessionNumber: TSpinEdit; procedure btnGetEKLZDepartmentReportInSessionsRangeClick(Sender: TObject); procedure btnGetEKLZSessionReportInSessionsRangeClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnGetEKLZDepartmentReportInDatesRangeClick(Sender: TObject); procedure btnGetEKLZSessionReportInDatesRangeClick(Sender: TObject); private FStopFlag: Boolean; procedure GetEKLZData; procedure Check2(ResultCode: Integer); end; implementation {$R *.DFM} { TfmEKLZReportInSessionsRange } procedure TfmEJReports.btnGetEKLZDepartmentReportInSessionsRangeClick(Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.ReportType := cbReportType.ItemIndex > 0; Driver.Department := seDepartment.Value; Driver.FirstSessionNumber := seFirstSessionNumber.Value; Driver.LastSessionNumber := seLastSessionNumber.Value; Check(Driver.GetEKLZDepartmentReportInSessionsRange); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmEJReports.btnGetEKLZSessionReportInSessionsRangeClick( Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.ReportType := cbReportType.ItemIndex > 0; Driver.FirstSessionNumber := seFirstSessionNumber.Value; Driver.LastSessionNumber := seLastSessionNumber.Value; Check(Driver.GetEKLZSessionReportInSessionsRange); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; /////////////////////////////////////////////////////////////////////////////// // Некоторый эксперт написал что неправильно выдавать ошибку // Хорошо, ошибка будет просто очищаться в драйвере procedure TfmEJReports.Check2(ResultCode: Integer); begin if ResultCode <> 0 then begin if ResultCode = $A9 then Driver.ClearResult; Abort; end; end; procedure TfmEJReports.GetEKLZData; begin Memo.Lines.Add(''); Memo.Lines.Add(' Тип ККМ: ' + Driver.UDescription); Memo.Lines.Add(''); repeat Check2(Driver.GetEKLZData); Memo.Lines.Add(' ' + Driver.EKLZData); Application.ProcessMessages; until FStopFlag; Driver.EKLZInterrupt; end; procedure TfmEJReports.btnGetEKLZDepartmentReportInDatesRangeClick( Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.ReportType := cbReportType.ItemIndex > 0; Driver.Department := seDepartment.Value; Driver.FirstSessionDate := dtpFirstSessionDate.Date; Driver.LastSessionDate := dtpLastSessionDate.Date; Check(Driver.GetEKLZDepartmentReportInDatesRange); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmEJReports.btnGetEKLZSessionReportInDatesRangeClick( Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.ReportType := cbReportType.ItemIndex > 0; Driver.FirstSessionDate := dtpFirstSessionDate.Date; Driver.LastSessionDate := dtpLastSessionDate.Date; Check(Driver.GetEKLZSessionReportInDatesRange); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmEJReports.btnStopClick(Sender: TObject); begin FStopFlag := True; end; end.
unit osCustomDataSetProvider; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Provider, db, dbclient, variants; type TBeforeOSGetRecordsEvent = procedure(Count: Integer; Options: Integer; const CommandText: WideString; Params: TParams; var vParams, OwnerData: OleVariant) of object; TosCustomDatasetProvider = class(TDataSetProvider) private FParams: TParams; FBeforeOSGetRecords: TBeforeOSGetRecordsEvent; protected {** Executa a query informada através da interface IProviderSupport } procedure DoGetValues(SQL: TStringList; Params: TParams; DataSet: TPacketDataSet); {** Implementa o método interno (DataRequest) GET_VIEWS } function GetViews(const PUserID, PName: string): OleVariant; procedure DoBeforeGetRecords(Count: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant); override; procedure DoGetTableName(DataSet: TDataSet; var TableName: string); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {** Métodos customizados internos chamados pelo ClientDataset } function DataRequest(Input: OleVariant): OleVariant; override; {** Define o método interno (DataRequest) GET_OIDHIGH } function GetIDHigh(const PSeqName: string = 'Geral'): OleVariant; virtual; abstract; published property BeforeOSGetRecords: TBeforeOSGetRecordsEvent read FBeforeOSGetRecords write FBeforeOSGetRecords; end; implementation { TccDataSetProvider } constructor TosCustomDatasetProvider.Create(AOwner: TComponent); begin inherited; Options := Options + [poNoReset]; //poIncFieldProps, poNoReset; end; function TosCustomDatasetProvider.DataRequest(Input: OleVariant): OleVariant; var sCmd, sUID, sName: string; begin if (VarType(Input) = varOleStr) then begin sCmd := Input; if Copy(sCmd, 1, 5) = '_CMD=' then // Se for um comando customizado então executa begin sCmd := Copy(sCmd, 6, Length(sCmd) - 5); // obtém o nome do comando if sCmd = 'GET_IDHIGH' then // Obter um OIDHigh para ser utilizado no client Result := GetIDHigh else if Copy(sCmd, 1, 9) = 'GET_VIEWS' then // Obter um lista de views begin sUID := Copy(sCmd, Pos('UID=', sCmd) + 4, Pos('CLASSNAME=', sCmd) + 3); sName := Copy(sCmd, Pos('CLASSNAME=', sCmd) + 10, 40); Result := GetViews(sUID, sName); end; end; end else if (VarType(Input) = 8204) then // ?? begin if Input[0] = '_CMD' then // Se for um comando customizado então executa begin sCmd := Input[1]; if sCmd = 'GET_IDHIGH' then // Obter um OIDHigh para ser utilizado no client Result := GetIDHigh(Input[2]) else if sCmd = 'GET_VIEWS' then // Obter um lista de views Result := GetViews(Input[2], Input[3]); end; end else if VarType(Result) = varEmpty then Result := inherited DataRequest(Input); end; destructor TosCustomDatasetProvider.Destroy; begin if Assigned(FParams) then FParams.Free; inherited; end; procedure TosCustomDatasetProvider.DoGetValues(SQL: TStringList; Params: TParams; DataSet: TPacketDataSet); var DS: TDataSet; TempProvider: TDatasetProvider; begin DS := nil; IProviderSupport(Self.DataSet).PSExecuteStatement(SQL.Text, Params, @DS); if Assigned(DS) then begin TempProvider := TDataSetProvider.Create(Self); Try TempProvider.DataSet := DS; Dataset.Data := TempProvider.Data; finally TempProvider.Free; DS.Free; end; end; end; function TosCustomDatasetProvider.GetViews(const PUserID, PName: string): OleVariant; var ViewsDataset: TPacketDataset; SQL: TStringList; iUpperBound, i: integer; Params: TParams; begin ViewsDataset := TPacketDataset.Create(Self); SQL := TStringList.Create; Params := TParams.Create(Self); try with SQL do begin Add('SELECT'); Add(' D.Number,'); Add(' D.Description,'); Add(' D.AttributeList,'); Add(' D.ExpressionList,'); Add(' D.ConstraintList,'); Add(' D.OrderList,'); Add(' D.QueryText,'); Add(' D.OrderColumn,'); Add(' D.OrderType'); Add('FROM XFilterDef F, XFilterDefDetail D'); Add('WHERE'); Add(' F.IDXFilterDef = D.IDXFilterDef and'); Add(' F.Name = ' + QuotedStr(PName)); Add('ORDER BY'); Add(' D.Number'); end; DoGetValues(SQL, Params, ViewsDataset); with ViewsDataset do begin if EOF then iUpperBound := 0 else iUpperBound := RecordCount - 1; Result := VarArrayCreate([0, iUpperBound], varVariant); i := 0; while not EOF do begin Result[i] := VarArrayOf([FieldByName('Description').AsString, FieldByName('QueryText').AsString, FieldByName('AttributeList').AsString, FieldByName('ExpressionList').AsString, FieldByName('ConstraintList').AsString, FieldByName('OrderList').AsString, FieldByName('Number').AsString, FieldByName('OrderColumn').AsString, FieldByName('OrderType').AsString]); Inc(i); Next; end; Close; end; finally ViewsDataset.Free; Params.Free; SQL.Free; end; end; procedure TosCustomDatasetProvider.DoBeforeGetRecords(Count, Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant); begin if Assigned(BeforeOSGetRecords) then begin if not Assigned(FParams) then FParams := TParams.Create; FParams.Clear; UnpackParams(Params, FParams); BeforeOSGetRecords(Count, Options, CommandText, FParams, Params, OwnerData); end; inherited; end; {-------------------------------------------------------------------------  Objetivo   > Transformar o TableName em UpperCase por que no dialect 3 da erro por falta de case sensitivity.  Parâmetros > Conforme documentação  Retorno    >  Criação    > 23.03.2006 - Ricardo N. Acras  Observações>  Atualização>  ------------------------------------------------------------------------} procedure TosCustomDatasetProvider.DoGetTableName(DataSet: TDataSet; var TableName: string); begin inherited DoGetTableName(DataSet, TableName); TableName := upperCase(TableName); end; end.
unit G2Mobile.Model.ExportarPedidos; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, uFrmUtilFormate, Form_Mensagem, G2Mobile.Controller.Pedidos; const CONST_DELETEITEMATUALIZADO = ' DELETE FROM itens_atualizado'; CONST_BUSCAATUALIZACAOPEDIDOS = ' select ti.cod_pedcar, ti.cod_prod, ti.chave, tpv.valor_final, tpv.status, tcp.motivo, ' + ' isnull(sum(th.qtd_tot), 0) as qtd_tot, isnull(sum(th.pes_tot), 0) as pes_tot, ' + ' isnull(sum(round(convert(numeric(14, 4), isnull(case tpr.tipo_calc when 0 then th.pes_tot when 1 then th.qtd_tot end, 0)*(ti.preco_unit-ti.desconto)), 2)), 0) as vlr_tot, ' + ' isnull(sum(ti.quantidade), 0) as qtd_ped ' + ' from t_pedidovenda tp left outer join v_pessoa tc on (tp.cod_cliente = tc.cod_pessoa) left outer join v_prestador ts on (tp.cod_prest = ts.cod_prest) ' + ' left outer join t_centro_custo tu on (tp.cod_cc = tu.cod_cc) left outer join t_vendedor tv on (tp.cod_vend = tv.cod_vend), ' + ' t_pedidovendaitens ti ' + ' left outer join t_pedido_cancel tcp on (ti.cod_pedcar = tcp.cod_pedcar) ' + ' left outer join t_pedidovenda tpv on (tpv.cod_pedcar = ti.cod_pedcar) ' + ' left outer join t_produto tpr on (tpr.cod_prod = ti.cod_prod) ' + ' left outer join t_materia_prima tmp on (tmp.cod_materia = tpr.mat_prima) ' + ' left outer join (select tt.cod_pedcar, tt.num_item, isnull(count(tt.cod_pedcar), 0)+isnull(sum(tm.quant)-count(tm.item_pes), 0) as qtd_tot, isnull(sum(tt.peso), 0) as pes_tot from t_tendal tt ' + ' left outer join t_tendal_multi tm on (tt.cod_pedcar = tm.cod_pedcar and tt.num_item = tm.num_item and tt.item_pes = tm.item_pes) group by tt.cod_pedcar, tt.num_item) th on (th.cod_pedcar = ti.cod_pedcar and th.num_item = ti.num_item) ' + ' where tp.cod_pedcar = ti.cod_pedcar ' + ' and ti.chave in( '; CONST_PEDIDOSSINCRONIZADOS = 'select chave from venda where sincronizado = 1'; CONST_INSERTPEDIDOATUALIZADO = ' INSERT INTO itens_atualizado (chave, cod_pedcar, cod_prod, qtd_ped, qtd_tot, pes_tot, vlr_tot, valor_final, motivo, status) VALUES ' + ' (:chave, :cod_pedcar, :cod_prod, :qtd_ped, :qtd_tot, :pes_tot, :vlr_tot, :valor_final, :motivo, :status) '; type TModelExportPedido = class(TInterfacedObject, iModelExportarPedidos) private FQry: TFDQuery; FRdwSQLTemp: TRESTDWClientSQL; FString: String; public constructor create; destructor destroy; override; class function new: iModelExportarPedidos; function DeleteItemAtualizado: iModelExportarPedidos; function BuscaInfoAtualizadaServidor(DataSet: TFDMemTable): iModelExportarPedidos; function GravaInfoAtulizadoPedidoSqlite(DataSet: TFDMemTable): iModelExportarPedidos; function VerificaPedidosSincronizadosSqlite: iModelExportarPedidos; end; implementation { TParametros } class function TModelExportPedido.new: iModelExportarPedidos; begin result := self.create; end; constructor TModelExportPedido.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQLTemp := TRESTDWClientSQL.create(nil); FRdwSQLTemp.DataBase := DmDados.RESTDWDataBase1; FRdwSQLTemp.BinaryRequest := True; FRdwSQLTemp.FormatOptions.MaxStringSize := 10000; FRdwSQLTemp.Active := false; FRdwSQLTemp.SQL.Clear; end; destructor TModelExportPedido.destroy; begin FreeAndNil(FQry); FreeAndNil(FRdwSQLTemp); inherited; end; function TModelExportPedido.DeleteItemAtualizado: iModelExportarPedidos; begin result := self; FQry.ExecSQL(CONST_DELETEITEMATUALIZADO); end; function TModelExportPedido.VerificaPedidosSincronizadosSqlite: iModelExportarPedidos; var I: Integer; begin result := self; FString := EmptyStr; FQry.Open(CONST_PEDIDOSSINCRONIZADOS); if FQry.IsEmpty then begin FString := QuotedStr('') + ' )'; end else begin for I := 0 to FQry.RecordCount - 1 do begin FString := FString + QuotedStr(FQry.FieldByName('chave').AsString); if I <> FQry.RecordCount - 1 then FString := FString + ', '; FQry.Next; end; FString := FString + ' )'; end; end; function TModelExportPedido.BuscaInfoAtualizadaServidor(DataSet: TFDMemTable): iModelExportarPedidos; begin result := self; FRdwSQLTemp.SQL.Text := CONST_BUSCAATUALIZACAOPEDIDOS + FString + ' group by ti.cod_prod, tpr.desc_ind, tpr.tipo_calc, tpv.status, tpv.valor_final,ti.cod_pedcar,ti.chave, tcp.motivo ' + ' order by tpr.desc_ind '; FRdwSQLTemp.Active := True; FRdwSQLTemp.RecordCount; DataSet.CopyDataSet(FRdwSQLTemp, [coStructure, coRestart, coAppend]); end; function TModelExportPedido.GravaInfoAtulizadoPedidoSqlite(DataSet: TFDMemTable): iModelExportarPedidos; var I: Integer; begin result := self; DataSet.First; FQry.Active := false; for I := 0 to DataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTPEDIDOATUALIZADO; FQry.ParamByName('chave').AsString := DataSet.FieldByName('chave').AsString; FQry.ParamByName('cod_pedcar').AsInteger := DataSet.FieldByName('cod_pedcar').AsInteger; FQry.ParamByName('cod_prod').AsInteger := DataSet.FieldByName('cod_prod').AsInteger; FQry.ParamByName('qtd_ped').AsFloat := DataSet.FieldByName('qtd_ped').AsFloat; FQry.ParamByName('qtd_tot').AsFloat := DataSet.FieldByName('qtd_tot').AsFloat; FQry.ParamByName('pes_tot').AsFloat := DataSet.FieldByName('pes_tot').AsFloat; FQry.ParamByName('vlr_tot').AsFloat := DataSet.FieldByName('vlr_tot').AsFloat; FQry.ParamByName('valor_final').AsFloat := DataSet.FieldByName('valor_final').AsFloat; FQry.ParamByName('motivo').AsString := DataSet.FieldByName('motivo').AsString; FQry.ParamByName('status').AsInteger := DataSet.FieldByName('status').AsInteger; FQry.ExecSQL; DataSet.Next; end; end; end.
unit uReceiveData; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Memo, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, System.SyncObjs; type TfrmHRMDataReceiver = class(TForm) Header: TToolBar; Footer: TToolBar; HeaderLabel: TLabel; FooterLabel: TLabel; Image1: TImage; SpeedButton1: TSpeedButton; Memo1: TMemo; TetherManagerHRM: TTetheringManager; TetherProfileHRM: TTetheringAppProfile; Label1: TLabel; Memo2: TMemo; Label2: TLabel; tmCheckConnection: TTimer; procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure TetherManagerHRMRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetherManagerHRMEndManagersDiscovery(const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); procedure TetherManagerHRMEndProfilesDiscovery(const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); procedure TetherProfileHRMResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure TetherManagerHRMPairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetherManagerHRMPairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetherManagerHRMRemoteManagerShutdown(const Sender: TObject; const AManagerIdentifier: string); procedure TetherManagerHRMNewManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetherManagerHRMUnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetherProfileHRMResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); procedure RefreshBPMList; procedure TetherProfileHRMDisconnect(const Sender: TObject; const AProfileInfo: TTetheringProfileInfo); private { Private declarations } //App Tethering Shared Resource FMyBPM: String; FLock: TCriticalSection; FRemoteProfiles: TTetheringProfileInfoList; procedure Lock; procedure Unlock; public { Public declarations } end; var frmHRMDataReceiver: TfrmHRMDataReceiver; implementation {$R *.fmx} procedure TfrmHRMDataReceiver.Lock; begin FLock.Acquire; end; procedure TfrmHRMDataReceiver.Unlock; begin FLock.Release; end; procedure TfrmHRMDataReceiver.FormCreate(Sender: TObject); begin // Assign a default value to the "Username" Resource TetherProfileHRM.Resources.FindByName('MyBPM').Value := 'Waiting for BPM...'; // Create the Remote Profile Lock FLock := TCriticalSection.Create; // Create the Remote Profiles List FRemoteProfiles := TTetheringProfileInfoList.Create; // Log the unique LOCAL identifier so we can distinguish between instances // This is a unique GUID generated when our application is executed Memo1.Lines.Add('Local Identifier: ' + TetherManagerHRM.Identifier); end; procedure TfrmHRMDataReceiver.SpeedButton1Click(Sender: TObject); begin FooterLabel.Text := 'Looking for Heart Rate Monitor...'; // AT: Log the unique GUID HR Monitor identifier when app starts Memo1.Lines.Add('GUID Identifier: ' + TetherManagerHRM.Identifier); // The Local Manager scans for Remote Managers. Memo1.Lines.Add('Scanning for Remote Managers to pair with...'); TetherManagerHRM.DiscoverManagers(2000); end; procedure TfrmHRMDataReceiver.TetherManagerHRMEndManagersDiscovery( const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); var I: Integer; begin // Output the number of Remote Managers into the Memo. // Handle pairing with Remote Managers Memo1.Lines.Add(Format('Manager Discovery Complete, found %d Remote Managers', [ARemoteManagers.Count])); // Iterate through all of the discovered Remote Managers, // Check if its Text properties matches that of the Local Manager. // If it matches, the Local Manager pairs with it; if not, // we acknowledge its existence in the log and move on. for I := 0 to ARemoteManagers.Count - 1 do begin // Log information about the Remote Manager Memo1.Lines.Add(Format('Discovered Remote Manager %d - %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [I, ARemoteManagers[I].ManagerIdentifier, ARemoteManagers[I].ManagerName, ARemoteManagers[I].ManagerText, ARemoteManagers[I].ConnectionString])); // Check if the Remote Manager's "Text" matches the Local Manager's if (ARemoteManagers[I].ManagerText = TetherManagerHRM.Text) then begin // Log that we're attempting to pair with this Remote Manager Memo1.Lines.Add('Remote Manager matches Local Manger, attempting to pair...'); FooterLabel.Text := 'Connected to HRM: '+ TetherManagerHRM.Text; // Pair with the Remote Manager TetherManagerHRM.PairManager(ARemoteManagers[I]); end else begin // Log that this Remote Manager is of no interest Memo1.Lines.Add('Remote Manager does not match Local Manager, ignoring it...'); end; end; // Once the Local Manager pairs with a Remote Manager, // the Profile Discovery process automatically takes place on both sides. end; procedure TfrmHRMDataReceiver.TetherManagerHRMEndProfilesDiscovery( const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); var LRemoteProfile: TTetheringProfileInfo; begin Memo1.Lines.Add(Format('Profile Discovery Complete, Found %d Remote Profiles', [ARemoteProfiles.Count])); // Lock the container Lock; try // Iterate all discovered profiles for LRemoteProfile in ARemoteProfiles do begin // If the profile isn't already in the list... if (not FRemoteProfiles.Contains(LRemoteProfile)) then begin // If we can connect to the Remote Profile if TetherProfileHRM.Connect(LRemoteProfile) then begin //We need to Subscribe to each Remote Profile‘s BPM resource. //This will enable the OnResourceUpdated event to update the BPM value. //Each time a Remote Profile changes the value of its BPM resource, //our Local Profile‘s OnResourceUpdated event is automatically fired, //and that refreshes the BPM value. TetherProfileHRM.SubscribeToRemoteItem(LRemoteProfile, TetherProfileHRM.GetRemoteResourceValue(LRemoteProfile, 'MyBPM')); // Add it into our lockable container FRemoteProfiles.Add(LRemoteProfile); // Log the Remote Profile Memo1.Lines.Add(Format('Added Remote Profile %s to the Lockable List', [LRemoteProfile.ProfileIdentifier])); end; end; end; // Re-sort the lockable container FRemoteProfiles.Sort; finally // Unlock the container Unlock; end; end; procedure TfrmHRMDataReceiver.TetherManagerHRMNewManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log new Remote Manager discovered. Memo1.Lines.Add(Format('New Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHRMDataReceiver.TetherManagerHRMPairedFromLocal( const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log we've paired to a Remote Manager Memo1.Lines.Add(Format('A Remote Manager %s has paired with us' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHRMDataReceiver.TetherManagerHRMPairedToRemote( const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log pairing with a Remote Manager initiated from our Local Manager. Memo1.Lines.Add(Format('We have paired with a Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHRMDataReceiver.TetherManagerHRMRemoteManagerShutdown( const Sender: TObject; const AManagerIdentifier: string); begin // Logs the identity of a Remote Manager that has shut down. Memo1.Lines.Add(Format('Remote Manager %s Shutdown', [AManagerIdentifier])); end; procedure TfrmHRMDataReceiver.TetherManagerHRMRequestManagerPassword( const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin TThread.Synchronize(TThread.CurrentThread, procedure begin Memo1.Lines.Add(Format('Remote Manager %s needs the password...', [ARemoteIdentifier])); end); Password := '1234'; end; procedure TfrmHRMDataReceiver.TetherManagerHRMUnPairManager( const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log we have unpaired from a Remote Manager. Memo1.Lines.Add(Format('UnPaired with Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHRMDataReceiver.TetherProfileHRMDisconnect(const Sender: TObject; const AProfileInfo: TTetheringProfileInfo); var LIndex: Integer; LProfileInfo: TTetheringProFileInfo; begin // Engage the Lock Lock; try // If the Profile is in the list... if FRemoteProfiles.BinarySearch(AProfileInfo, LIndex) then begin // ...remove it FRemoteProfiles.Delete(LIndex); // Log that we've removed it LProfileInfo := AProfileInfo; TThread.Synchronize(TThread.CurrentThread, procedure begin Memo2.Lines.Add(Format('Removed Remote Profile %s from the lockable container', [LProfileInfo.ProfileIdentifier])); end); end; finally // Disengage the Lock Unlock; end; end; procedure TfrmHRMDataReceiver.TetherProfileHRMResourceReceived( const Sender: TObject; const AResource: TRemoteResource); begin Memo1.Lines.Add(Format('Temporary Resource Received: %s', [AResource.Hint])); // if it's a String resource... if (AResource.Hint = 'BPM') and (AResource.Value.DataType = TResourceType.String) then begin // Add the message to the display Memo2.Lines.Add(AResource.Value.AsString); end; end; procedure TfrmHRMDataReceiver.TetherProfileHRMResourceUpdated( const Sender: TObject; const AResource: TRemoteResource); begin // Log that a Remote Resource has been updated Memo1.Lines.Add(Format('Remote Resource Updated: %s', [AResource.Name])); // if this is the MyBPM resource... if AResource.Name = 'MyBPM' then RefreshBPMList; // ...Refresh the BPM list end; procedure TfrmHRMDataReceiver.RefreshBPMList; var LRemoteProfile: TTetheringProfileInfo; LRemoteBPM: String; begin // Lock the container Lock; try // Iterate all Connected Remote Profiles for LRemoteProfile in FRemoteProfiles do begin // Retreive the BPM LRemoteBPM := TetherProfileHRM.GetRemoteResourceValue( LRemoteProfile, 'MyBPM').Value.AsString; // If the BPM has been specified if LRemoteBPM <> 'Waiting for BPM...' then begin // Add the BPM to the list // lbBPM.Items.Add(LRemoteBPM); end; end; // Unlock the container finally Unlock; end; end; end.
unit uSettingApp; interface uses uModel, System.SysUtils, uUser; type TSettingApp = class(TAppObject) private FCabang: TCabang; FGudangPenjualan: tgudang; FGudangTransit: tgudang; FMaxBelanjaSantri: Double; procedure SetCabang(const Value: TCabang); procedure SetGudangPenjualan(const Value: tgudang); procedure SetGudangTransit(const Value: tgudang); published property Cabang: TCabang read FCabang write SetCabang; property GudangPenjualan: tgudang read FGudangPenjualan write SetGudangPenjualan; property GudangTransit: tgudang read FGudangTransit write SetGudangTransit; property MaxBelanjaSantri: Double read FMaxBelanjaSantri write FMaxBelanjaSantri; end; var UserApplikasi : TUser; implementation procedure TSettingApp.SetCabang(const Value: TCabang); begin FreeAndNil(FCabang); FCabang := Value; end; procedure TSettingApp.SetGudangPenjualan(const Value: tgudang); begin FreeAndNil(FGudangPenjualan); FGudangPenjualan := Value; end; procedure TSettingApp.SetGudangTransit(const Value: tgudang); begin FreeAndNil(FGudangTransit); FGudangTransit := Value; end; end.
unit TTSACCESSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSACCESSRecord = record PLenderNum: String[4]; PUserName: String[10]; PModCount: Integer; PRights: String[7]; PRightRank: String[1]; End; TTTSACCESSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSACCESSRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSACCESS = (TTSACCESSPrimaryKey, TTSACCESSByAccess); TTTSACCESSTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFUserName: TStringField; FDFModCount: TIntegerField; FDFRights: TStringField; FDFRightRank: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPUserName(const Value: String); function GetPUserName:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPRights(const Value: String); function GetPRights:String; procedure SetPRightRank(const Value: String); function GetPRightRank:String; procedure SetEnumIndex(Value: TEITTSACCESS); function GetEnumIndex: TEITTSACCESS; protected procedure CreateFields; override; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSACCESSRecord; procedure StoreDataBuffer(ABuffer:TTTSACCESSRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFUserName: TStringField read FDFUserName; property DFModCount: TIntegerField read FDFModCount; property DFRights: TStringField read FDFRights; property DFRightRank: TStringField read FDFRightRank; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PUserName: String read GetPUserName write SetPUserName; property PModCount: Integer read GetPModCount write SetPModCount; property PRights: String read GetPRights write SetPRights; property PRightRank: String read GetPRightRank write SetPRightRank; published property Active write SetActive; property EnumIndex: TEITTSACCESS read GetEnumIndex write SetEnumIndex; end; { TTTSACCESSTable } procedure Register; implementation procedure TTTSACCESSTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFUserName := CreateField( 'UserName' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFRights := CreateField( 'Rights' ) as TStringField; FDFRightRank := CreateField( 'RightRank' ) as TStringField; end; { TTTSACCESSTable.CreateFields } procedure TTTSACCESSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSACCESSTable.SetActive } procedure TTTSACCESSTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSACCESSTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSACCESSTable.SetPUserName(const Value: String); begin DFUserName.Value := Value; end; function TTTSACCESSTable.GetPUserName:String; begin result := DFUserName.Value; end; procedure TTTSACCESSTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSACCESSTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSACCESSTable.SetPRights(const Value: String); begin DFRights.Value := Value; end; function TTTSACCESSTable.GetPRights:String; begin result := DFRights.Value; end; procedure TTTSACCESSTable.SetPRightRank(const Value: String); begin DFRightRank.Value := Value; end; function TTTSACCESSTable.GetPRightRank:String; begin result := DFRightRank.Value; end; procedure TTTSACCESSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('UserName, String, 10, N'); Add('ModCount, Integer, 0, N'); Add('Rights, String, 7, N'); Add('RightRank, String, 1, N'); end; end; procedure TTTSACCESSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;UserName, Y, Y, N, N'); Add('ByAccess, LenderNum;RightRank;UserName, N, N, Y, N'); end; end; procedure TTTSACCESSTable.SetEnumIndex(Value: TEITTSACCESS); begin case Value of TTSACCESSPrimaryKey : IndexName := ''; TTSACCESSByAccess : IndexName := 'ByAccess'; end; end; function TTTSACCESSTable.GetDataBuffer:TTTSACCESSRecord; var buf: TTTSACCESSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PUserName := DFUserName.Value; buf.PModCount := DFModCount.Value; buf.PRights := DFRights.Value; buf.PRightRank := DFRightRank.Value; result := buf; end; procedure TTTSACCESSTable.StoreDataBuffer(ABuffer:TTTSACCESSRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFUserName.Value := ABuffer.PUserName; DFModCount.Value := ABuffer.PModCount; DFRights.Value := ABuffer.PRights; DFRightRank.Value := ABuffer.PRightRank; end; function TTTSACCESSTable.GetEnumIndex: TEITTSACCESS; var iname : string; begin result := TTSACCESSPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSACCESSPrimaryKey; if iname = 'BYACCESS' then result := TTSACCESSByAccess; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSACCESSTable, TTTSACCESSBuffer ] ); end; { Register } function TTTSACCESSBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('LENDERNUM','USERNAME','MODCOUNT','RIGHTS','RIGHTRANK' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TTTSACCESSBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftString; end; end; function TTTSACCESSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PUserName; 3 : result := @Data.PModCount; 4 : result := @Data.PRights; 5 : result := @Data.PRightRank; end; end; end.
unit UDemo; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX.TMSXUtil, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, FMX.Edit, FMX.ListBox, FMX.ExtCtrls, FMX.Colors, FMX.Menus, FMX.TMSGridCell, FMX.TMSCustomGrid, FMX.StdCtrls, IOUtils; type TForm719 = class(TForm) TMSFMXGrid1: TTMSFMXGrid; Panel1: TPanel; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure TMSFMXGrid1CellEditSetData(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject; var CellString: string); procedure TMSFMXGrid1GetCellClass(Sender: TObject; ACol, ARow: Integer; var CellClassType: TFmxObjectClass); procedure TMSFMXGrid1GetCellEditorProperties(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject); procedure TMSFMXGrid1GetCellEditorType(Sender: TObject; ACol, ARow: Integer; var CellEditorType: TTMSFMXGridEditorType); procedure TMSFMXGrid1GetCellEditorCustomClassType(Sender: TObject; ACol, ARow: Integer; var CellEditorCustomClassType: TFmxObjectClass); procedure TMSFMXGrid1CellEditGetData(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject; var CellString: string); private { Private declarations } public { Public declarations } end; var Form719: TForm719; implementation {$R *.fmx} procedure TForm719.FormCreate(Sender: TObject); var I: Integer; begin TMSFMXGrid1.IOOffset := Point(1, 1); TMSFMXGrid1.LoadFromCSV(GetHomePath + '/CARS.CSV'); TMSFMXGrid1.DefaultColumnWidth := 100; TMSFMXGrid1.DefaultRowHeight := 30; TMSFMXGrid1.Cells[1, 0] := 'ComboBox'; TMSFMXGrid1.Cells[2, 0] := 'Edit'; TMSFMXGrid1.Cells[3, 0] := 'TrackBar'; TMSFMXGrid1.Cells[4, 0] := 'DatePicker'; TMSFMXGrid1.Cells[5, 0] := 'ArcDial'; TMSFMXGrid1.Cells[6, 0] := 'ColorPicker'; TMSFMXGrid1.Cells[7, 0] := 'Switch'; TMSFMXGrid1.Cells[8, 0] := 'Pasword'; TMSFMXGrid1.CellComboBox.Items.Add('Mercedes'); TMSFMXGrid1.CellComboBox.Items.Add('Audi'); TMSFMXGrid1.CellComboBox.Items.Add('Bugatti'); TMSFMXGrid1.CellComboBox.Items.Add('Alfa Romeo'); TMSFMXGrid1.CellComboBox.Items.Add('Jaguar'); TMSFMXGrid1.CellComboBox.Items.Add('BMW'); TMSFMXGrid1.AutoNumberCol(0); for I := 1 to TMSFMXGrid1.RowCount - 1 do begin TMSFMXGrid1.Cells[7, I] := '0'; TMSFMXGrid1.Cells[4, I] := DateToStr(Now - 100 + Random(200)); end; TMSFMXGrid1.Cells[7, 2] := '1'; TMSFMXGrid1.Cells[7, 5] := '1'; TMSFMXGrid1.Cells[7, 7] := '1'; TMSFMXGrid1.Cells[7, 10] := '1'; TMSFMXGrid1.SetFocus; end; procedure TForm719.TMSFMXGrid1CellEditGetData(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject; var CellString: string); begin if CellEditor is TSwitch then (CellEditor as TSwitch).IsChecked := StrToBool(TMSFMXGrid1.Cells[ACol, ARow]); end; procedure TForm719.TMSFMXGrid1CellEditSetData(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject; var CellString: string); begin case ACol of 3: CellString := floattostr((CellEditor as TTrackBar).Value); 4: CellString := DateToStr((CellEditor as TCellCalendarBox).Date); 5: CellString := floattostr((CellEditor as TArcDial).Value); 6: TMSFMXGrid1.Colors[ACol, ARow] := (CellEditor as TColorComboBox).Color; 7: begin if (CellEditor as TSwitch).IsChecked then CellString := '1' else CellString := '0'; end; end; end; procedure TForm719.TMSFMXGrid1GetCellClass(Sender: TObject; ACol, ARow: Integer; var CellClassType: TFmxObjectClass); begin if ARow = 7 then CellClassType := TTMSFMXFixedGridCell; end; procedure TForm719.TMSFMXGrid1GetCellEditorCustomClassType(Sender: TObject; ACol, ARow: Integer; var CellEditorCustomClassType: TFmxObjectClass); begin if ACol = 7 then CellEditorCustomClassType := TSwitch; end; procedure TForm719.TMSFMXGrid1GetCellEditorProperties(Sender: TObject; ACol, ARow: Integer; CellEditor: TFmxObject); begin if (CellEditor is TEdit) then (CellEditor as TEdit).Password := Acol = 8; end; procedure TForm719.TMSFMXGrid1GetCellEditorType(Sender: TObject; ACol, ARow: Integer; var CellEditorType: TTMSFMXGridEditorType); begin case ACol of 1: CellEditorType := etComboBox; 3: CellEditorType := etTrackBar; 4: CellEditorType := etDatePicker; 5: CellEditorType := etArcDial; 6: CellEditorType := etColorComboBox; 7: CellEditorType := etCustom; end; end; end.
unit Model.Lancamentos; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, System.Variants; type TLancamentos = class private FCodigo: Integer; FDescricao: String; FData: TDateTime; FCadastro: Integer; FEntregador: Integer; FTipo: String; FValor: Double; FDesconto: String; FDataDesconto: TDate; FExtrato: String; FPersistir: String; FConexao : TConexao; FAcao: TAcao; FDataCadastro: TDateTime; FReferencia: integer; FUsuario: String; FQuery: TFDQuery; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public constructor Create; property Codigo: Integer read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Data: TDateTime read FData write FData; property Cadastro: Integer read FCadastro write FCadastro; property Entregador: Integer read FEntregador write FEntregador; property Tipo: String read FTipo write FTipo; property Valor: Double read FValor write FValor; property Desconto: String read FDesconto write FDesconto; property DataDesconto: TDate read FDataDesconto write FDataDesconto; property Extrato: String read FExtrato write FExtrato; property Persistir: String read FPersistir write FPersistir; property Referencia: integer read FReferencia write FReferencia; property DataCadastro: TDateTime read FDataCadastro write FDataCadastro; property Usuario: String read FUsuario write FUsuario; property Acao: TAcao read FAcao write FAcao; property Query: TFDQuery read FQuery write FQuery; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function GetID(): Integer; function ExtratoLancamentos(aParam: Array of variant): TFDQuery; function ExtratoLancamentosEntregador(aParam: Array of variant): Boolean; function EncerraLancamentos(aParam: Array of variant): Boolean; procedure SetupClass(fdQuery: TFDQuery); end; const TABLENAME = 'tblancamentos'; SQLUPDATE = 'UPDATE ' + TABLENAME + ' SET DES_LANCAMENTO = :DES_LANCAMENTO, DAT_LANCAMENTO = :DAT_LANCAMENTO, ' + 'COD_CADASTRO = :COD_CADASTRO, COD_ENTREGADOR = :COD_ENTREGADOR, DES_TIPO = :DES_TIPO, ' + 'VAL_LANCAMENTO = :VAL_LANCAMENTO, DOM_DESCONTO = :DOM_DESCONTO, DAT_DESCONTO = :DAT_DESCONTO, ' + 'NUM_EXTRATO = :NUM_EXTRATO, DOM_PERSISTIR = :DOM_PERSISTIR, COD_REFERENCIA = :COD_REFERENCIA, ' + 'DAT_CADASTRO = :DAT_CADASTRO, NOM_USUARIO = :NOM_USUARIO WHERE COD_LANCAMENTO = :COD_LANCAMENTO;'; SQLINSERT = 'INSERT INTO ' + TABLENAME + '(COD_LANCAMENTO, DES_LANCAMENTO, DAT_LANCAMENTO, COD_CADASTRO, ' + 'COD_ENTREGADOR, DES_TIPO, VAL_LANCAMENTO, DOM_DESCONTO, DAT_DESCONTO, NUM_EXTRATO, DOM_PERSISTIR, ' + 'COD_REFERENCIA, DAT_CADASTRO, NOM_USUARIO) ' + 'VALUES ' + '(:COD_LANCAMENTO, :DES_LANCAMENTO, :DAT_LANCAMENTO, :COD_CADASTRO, :COD_ENTREGADOR, :DES_TIPO, ' + ':VAL_LANCAMENTO, :DOM_DESCONTO, :DAT_DESCONTO, :NUM_EXTRATO, :DOM_PERSISTIR, :COD_REFERENCIA, ' + ':DAT_CADASTRO, :NOM_USUARIO);'; SQLQUERY = 'SELECT COD_LANCAMENTO, DES_LANCAMENTO, DAT_LANCAMENTO, COD_CADASTRO, COD_ENTREGADOR, DES_TIPO, ' + 'VAL_LANCAMENTO, DOM_DESCONTO, DAT_DESCONTO, NUM_EXTRATO, DOM_PERSISTIR, COD_REFERENCIA, DAT_CADASTRO, ' + 'NOM_USUARIO FROM ' + TABLENAME; SQLEXTRATO ='select tblancamentos.cod_entregador as cod_entregador, tblancamentos.des_tipo as des_tipo, ' + 'sum(tblancamentos.val_lancamento) as val_total from ' + TABLENAME + ' where tblancamentos.dat_lancamento <= :data1 and tblancamentos.dom_desconto <> :dom ' + 'group by tblancamentos.cod_entregador, tblancamentos.des_tipo;'; SQLENCERRA ='UPDATE ' + TABLENAME + ' SET ' + 'DOM_DESCONTO = "S", DAT_DESCONTO = :DAT_DESCONTO, NUM_EXTRATO = :NUM_EXTRATO ' + 'WHERE COD_ENTREGADOR = :COD_ENTREGADOR AND DAT_LANCAMENTO <= :DAT_LANCAMENTO AND DOM_DESCONTO <> "S" '+ 'AND DOM_PERSISTIR <> "S";'; implementation { TLancamentos } function TLancamentos.Alterar: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE,[Descricao, Data, Cadastro, Entregador ,Tipo, Valor, Desconto, DataDesconto, Extrato, Persistir, Referencia, DataCadastro, Usuario, Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TLancamentos.Create; begin FConexao := TConexao.Create; end; function TLancamentos.EncerraLancamentos(aParam: array of variant): Boolean; var FDQuery: TFDQuery; dtData: TDate; sExtrato: String; iEntregador : Integer; dtLancamento : TDate; sSQL :String; begin try Result := False; FDQuery := FConexao.ReturnQuery(); dtData := VarToDateTime(aParam[0]); sExtrato := VarToStr(aParam[1]); iEntregador := aParam[2]; dtLancamento := VarToDateTime(aParam[3]); sSQL :='UPDATE ' + TABLENAME + ' SET ' + 'DOM_DESCONTO = "S", DAT_DESCONTO = ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtData)) +', NUM_EXTRATO = ' + QuotedStr(sExtrato) +' WHERE COD_ENTREGADOR = ' + iEntregador.ToString + ' AND DAT_LANCAMENTO <= ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtLancamento)) +' AND DOM_DESCONTO <> "S" '+ 'AND DOM_PERSISTIR <> "S";'; FDQuery.ExecSQL(sSQL); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentos.Excluir: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' WHERE COD_LANCAMENTO = :COD_LANCAMENTO;', [Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentos.ExtratoLancamentos(aParam: array of variant): TFDQuery; var fdQuery:TFDQuery; begin fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(SQLEXTRATO); fdQuery.ParamByName('data1').AsDate := aParam[0]; fdQuery.ParamByName('dom').AsString := 'S'; FDQuery.Open(); Result := FDQuery; end; function TLancamentos.ExtratoLancamentosEntregador(aParam: array of variant): Boolean; var fdQuery:TFDQuery; begin try REsult := False; fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(SQLEXTRATO); fdQuery.ParamByName('data1').AsDate := aParam[0]; fdQuery.ParamByName('dom').AsString := 'S'; FDQuery.Open(); if fdQuery.IsEmpty then begin Exit; end; FQuery := fdQuery; Result := True; finally FDQuery.Close; fdQuery.Connection.Close; fdQuery.Free; end; end; function TLancamentos.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(COD_LANCAMENTO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentos.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Inserir(); Common.ENum.tacAlterar: Result := Alterar(); Common.ENum.tacExcluir: Result := Excluir(); end; end; function TLancamentos.Inserir: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Codigo := Self.GetID(); FDQuery.ExecSQL(SQLINSERT, [Codigo, Descricao, Data, Cadastro, Entregador ,Tipo, Valor, Desconto, DataDesconto, Extrato, Persistir, Referencia, DataCadastro, Usuario]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TLancamentos.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_LANCAMENTO = :COD_LANCAMENTO'); FDQuery.ParamByName('COD_LANCAMENTO').AsInteger := aParam[1]; end; if aParam[0] = 'REFERENCIA' then begin FDQuery.SQL.Add('WHERE COD_REFERENCIA = :COD_REFERENCIA'); FDQuery.ParamByName('COD_REFERENCIA').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('WHERE DES_LANCAMENTO LIKE :DES_LANCAMENTO'); FDQuery.ParamByName('DES_LANCAMENTO').AsString := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('WHERE DAT_LANCAMENTO = :DAT_LANCAMENTO'); FDQuery.ParamByName('WHERE DAT_LANCAMENTO').AsDate := aParam[1]; end; if aParam[0] = 'DATACADASTRO' then begin FDQuery.SQL.Add('WHERE DAT_CADASTRO = :DAT_CADASTRO'); FDQuery.ParamByName('WHERE DAT_CADASTRO').AsDate := aParam[1]; end; if aParam[0] = 'CADASTRO' then begin FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO'); FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1]; end; if aParam[0] = 'ENTREGADOR' then begin FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR'); FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1]; end; if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('WHERE NUM_EXTRATO LIKE :NUM_EXTRATO'); FDQuery.ParamByName('NUM_EXTRATO').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add(aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; if NOT FDQuery.IsEmpty then begin FDQuery.First; SetupClass(FDQuery); end; Result := FDQuery; end; procedure TLancamentos.SetupClass(fdQuery: TFDQuery); begin Self.Codigo := fdQuery.FieldByName('COD_LANCAMENTO').AsInteger; Self.Descricao := fdQuery.FieldByName('DES_LANCAMENTO').AsString; Self.Data := fdQuery.FieldByName('DAT_LANCAMENTO').AsDateTime; Self.Cadastro := fdQuery.FieldByName('COD_CADASTRO').AsInteger; Self.Entregador := fdQuery.FieldByName('COD_ENTREGADOR').AsInteger; Self.Tipo := fdQuery.FieldByName('DES_TIPO').AsString; Self.Valor := fdQuery.FieldByName('VAL_LANCAMENTO').AsFloat; Self.Desconto := fdQuery.FieldByName('DOM_DESCONTO').AsString; Self.Extrato := fdQuery.FieldByName('NUM_EXTRATO').AsString; Self.Persistir := fdQuery.FieldByName('DOM_PERSISTIR').AsString; Self.Referencia := fdQuery.FieldByName('COD_REFERENCIA').AsInteger; Self.DataDesconto := fdQuery.FieldByName('DAT_DESCONTO').AsDateTime; Self.DataCadastro := fdQuery.FieldByName('DAT_CADASTRO').AsDateTime; Self.Usuario := fdQuery.FieldByName('NOM_USUARIO').AsString; end; end.
unit Actual; interface uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Dialogs, Controls, StdCtrls, Buttons, Db, DBTables, htmlHelp; type TActualDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; HelpBtn: TButton; SrcList: TListBox; DstList: TListBox; SrcLabel: TLabel; DstLabel: TLabel; IncludeBtn: TSpeedButton; IncAllBtn: TSpeedButton; ExcludeBtn: TSpeedButton; ExAllBtn: TSpeedButton; BM: TBatchMove; TOri: TTable; TDes: TTable; lbEstado: TLabel; procedure IncludeBtnClick(Sender: TObject); procedure ExcludeBtnClick(Sender: TObject); procedure IncAllBtnClick(Sender: TObject); procedure ExcAllBtnClick(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure HelpBtnClick(Sender: TObject); private { Private declarations } nSaldo: double; sCli: string; procedure Actualizar; procedure ActualizarProve; procedure ActualizarClientes; procedure ActualizarArticulos; procedure SetearSesion; public { Public declarations } procedure MoveSelected(List: TCustomListBox; Items: TStrings); procedure SetItem(List: TListBox; Index: Integer); function GetFirstSelection(List: TCustomListBox): Integer; procedure SetButtons; procedure ActualizarArchivos( FBd: TDataBase ); end; var ActualDlg: TActualDlg; implementation uses Main, DM; {$R *.DFM} procedure TActualDlg.IncludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(SrcList); MoveSelected(SrcList, DstList.Items); SetItem(SrcList, Index); end; procedure TActualDlg.ExcludeBtnClick(Sender: TObject); var Index: Integer; begin Index := GetFirstSelection(DstList); MoveSelected(DstList, SrcList.Items); SetItem(DstList, Index); end; procedure TActualDlg.IncAllBtnClick(Sender: TObject); var I: Integer; begin for I := 0 to SrcList.Items.Count - 1 do DstList.Items.AddObject(SrcList.Items[I], SrcList.Items.Objects[I]); SrcList.Items.Clear; SetItem(SrcList, 0); end; procedure TActualDlg.ExcAllBtnClick(Sender: TObject); var I: Integer; begin for I := 0 to DstList.Items.Count - 1 do SrcList.Items.AddObject(DstList.Items[I], DstList.Items.Objects[I]); DstList.Items.Clear; SetItem(DstList, 0); end; procedure TActualDlg.MoveSelected(List: TCustomListBox; Items: TStrings); var I: Integer; begin for I := List.Items.Count - 1 downto 0 do if List.Selected[I] then begin Items.AddObject(List.Items[I], List.Items.Objects[I]); List.Items.Delete(I); end; end; procedure TActualDlg.SetButtons; var SrcEmpty, DstEmpty: Boolean; begin SrcEmpty := SrcList.Items.Count = 0; DstEmpty := DstList.Items.Count = 0; IncludeBtn.Enabled := not SrcEmpty; IncAllBtn.Enabled := not SrcEmpty; ExcludeBtn.Enabled := not DstEmpty; ExAllBtn.Enabled := not DstEmpty; end; function TActualDlg.GetFirstSelection(List: TCustomListBox): Integer; begin for Result := 0 to List.Items.Count - 1 do if List.Selected[Result] then Exit; Result := LB_ERR; end; procedure TActualDlg.SetItem(List: TListBox; Index: Integer); var MaxIndex: Integer; begin with List do begin SetFocus; MaxIndex := List.Items.Count - 1; if Index = LB_ERR then Index := 0 else if Index > MaxIndex then Index := MaxIndex; Selected[Index] := True; end; SetButtons; end; procedure TActualDlg.OKBtnClick(Sender: TObject); begin Actualizar; showmessage( 'Fin de rutina' ); end; procedure TActualDlg.Actualizar; var x: integer; begin Screen.cursor := crHourglass; for x:= 0 to DstList.Items.Count-1 do try if DstList.Items[ x ] = 'CLIENTE' then begin ActualizarClientes; Continue; end; if DstList.Items[ x ] = 'ARTICULO' then begin ActualizarArticulos; Continue; end; if DstList.Items[ x ] = 'PROVE' then begin ActualizarProve; Continue; end; TOri.TableName := DstList.Items[ x ]; TDes.TableName := DstList.Items[ x ]; if DstList.Items[ x ] = 'LISTA' then begin TOri.IndexName := 'CODLIS'; TDes.IndexName := 'CODLIS'; end else begin TOri.IndexName := 'PrimaryKey'; TDes.IndexName := 'PrimaryKey'; end; lbEstado.Caption := 'Blanqueando archivo ' + DstList.Items[ x ]; Application.ProcessMessages; TDes.EmptyTable; lbEstado.Caption := 'Actualizando ' + DstList.Items[ x ]; Application.ProcessMessages; Bm.Execute; except on e:exception do showmessage( 'Error al actualizar archivo: ' + DstList.Items[ x ] + #13 + e.message ); end; lbEstado.Caption := 'Tarea finalizada'; Screen.cursor := crdefault; end; procedure TActualDlg.FormCreate(Sender: TObject); begin SetearSesion; // DataIng.Opx.Connected := true; end; procedure TActualDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin // DataIng.Opx.Connected := false; end; procedure TActualDlg.ActualizarArchivos( FBd: TDataBase ); var FSec: string; FVieAlias: string; begin with FMain, FModiDatos do try try // guardamos alias; FVieAlias := FBd.AliasName; // primero de oficial a negro FSec := 'ATOX'; FBd.Connected := false; FBd.AliasName := 'BASE2000'; // origen debe apuntar a la base de datos oficial TOri.DataBaseName := 'Bd'; // y destino a base de datos negra TDes.DataBaseName := 'BdX'; ReadSection( FSec, DstList.Items ); Actualizar; EraseSection( FSec ); FSec := 'XTOA'; // ahora de negro a oficial si hay modificaciones; // el origen es la base de datos en negro TOri.DataBaseName := 'Bdx'; TDes.DataBaseName := 'Bd'; ReadSection( FSec, DstList.Items ); Actualizar; EraseSection( FSec ); except end; ShowMessage( 'Actualizacion Concluida' ); finally FBd.Connected := false; FBd.AliasName := FVieAlias; end; end; procedure TActualDlg.ActualizarClientes; var x: integer; begin try TOri.TableName := 'CLIENTE'; TDes.TableName := 'CLIENTE'; TOri.IndexName := 'PrimaryKey'; TDes.IndexName := 'PrimaryKey'; TOri.Open; TDes.Open; TOri.first; while not TOri.eof do begin if TDes.FindKey( [ TOri.FieldByName( 'CODIGO' ).value ] ) then TDes.Edit else TDes.append; for x:=0 to TOri.FieldCount-1 do if ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDO' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDODOC' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDOF' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDODOCOF' ) then else TDes.Fields[ x ].value := TOri.Fields[ x ].value; TDes.Post; TOri.next; end; finally TOri.Close; TDes.Close; end; end; procedure TActualDlg.ActualizarArticulos; var x: integer; begin try TOri.TableName := 'ARTICULO'; TDes.TableName := 'ARTICULO'; TOri.IndexName := 'PrimaryKey'; TDes.IndexName := 'PrimaryKey'; TOri.Open; TDes.Open; TOri.first; while not TOri.eof do begin if TDes.FindKey( [ TOri.FieldByName( 'CODIGO' ).value ] ) then TDes.Edit else TDes.append; for x:=0 to TOri.FieldCount-1 do if ( UpperCase( TOri.Fields[ x ].FieldName ) = 'STOCK' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'STOCKOF' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'PEDIDO' ) then else TDes.Fields[ x ].value := TOri.Fields[ x ].value; TDes.Post; TOri.next; end; finally TOri.Close; TDes.Close; end; end; procedure TActualDlg.ActualizarProve; var x: integer; begin try TOri.TableName := 'PROVE'; TDes.TableName := 'PROVE'; TOri.IndexName := 'PrimaryKey'; TDes.IndexName := 'PrimaryKey'; TOri.Open; TDes.Open; TOri.first; while not TOri.eof do begin if TDes.FindKey( [ TOri.FieldByName( 'CODIGO' ).value ] ) then TDes.Edit else TDes.append; for x:=0 to TOri.FieldCount-1 do if ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDO' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDODOC' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDOF' ) or ( UpperCase( TOri.Fields[ x ].FieldName ) = 'SALDODOCOF' ) then else TDes.Fields[ x ].value := TOri.Fields[ x ].value; TDes.Post; TOri.next; end; finally TOri.Close; TDes.Close; end; end; procedure TActualDlg.SetearSesion; var x: integer; begin for x:=0 to ComponentCount-1 do if Components[ x ] is TDbDataSet then TDbDataSet(Components[ x ]).SessionName := DMod.Session1.SessionName; end; procedure TActualDlg.HelpBtnClick(Sender: TObject); var dummy: boolean; begin hh( 0,0, dummy ); end; end.
unit dmfotos; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, rxmemds, ZDataset, db ,dmGeneral ; type { TDM_Fotos } TDM_Fotos = class(TDataModule) qFotoRelacionFOTO: TBlobField; qFotoRelacionIDFOTO: TStringField; qFotoRelacionRELACION: TStringField; tbFoto: TRxMemoryData; tbFotoFoto: TBlobField; tbFotoidFoto: TStringField; tbFotorelacion: TStringField; qFotoRelacion: TZQuery; procedure DataModuleCreate(Sender: TObject); procedure tbFotoAfterInsert(DataSet: TDataSet); private { private declarations } public procedure LevantarFoto (relacion: GUID_ID); procedure cargarArchivo (relacion: GUID_ID; archivo: string); end; var DM_Fotos: TDM_Fotos; implementation {$R *.lfm} { TDM_Fotos } procedure TDM_Fotos.tbFotoAfterInsert(DataSet: TDataSet); begin with DataSet do begin FieldByName('idFoto').asString:= DM_General.CrearGUID; FieldByName('relacion').asString:= GUIDNULO; end; end; procedure TDM_Fotos.DataModuleCreate(Sender: TObject); begin tbFoto.Open; end; procedure TDM_Fotos.LevantarFoto(relacion: GUID_ID); begin DM_General.ReiniciarTabla(tbFoto); with qFotoRelacion do begin if active then close; ParamByName('relacion').asString:= relacion; Open; tbFoto.LoadFromDataSet(qFotoRelacion, 0, lmAppend); end; end; procedure TDM_Fotos.cargarArchivo(relacion: GUID_ID; archivo: string); begin DM_General.ReiniciarTabla(tbFoto); tbFoto.Insert; tbFotorelacion.asString:= relacion; // tbFotoFoto.LoadFromFile(archivo); tbFoto.Post; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.Receivers.ZeroMQ; { ZeroMQ channel receiver. } interface uses System.Classes, Vcl.ExtCtrls, Spring, Spring.Collections, ZeroMQ, DDuce.DynamicRecord, LogViewer.Interfaces, LogViewer.Receivers.Base, LogViewer.ZeroMQ.Settings; {$REGION 'documentation'} { Receives logmessages from one or more ZMQ publisher through a subscriber socket. A ZeroMQChannelReceiver can receive messages from multiple channels that are bound to one or more ZMQ publisher sockets. In this setup the source application (sender of log messages) acts as a server which binds to a ZeroMQ socket (publisher). Multiple subscribers (TZeroMQChannelReceiver instances) can connect to the same publisher. REMARKS: - communication with ZeroMQ sockets is asynchronious. So the source application is never blocked as all messages are queued. - when the receiver cannot keep up with the publisher, messages are thrown away by the ZeroMQ subscriber. TODO: - list of connectionstrings to subscribe to? } {$ENDREGION} type TZeroMQChannelReceiver = class(TChannelReceiver, IChannelReceiver, IZMQ) private FZMQ : IZeroMQ; protected {$REGION 'property access methods'} function GetSettings: TZeroMQSettings; procedure SetEnabled(const Value: Boolean); override; {$ENDREGION} procedure SettingsChanged(Sender: TObject); function CreateSubscriber( ASourceId : UInt32; AThreadId : UInt32; const ASourceName : string ): ISubscriber; override; public procedure AfterConstruction; override; constructor Create( AManager : ILogViewerManager; AZMQ : IZeroMQ; const AName : string ); reintroduce; property Settings: TZeroMQSettings read GetSettings; end; implementation uses System.SysUtils, Vcl.Forms, LogViewer.Subscribers.ZeroMQ; {$REGION 'construction and destruction'} procedure TZeroMQChannelReceiver.AfterConstruction; begin inherited AfterConstruction; PollTimer.OnTimer := PollTimerTimer; PollTimer.Interval := Settings.PollingInterval; Settings.OnChanged.Add(SettingsChanged); end; constructor TZeroMQChannelReceiver.Create(AManager: ILogViewerManager; AZMQ: IZeroMQ; const AName: string); begin inherited Create(AManager, AName); FZMQ := AZMQ; end; function TZeroMQChannelReceiver.CreateSubscriber(ASourceId, AThreadId: UInt32; const ASourceName: string): ISubscriber; begin // Result := TZMQSubscriber.Create( // Self, FZMQ, '', ASourceId, '', ASourceName, False // ); end; {$ENDREGION} {$REGION 'property access methods'} procedure TZeroMQChannelReceiver.SetEnabled(const Value: Boolean); begin inherited SetEnabled(Value); PollTimer.Enabled := Value; end; function TZeroMQChannelReceiver.GetSettings: TZeroMQSettings; begin Result := Manager.Settings.ZeroMQSettings; end; {$ENDREGION} {$REGION 'event handlers'} procedure TZeroMQChannelReceiver.SettingsChanged(Sender: TObject); begin Enabled := Settings.Enabled; PollTimer.Interval := Settings.PollingInterval; end; {$ENDREGION} end.
unit MVCBr.FMX.PageView; interface uses FMX.Forms, FMX.Controls, System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.PageView, MVCBr.FormView, FMX.TabControl, FMX.Types; type TFMXpageViewOnQueryClose = procedure(APageView: IPageView; var ACanClose: boolean) of object; TFMXPageViewManager = class(TCustomPageViewFactory, IPageViews) private FOldPageChange: TNotifyEvent; FOnQueryClose: TFMXpageViewOnQueryClose; FAfterTabCreate: TNotifyEvent; FAfterCreate: TNotifyEvent; procedure Init(APageView: IPageView); override; procedure SetTabControl(const Value: TTabControl); function GetTabControl: TTabControl; procedure SetOnQueryClose(const Value: TFMXpageViewOnQueryClose); procedure SetAfterTabCreate(const Value: TNotifyEvent); procedure SetAfterCreate(const Value: TNotifyEvent); procedure DoPageChange(Sender: TObject); protected Procedure DoQueryClose(const APageView: IPageView; var ACanClose: boolean); override; procedure SetActivePage(Const Tab: TObject); override; public class function New(AController: IController): IPageViews; function Update: IModel; virtual; function GetPageTabClass: TComponentClass; override; function GetPageContainerClass: TComponentClass; override; function NewTab(APageView: IPageView): TObject; override; function AddView(AView: IView): IPageView; override; function AddView(Const AController: TGuid): IPageView; overload; override; published property TabControl: TTabControl read GetTabControl write SetTabControl; property AfterViewCreate; property AfterCreateComplete: TNotifyEvent read FAfterCreate write SetAfterCreate; property AfterTabCreate: TNotifyEvent read FAfterTabCreate write SetAfterTabCreate; property OnQueryClose: TFMXpageViewOnQueryClose read FOnQueryClose write SetOnQueryClose; end; procedure register; implementation uses FMX.Layouts; procedure register; begin RegisterComponents('MVCBr', [TFMXPageViewManager]); end; { TVCLPageViewFactory } function TFMXPageViewManager.AddView(AView: IView): IPageView; begin result := inherited AddView(AView); end; function TFMXPageViewManager.AddView(const AController: TGuid): IPageView; begin result := inherited AddView(AController); end; procedure TFMXPageViewManager.DoQueryClose(const APageView: IPageView; var ACanClose: boolean); begin inherited; if assigned(FOnQueryClose) then FOnQueryClose(APageView, ACanClose); end; procedure TFMXPageViewManager.DoPageChange(Sender: TObject); begin if assigned(FOldPageChange) then FOldPageChange(Sender); ActivePageIndex := TTabControl(FPageContainer).TabIndex; end; function TFMXPageViewManager.GetPageContainerClass: TComponentClass; begin result := TTabControl; end; function TFMXPageViewManager.GetTabControl: TTabControl; begin result := TTabControl(FPageContainer); end; type TTabItemView = class(TTabItem) private FViewer: TLayout; public PageView: IPageView; constructor create(AOwner: TComponent); override; destructor destroy; override; procedure CanClose(var ACanClose: boolean); end; procedure TTabItemView.CanClose(var ACanClose: boolean); var form: TForm; ref: TFMXPageViewManager; begin ref := TFMXPageViewManager(PageView.This.GetOwner); if assigned(ref) and assigned(ref.OnQueryClose) then TFMXPageViewManager(ref).OnQueryClose(PageView, ACanClose); if ACanClose then if assigned(PageView) then if assigned(PageView.This.View) then begin form := TForm(PageView.This.View.This); if assigned(form) then if assigned(form.OnCloseQuery) then form.OnCloseQuery(self, ACanClose); if ACanClose then // with PageView.This.View.GetController do begin TControllerAbstract.RevokeInstance(PageView.This.View.GetController); end; end; end; constructor TTabItemView.create(AOwner: TComponent); begin inherited; FViewer := TLayout.create(self); FViewer.Parent := self; FViewer.Align := TAlignLayout.Client; end; destructor TTabItemView.destroy; var LCanClose: boolean; begin LCanClose := true; CanClose(LCanClose); if not LCanClose then abort; if assigned(PageView) then begin PageView.remove; PageView := nil; end; inherited destroy; end; function TFMXPageViewManager.GetPageTabClass: TComponentClass; begin result := TTabItemView; end; procedure TFMXPageViewManager.Init(APageView: IPageView); var frm: TForm; tl: TLayout; o: TComponent; begin if assigned(APageView) then if assigned(APageView.This.View) then begin if APageView.This.View.This.InheritsFrom(TViewFactoryAdapter) then begin frm := TForm(TViewFactoryAdapter(APageView.This.View.This).form); APageView.This.text := frm.Caption; end else frm := TForm(APageView.This.View.This); with frm do begin frm.Parent := TTabItemView(APageView.This.Tab).FViewer; // TTabItemView(APageView.This.Tab).FViewer.AddObject(frm); while frm.ChildrenCount > 0 do frm.Children[0].Parent := TTabItemView(APageView.This.Tab).FViewer; BorderStyle := TFmxFormBorderStyle.None; TTabItem(APageView.This.Tab).text := APageView.This.text; if APageView.This.View.This.InheritsFrom(TFormFactory) then begin TFormFactory(APageView.This.View.This).isShowModal := false; APageView.This.View.ShowView(nil); // show; end else { show }; if assigned(AfterCreateComplete) then AfterCreateComplete(APageView.This); end; end; end; class function TFMXPageViewManager.New(AController: IController): IPageViews; begin result := TFMXPageViewManager.create(nil); result.Controller(AController); end; function TFMXPageViewManager.NewTab(APageView: IPageView): TObject; var Tab: TTabItemView; begin Tab := GetPageTabClass.create(FPageContainer) as TTabItemView; Tab.Parent := TTabControl(FPageContainer); Tab.PageView := APageView; TTabControl(FPageContainer).ActiveTab := Tab; result := Tab; if assigned(FAfterTabCreate) then FAfterTabCreate(Tab); end; procedure TFMXPageViewManager.SetActivePage(const Tab: TObject); begin inherited; TTabControl(FPageContainer).ActiveTab := TTabItem(Tab); end; procedure TFMXPageViewManager.SetAfterCreate(const Value: TNotifyEvent); begin FAfterCreate := Value; end; procedure TFMXPageViewManager.SetAfterTabCreate(const Value: TNotifyEvent); begin FAfterTabCreate := Value; end; procedure TFMXPageViewManager.SetOnQueryClose(const Value : TFMXpageViewOnQueryClose); begin FOnQueryClose := Value; end; procedure TFMXPageViewManager.SetTabControl(const Value: TTabControl); begin if assigned(Value) then begin FOldPageChange := Value.OnChange; Value.OnChange := DoPageChange; end else begin FOldPageChange := nil; end; FPageContainer := Value; end; function TFMXPageViewManager.Update: IModel; var APageView: IPageView; begin ActivePageIndex := TTabControl(FPageContainer).TabIndex; APageView := ActivePage; Init(APageView); end; end.
unit cAtualizacaoBancoDeDados; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; type TAtualizaBancoDados = class private public ConexaoDB: TFDConnection; constructor Create(aConexao: TFDConnection); procedure ExecutaDiretoBancoDeDados(aScript: String); end; Type TAtualizaBancoDadosMySQL = Class private ConexaoDB: TFDConnection; public function AtualizarBancoDeDadosMySQL: Boolean; constructor Create(aConexao: TFDConnection); End; implementation uses cAtualizacaoTabelaMySQL, cAtualizacaoCampoMySQL; { TAtualizaBancoDados } constructor TAtualizaBancoDados.Create(aConexao: TFDConnection); begin ConexaoDB := aConexao; end; procedure TAtualizaBancoDados.ExecutaDiretoBancoDeDados(aScript: String); Var Qry: TFDQuery; Begin Try Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(aScript); Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; End; Finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry); End; end; { TAtualizaBancoDadosMySQL } function TAtualizaBancoDadosMySQL.AtualizarBancoDeDadosMySQL: Boolean; var oAtualizaDB: TAtualizaBancoDados; oTabela: TAtualizacaoTabelaMySQL; oCampo: TAtualizacaoCampoMySQL; begin try oAtualizaDB := TAtualizaBancoDados.Create(ConexaoDB); oTabela := TAtualizacaoTabelaMySQL.Create(ConexaoDB); oCampo := TAtualizacaoCampoMySQL.Create(ConexaoDB); finally if Assigned(oAtualizaDB) then FreeAndNil(oAtualizaDB); if Assigned(oTabela) then FreeAndNil(oTabela); if Assigned(oCampo) then FreeAndNil(oCampo); end; end; constructor TAtualizaBancoDadosMySQL.Create(aConexao: TFDConnection); begin ConexaoDB := aConexao; end; end.
unit TestuRfMemoryProfiler; interface uses TestFramework, uRfMemoryProfiler, SyncObjs, Classes, Contnrs, uUnitTestHeader, Diagnostics, Windows; type {$DEFINE BUFFER_TRACKER} {$DEFINE INSTANCES_TRACKER} {$Include RfMemoryProfilerOptions.inc} // Test methods for class TAllocationMap TObjectTest = class(TObject); TestRfMemoryProfiller = class(TTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure TestObjectCounter; {$IFDEF INSTANCES_TRACKER} procedure TestTraceObjectAllocation; {$ENDIF} end; TestBufferAllocation = class(TTestCase) private FBufferList: TList; public procedure SetUp; override; procedure TearDown; override; public procedure TestBufferAllocMemCounter; procedure TestBufferFreeMemToAllocMemCounter; procedure TestBufferPointerAddrToAllocFree; procedure TestBufferGetMemCounter; procedure TestBufferFreeMemToGetMemCounter; procedure TestBufferPointerAddrToGetFree; procedure TestBufferReallocMemCounter; published procedure TestCheckPerfomance; procedure TestBasicFunctionsAllocFree; procedure TestBasicFunctionsGetMemFree; procedure TestRealloc; {$IFDEF BUFFER_TRACKER} procedure TestTracker; {$ENDIF} end; implementation uses SysUtils; var UGetModuleHandle: Cardinal; const CODE_SECTION = $1000; procedure GetCodeOffset; var LMapFile: string; begin LMapFile := GetModuleName(hInstance); UGetModuleHandle := GetModuleHandle(Pointer(ExtractFileName(LMapFile))) + CODE_SECTION; end; procedure TestRfMemoryProfiller.SetUp; begin InitializeRfMemoryProfiler; end; procedure TestRfMemoryProfiller.TearDown; begin end; procedure TestRfMemoryProfiller.TestObjectCounter; var LObjectList: TObjectList; I: Integer; LList: TList; LClassVars: TRfClassController; LFound: Boolean; begin LObjectList := TObjectList.Create; for I := 0 to AMOUNT_OF_ALLOCATIONS -1 do LObjectList.Add(TObjectTest.Create); LFound := False; LList := RfGetInstanceList; for I := 0 to LList.Count -1 do if TRfClassController(LList.Items[I]).BaseClassName = 'TObjectTest' then begin CheckTrue(TRfClassController(LList.Items[I]).BaseInstanceCount = AMOUNT_OF_ALLOCATIONS, 'The object counter is not working as it should. The value in counter is different from the excepted.'); LFound := True; Break; end; CheckTrue(LFound, 'The object registration is not working'); LObjectList.Free; end; {$IFDEF INSTANCES_TRACKER} procedure TestRfMemoryProfiller.TestTraceObjectAllocation; var LStack: Integer; LObjectTest: TRfObjectHack; LAllocationMap: TAllocationMap; I: Integer; LObjectList: TObjectList; II: Integer; begin {Get the addr of this procedure} asm mov LStack, ebp end; LStack := PInteger(Integer(LStack) + 4)^; Dec(LStack, UGetModuleHandle); for II := 0 to 50 do begin LObjectList := TObjectList.Create; for I := 0 to AMOUNT_OF_ALLOCATIONS -1 do begin LObjectTest := TRfObjectHack(TPersistent.Create); LAllocationMap := LObjectTest.GetRfClassController.AllocationMap; LObjectList.Add(LObjectTest); CheckTrue(LObjectTest.AllocationAddress = LStack, 'Allocation address do not correspond to actual caller.'); CheckTrue(LAllocationMap.GetAllocationCounterByCallerAddr(LStack).NumAllocations = LObjectList.Count, 'Object allocation counter is not working.'); end; LObjectList.Free; end; CheckTrue(LAllocationMap.GetAllocationCounterByCallerAddr(LStack).NumAllocations = 0, 'Object deallocation counter is not working.'); end; {$ENDIF} { TestBufferAllocation } procedure TestBufferAllocation.SetUp; begin InitializeRfMemoryProfiler; RfInitilializeAllocDeallocArrays; FBufferList := TList.Create; end; procedure TestBufferAllocation.TearDown; begin FBufferList.Free; end; procedure TestBufferAllocation.TestBasicFunctionsAllocFree; begin Status('Testing TestBufferAllocMemCounter'); TestBufferAllocMemCounter; Status('Testing TestBufferFreeMemToAllocMemCounter'); TestBufferFreeMemToAllocMemCounter; Status('Testing TestBufferPointerAddrToAllocFree'); TestBufferPointerAddrToAllocFree; end; procedure TestBufferAllocation.TestBasicFunctionsGetMemFree; begin Status('Testing TestBufferGetMemCounter'); TestBufferGetMemCounter; Status('Testing TestBufferFreeMemToGetMemCounter'); TestBufferFreeMemToGetMemCounter; Status('Testing TestBufferPointerAddrToGetFree'); TestBufferPointerAddrToGetFree; end; procedure TestBufferAllocation.TestBufferAllocMemCounter; var I: Integer; begin for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do FBufferList.Add(AllocMem(BUFFER_TEST_SIZE)); CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = AMOUNT_OF_ALLOCATIONS, 'Wrong counter of buffer allocation for AllocMem.'); CheckTrue(ComparePointerListToAllocationAddress(FBufferList), 'The comparision btw the addresses pointer of allocmem result are not correct.'); end; procedure TestBufferAllocation.TestBufferFreeMemToAllocMemCounter; var I: Integer; LPointer: Pointer; begin for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do begin LPointer := FBufferList.Items[I]; Dispose(LPointer); end; CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = 0, 'Wrong count of buffer deallocation to AllocMem.'); end; procedure TestBufferAllocation.TestBufferFreeMemToGetMemCounter; var I: Integer; LPointer: Pointer; begin for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do begin LPointer := FBufferList.Items[I]; Dispose(LPointer); end; CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = 0, 'Wrong count of buffer deallocation GetMem.'); end; procedure TestBufferAllocation.TestBufferGetMemCounter; var I: Integer; begin for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do FBufferList.Add(GetMemory(BUFFER_TEST_SIZE)); CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = AMOUNT_OF_ALLOCATIONS, 'Wrong counter of buffer allocation GetMem.'); CheckTrue(ComparePointerListToAllocationAddress(FBufferList), 'The comparision btw the addresses pointer of GetMem result are not correct.'); end; procedure TestBufferAllocation.TestBufferPointerAddrToAllocFree; begin CheckTrue(IsSameValuesInAllocAndDeallocArray, 'Wrong allocation and deallocations address to AllocMem and FreeMem.'); end; procedure TestBufferAllocation.TestBufferPointerAddrToGetFree; begin CheckTrue(IsSameValuesInAllocAndDeallocArray, 'Wrong allocation and deallocations address GetMem and FreeMem.'); end; procedure TestBufferAllocation.TestBufferReallocMemCounter; var I: Integer; LPointer: Pointer; begin for I := 0 to FBufferList.Count -1 do begin LPointer := FBufferList.Items[I]; ReallocMem(LPointer, BUFFER_TEST_REALOC_SIZE); FBufferList.Items[I] := LPointer; end; CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = 0, 'Wrong counter of buffer on base pointer on reallocation.'); CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_REALOC_SIZE] = AMOUNT_OF_ALLOCATIONS, 'Wrong counter of buffer on new pointer on reallocation.'); for I := 0 to FBufferList.Count -1 do begin LPointer := FBufferList.Items[I]; FreeMem(LPointer); end; CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_REALOC_SIZE] = 0, 'Wrong counter of buffer on new pointer on deallocation.'); end; procedure TestBufferAllocation.TestCheckPerfomance; const LOOP_AMOUNT = 200; var LStopWatcher: TStopwatch; I: Integer; LDefaultAllocMemTime: Int64; LDefaultFreeMemTime: Int64; LNewAllocMemTime: Int64; LNewFreeMemTime: Int64; LPointer: Pointer; II: Integer; LDeltaAllocMem: Extended; LDeltaFreeMem: Extended; begin LDefaultAllocMemTime := 0; LDefaultFreeMemTime := 0; LNewAllocMemTime := 0; LNewFreeMemTime := 0; //Old callers LStopWatcher := TStopwatch.Create; for II := 0 to LOOP_AMOUNT do begin LStopWatcher.Reset; LStopWatcher.Start; for I := 0 to PERFOMANCE_AMOUNT_OF_ALLOCATIONS do FBufferList.Add(SDefaultAllocMem(SIZE_OF_INT)); LStopWatcher.Stop; LDefaultAllocMemTime := LStopWatcher.ElapsedMilliseconds + LDefaultAllocMemTime; LStopWatcher.Reset; LStopWatcher.Start; for I := 0 to PERFOMANCE_AMOUNT_OF_ALLOCATIONS do begin LPointer := FBufferList.Items[I]; SDefaultFreeMem(LPointer); end; LStopWatcher.Stop; LDefaultFreeMemTime := LStopWatcher.ElapsedMilliseconds + LDefaultFreeMemTime; FBufferList.Clear; //New callers LStopWatcher.Reset; LStopWatcher.Start; for I := 0 to PERFOMANCE_AMOUNT_OF_ALLOCATIONS do FBufferList.Add(SDefaultAllocMem(SIZE_OF_INT)); LStopWatcher.Stop; LNewAllocMemTime := LStopWatcher.ElapsedMilliseconds + LNewAllocMemTime; LStopWatcher.Reset; LStopWatcher.Start; for I := 0 to PERFOMANCE_AMOUNT_OF_ALLOCATIONS do begin LPointer := FBufferList.Items[I]; FreeMem(LPointer); end; LStopWatcher.Stop; LNewFreeMemTime := LStopWatcher.ElapsedMilliseconds + LNewFreeMemTime; FBufferList.Clear; end; LDeltaAllocMem := (LDefaultAllocMemTime / LNewAllocMemTime); LDeltaFreeMem := (LDefaultFreeMemTime / LNewFreeMemTime); Status('------------------ Perfomance Test ------------------'); Status(Format('Amount of items allocated/deallocated: %d', [LOOP_AMOUNT * PERFOMANCE_AMOUNT_OF_ALLOCATIONS])); Status('-- AllocMem: '); Status(Format(' Default: Spent %d ms', [LDefaultAllocMemTime])); Status(Format(' New: Spent %d ms', [LNewAllocMemTime])); Status(Format(' Speed delta: %2.2f %%',[(LDeltaAllocMem * 100) - 100])); Status('-- FreeMem: '); Status(Format(' Default: Spent %d ms', [LDefaultFreeMemTime])); Status(Format(' New: Spent %d ms', [LNewFreeMemTime])); Status(Format(' Speed delta: %2.2f %%',[(LDeltaFreeMem * 100) - 100])); CheckTrue(LDeltaAllocMem > 0.5, 'The new memory allocator is more than 50% slower the default method.'); CheckTrue(LDeltaFreeMem > 0.5, 'The new free memory is more than 50% slower than the default methos'); end; procedure TestBufferAllocation.TestRealloc; begin TestBufferAllocMemCounter; TestBufferReallocMemCounter; end; procedure TestBufferAllocation.TestTracker; var I: Integer; LStack: Cardinal; LPointer: Pointer; LMemoryItem: TMappedRecord; begin {Get the addr of this procedure} asm mov LStack, ebp end; LStack := PInteger(Integer(LStack) + 4)^; Dec(LStack, UGetModuleHandle); CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = 0, 'Wrong buffer trace test initialization. The buffer counter allocation must start in 0.'); CheckTrue(GetAmountOfBufferAllocations(LStack, BUFFER_TEST_SIZE) = 0, 'Wrong buffer trace test initialization. The buffer addr allocation counter allocation must start in 0.'); for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do FBufferList.Add(GetMemory(BUFFER_TEST_SIZE)); LMemoryItem := TMappedRecord(Pointer(Integer(FBufferList.Items[0]) - GAP_SIZE)^); CheckTrue(LMemoryItem.AllocationAddr = LStack, 'Wrong caller addr for buffer allocation'); CheckTrue(GetAmountOfBufferAllocations(LStack, BUFFER_TEST_SIZE) = AMOUNT_OF_ALLOCATIONS, 'The number of buffer allocations for addr is wrong'); for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do begin LPointer := FBufferList.Items[I]; Dispose(LPointer); end; CheckTrue(RfMapOfBufferAllocation[BUFFER_TEST_SIZE] = 0, 'Wrong count of buffer deallocation to AllocMem.'); CheckTrue(GetAmountOfBufferAllocations(LStack, BUFFER_TEST_SIZE) = 0, 'The number of buffer deallocations for addr is wrong'); end; initialization GetCodeOffset; RegisterTest(TestRfMemoryProfiller.Suite); RegisterTest(TestBufferAllocation.Suite); end.
{ *************************************************************************** Copyright (c) 2015-2021 Kike Pérez Unit : Quick.FileMonitor Description : Watch for single file changes Author : Kike Pérez Version : 1.2 Created : 11/09/2017 Modified : 10/05/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.FileMonitor; interface {$i QuickLib.inc} uses Classes, {$IFDEF MSWINDOWS} Windows, SyncObjs, {$ELSE} SyncObjs, {$ENDIF} SysUtils, {$IFDEF FPC} Quick.Files; {$ELSE} System.IOUtils; {$ENDIF} type TMonitorNotify = (mnNone, mnFileCreated, mnFileModified, mnFileDeleted); TMonitorWatch = set of TMonitorNotify; TFileChangeNotify = procedure(MonitorNofify : TMonitorNotify) of object; TFileMonitor = class(TThread) private fFileName : string; fTickEvent : TSimpleEvent; fInterval : Integer; fNotifies : TMonitorWatch; fEnabled : Boolean; fExists : Boolean; fModifedDate : TDateTime; fCurrentMonitorNotify : TMonitorNotify; fOnChangeNotify : TFileChangeNotify; fIsThreadStarted : Boolean; procedure SetEnabled(Status : Boolean); procedure NotifyEvent; protected procedure Execute; override; public constructor Create; destructor Destroy; override; property FileName : string read fFileName write fFileName; property Interval : Integer read fInterval write fInterval; property Notifies : TMonitorWatch read fNotifies write fNotifies; property OnFileChange : TFileChangeNotify read fOnChangeNotify write fOnChangeNotify; property Enabled : Boolean read fEnabled write SetEnabled; end; TQuickFileMonitor = TFileMonitor; implementation constructor TFileMonitor.Create; begin inherited Create(True); fIsThreadStarted := False; fEnabled := False; Self.FreeOnTerminate := False; fInterval := 1000; fExists := False; fModifedDate := 0; fCurrentMonitorNotify := mnNone; fNotifies := [mnFileCreated,mnFileModified,mnFileDeleted]; {$IFDEF FPC} fTickEvent := TSimpleEvent.Create; {$ELSE} fTickEvent := TSimpleEvent.Create(nil,True,False,''); {$ENDIF} end; destructor TFileMonitor.Destroy; begin if not Terminated then Terminate; Self.WaitFor; fTickEvent.SetEvent; fTickEvent.Free; inherited; end; procedure TFileMonitor.Execute; var LastModifiedDate : TDateTime; begin inherited; while not Terminated do begin fCurrentMonitorNotify := mnNone; if fTickEvent.WaitFor(fInterval) = TWaitResult.wrTimeout then begin if fEnabled then begin if TFile.Exists(fFileName) then begin if fExists then begin if mnFileModified in fNotifies then begin LastModifiedDate := TFile.GetLastWriteTime(fFileName); if LastModifiedDate > fModifedDate then begin fCurrentMonitorNotify := mnFileModified; fModifedDate := LastModifiedDate; end; end; end else begin if mnFileCreated in fNotifies then fCurrentMonitorNotify := mnFileCreated; LastModifiedDate := TFile.GetLastWriteTime(fFileName); fModifedDate := LastModifiedDate; end; fExists := True; end else begin //check if file deleted if mnFileDeleted in fNotifies then begin if fExists then begin fExists := False; fCurrentMonitorNotify := mnFileDeleted; end; end; end; if fCurrentMonitorNotify <> mnNone then begin if IsConsole then NotifyEvent else Synchronize(NotifyEvent); end; end; end; end; end; procedure TFileMonitor.SetEnabled(Status : Boolean); begin if fEnabled <> Status then begin if Status then begin //gets current values if TFile.Exists(fFileName) then begin fExists := True; fModifedDate := TFile.GetLastWriteTime(fFileName); end; end; if not fIsThreadStarted then begin fIsThreadStarted := True; if (Status) and {$IFNDEF FPC}(Started = False){$ELSE}(Suspended){$ENDIF} then Start; end; fEnabled := Status; end; end; procedure TFileMonitor.NotifyEvent; begin if Assigned(fOnChangeNotify) then fOnChangeNotify(fCurrentMonitorNotify); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons; type IAnimal = interface ['{8C3A2794-51D3-4401-8849-B4A4BF97C70F}'] function classe: string; function GetNome: string; procedure SetNome(ANome : String); property Nome:String read GetNome write SetNome; end; IMutante = interface ['{A1CDDF49-D45A-4915-B378-053467F17B46}'] function GetCategoria:String; end; TAnimal = class(TInterfacedObject, IAnimal) private FNome : string; protected function GetNome: string; virtual; procedure SetNome(ANome : String); virtual; public function classe: String; virtual; constructor Create; end; THomem = class(TInterfacedObject, IAnimal) private FNome : string; protected function GetNome: string; virtual; procedure SetNome(ANome : String); virtual; public function classe: String; virtual; constructor Create; end; TCachorro = class(TInterfacedObject, IAnimal) private FNome : string; protected function GetNome: string; virtual; procedure SetNome(ANome : String); virtual; public function classe: String; virtual; constructor Create; end; TLobisomen = class (TInterfacedObject, IAnimal, IMutante) private FNome : string; protected function GetNome: string; virtual; procedure SetNome(ANome : String); virtual; public function classe: String; virtual; function GetCategoria : String; virtual; constructor Create; end; TForm1 = class(TForm) BitBtn1: TBitBtn; BtnAnimal: TRadioButton; BtnHomem: TRadioButton; BtnCachorro: TRadioButton; BtnLob: TRadioButton; procedure BitBtn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.BitBtn1Click(Sender: TObject); var obj : IAnimal; objMut : IMutante; begin if BtnAnimal.Checked then obj := TAnimal.Create else if BtnCachorro.Checked then obj := TCachorro.Create else if BtnHomem.Checked then obj := THomem.Create else obj := TLobisomen.Create; ShowMessage(obj.classe); ShowMessage(obj.Nome); if obj.QueryInterface(IMutante, objMut) = 0 then ShowMessage('Categoria: '+objMut.GetCategoria); end; { THomem } function THomem.classe: String; begin Result := 'Homen'; end; constructor THomem.Create; begin inherited Create; FNome := 'Joao'; end; function THomem.GetNome: string; begin Result := FNome; end; procedure THomem.SetNome(ANome: String); begin FNome := ANome; end; { TCachorro } function TCachorro.classe: string; begin Result := 'Cachorro'; end; constructor TCachorro.Create; begin inherited Create; FNome := 'dog'; end; function TCachorro.GetNome: string; begin Result := FNome; end; procedure TCachorro.SetNome(ANome: String); begin FNome := ANome; end; { TAnimal } function TAnimal.classe: string; begin REsult := 'Animal'; end; constructor TAnimal.Create; begin inherited Create; FNome := 'sapiens'; end; function TAnimal.GetNome: string; begin Result := FNome; end; procedure TAnimal.SetNome(ANome: String); begin FNome := ANome; end; { TLobisomen } function TLobisomen.GetCategoria: String; begin Result := 'Ficção'; end; function TLobisomen.classe: String; begin REsult := 'Lobinho'; end; constructor TLobisomen.Create; begin inherited Create; FNome := 'Alien'; end; function TLobisomen.GetNome: string; begin Result := FNome; end; procedure TLobisomen.SetNome(ANome: String); begin FNome := ANome; end; end.
unit K609131924; {* [Requestlink:609131924] } // Модуль: "w:\common\components\rtl\Garant\Daily\K609131924.pas" // Стереотип: "TestCase" // Элемент модели: "K609131924" MUID: (561F3A590343) // Имя типа: "TK609131924" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK609131924 = class(TRTFtoEVDWriterTest) {* [Requestlink:609131924] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK609131924 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *561F3A590343impl_uses* //#UC END# *561F3A590343impl_uses* ; function TK609131924.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK609131924.GetFolder function TK609131924.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '561F3A590343'; end;//TK609131924.GetModelElementGUID initialization TestFramework.RegisterTest(TK609131924.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit clAcessos; interface uses Vcl.ActnList, clConexao, System.Classes; type TAcessos = Class(TObject) private function getFormulario: String; function getModulo: String; function getUsuario: Integer; procedure setFormulario(const Value: String); procedure setModulo(const Value: String); procedure setUsuario(const Value: Integer); protected _form: String; _modulo: String; _usuario: Integer; _conexao: TConexao; public constructor Create; destructor Destroy; property Formulario: String read getFormulario write setFormulario; property Modulo: String read getModulo write setModulo; property Usuario: Integer read getUsuario write setUsuario; function getAcessos(filtro: String): Boolean; function Insert(): Boolean; function Delete(filtro: String): Boolean; procedure SetAcessos(aMenu: TActionList); procedure SetNivel(aMenu: TActionList); end; const TABLENAME = 'TBACESSOS'; implementation { TAcessos } uses SysTem.SysUtils, Vcl.Dialogs, udm, clUtil, uGlobais; constructor TAcessos.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conex„o ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TAcessos.Destroy; begin _conexao.Free; end; function TAcessos.getFormulario: String; begin Result := _form; end; function TAcessos.getModulo: String; begin Result := _modulo; end; function TAcessos.getUsuario: Integer; begin Result := _usuario; end; function TAcessos.getAcessos(filtro: String): Boolean; begin try Result := False; if TUtil.Empty(filtro) then begin Exit; end; with dm.qryPesquisa do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CHAVE' then begin SQL.Add('WHERE NOM_FORM = :FORM AND NOM_MODULO = :MODULO AND COD_USUARIO = :USUARIO'); ParamByName('FORM').AsString := Self.Formulario; ParamByName('MODULO').AsString := Self.Modulo; ParamByName('USUARIO').AsInteger := Self.Usuario; end; if filtro = 'USUARIO' then begin SQL.Add('WHERE COD_USUARIO = :USUARIO'); ParamByName('USUARIO').AsInteger := Self.Usuario; end; if filtro = 'FORM' then begin SQL.Add('WHERE NOM_FORM = :FORM'); ParamByName('FORM').AsString := Self.Formulario; end; dm.ZConn.PingServer; Open; if IsEmpty then begin Close; SQL.Clear; Exit; end; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TAcessos.Insert(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + ' (' + 'NOM_FORM, ' + 'NOM_MODULO, ' + 'COD_USUARIO ' + ') VALUES (' + ':FORM, ' + ':MODULO, ' + ':USUARIO)'; ParamByName('FORM').AsString := Self.Formulario; ParamByName('MODULO').AsString := Self.Modulo; ParamByName('USUARIO').AsInteger := Self.Usuario; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; function TAcessos.Delete(filtro: string): Boolean; begin try Result := False; if TUtil.Empty(filtro) then begin Exit; end; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CHAVE' then begin SQL.Add('WHERE NOM_FORM = :FORM AND NOM_MODULO = :MODULO AND COD_USUARIO = :USUARIO'); ParamByName('FORM').AsString := Self.Formulario; ParamByName('MODULO').AsString := Self.Modulo; ParamByName('USUARIO').AsInteger := Self.Usuario; end; if filtro = 'USUARIO' then begin SQL.Add('WHERE COD_USUARIO = :USUARIO'); ParamByName('USUARIO').AsInteger := Self.Usuario; end; if filtro = 'FORM' then begin SQL.Add('WHERE NOM_FORM = :FORM'); ParamByName('FORM').AsString := Self.Formulario; end; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; except on E: Exception do begin ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end; procedure TAcessos.SetAcessos(aMenu: TActionList); var i: Integer; begin for i := 0 to aMenu.ActionCount - 1 do begin Self.Modulo := aMenu.Actions[i].Name; TAction(aMenu.Actions[i]).Visible := Self.getAcessos('CHAVE') end; end; procedure TAcessos.SetNivel(aMenu: TActionList); var i: Integer; begin for i := 0 to aMenu.ActionCount - 1 do begin TAction(aMenu.Actions[i]).Visible := (uGlobais.iNivelUsuario <= aMenu.Actions[i].Tag); end; end; procedure TAcessos.setFormulario(const Value: String); begin _form := Value; end; procedure TAcessos.setModulo(const Value: String); begin _modulo := Value; end; procedure TAcessos.setUsuario(const Value: Integer); begin _usuario := Value; end; end.
unit D_AttrActiveInterval; {$Include l3Define.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, vtCombo, vtDateEdit, Buttons, ExtCtrls, d_DateIntervalEdit, k2Interfaces, k2Tags, DT_Const, DT_Active, OvcBase, evEditorWindow, evMultiSelectEditorWindow, evCustomEditor, evEditorWithOperations, evMemo, afwControl, afwControlPrim, afwBaseControl, nevControl, evCustomMemo, evCustomEditorWindowPrim, evCustomEditorWindow, evCustomEditorWindowModelPart, evCustomEditorModelPart, l3Variant ; //, OvcBase, evEditorWindow, evEditor, evMemo; type TAttrActiveIntervalDlg = class(TDateIntervalDlg) Label3: TLabel; GroupBox1: TGroupBox; rbActive: TRadioButton; rbPreactive: TRadioButton; rbNoActive: TRadioButton; rbNotSure: TRadioButton; sbDateCalc: TSpeedButton; edtComment: TevMemo; Button1: TButton; procedure rbActiveClick(Sender: TObject); procedure rbPreactiveClick(Sender: TObject); procedure rbNoActiveClick(Sender: TObject); procedure edtDateLowEnter(Sender: TObject); procedure edtDateHighEnter(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure rbNotSureClick(Sender: TObject); procedure edtCommentDropDown(Sender: TObject); procedure sbDateCalcClick(Sender: TObject); procedure edtCommentKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; function GetAttrActiveInterval(aRec : Tl3Tag; aRecEmpty : Boolean = False) : Boolean; implementation {$INCLUDE ProjectDefine.inc} {$R *.dfm} uses DateUtils, Types, StrShop, l3Date, l3String, InsDWin, D_DateCalc, evFacadTextSource ; function GetAttrActiveInterval(aRec : Tl3Tag; aRecEmpty : Boolean = False) : Boolean; var lStart : Integer; lFinish : Integer; begin with TAttrActiveIntervalDlg.Create(nil) do try with aRec do If aRecEmpty then //aRec.RecID := 0 else begin lStart := IntA[k2_tiStart]; lFinish := IntA[k2_tiFinish]; if (lStart = maxActiveDate) and (lFinish = maxActiveDate) then begin rbPreActive.Checked := True; ActiveControl := rbPreActive; end else if (lStart = minActiveDate) and (lFinish = minActiveDate) then begin rbNoActive.Checked := True; ActiveControl := rbNoActive; end else begin if not ((lStart = minActiveDate) or (lStart = maxActiveDate)) then edtDateLow.StDate := lStart; if not ((lFinish = minActiveDate) or (lFinish = maxActiveDate)) then edtDateHigh.StDate := lFinish; if IntA[k2_tiType] = 1 then begin rbNotSure.Checked := True; //ActiveControl := rbNotSure; end else begin rbActive.Checked := True; //ActiveControl := rbActive; end; end; edtComment.Text := StrA[k2_tiComment]; end; Result := Execute; if Result then with aRec do begin AttrW[k2_tiName, nil] := nil; if rbActive.Checked or rbNotSure.Checked then begin If edtDateLow.IsEmpty then lStart := minActiveDate else lStart := edtDateLow.StDate; if edtDateHigh.IsEmpty then lFinish := maxActiveDate else lFinish := edtDateHigh.StDate; end else if rbPreActive.Checked then begin lStart := maxActiveDate; lFinish := maxActiveDate; end else if rbNoActive.Checked then begin lStart := minActiveDate; lFinish := minActiveDate; end; IntA[k2_tiStart] := lStart; IntA[k2_tiFinish] := lFinish; if rbNotSure.Checked then IntA[k2_tiType] := 1 else IntA[k2_tiType] := 0; StrA[k2_tiComment] := edtComment.Text; end; finally Free; end; end; procedure TAttrActiveIntervalDlg.rbActiveClick(Sender: TObject); begin rbActive.Checked := True; end; procedure TAttrActiveIntervalDlg.rbPreactiveClick(Sender: TObject); begin rbPreActive.Checked := True; edtDateLow.Clear; edtDateHigh.Clear; end; procedure TAttrActiveIntervalDlg.rbNoActiveClick(Sender: TObject); begin rbNoActive.Checked := True; edtDateLow.Clear; edtDateHigh.Clear; end; procedure TAttrActiveIntervalDlg.rbNotSureClick(Sender: TObject); begin rbNotSure.Checked := True; end; procedure TAttrActiveIntervalDlg.edtDateLowEnter(Sender: TObject); begin if rbPreActive.Checked or rbNoActive.Checked then rbActive.Checked := True; end; procedure TAttrActiveIntervalDlg.edtDateHighEnter(Sender: TObject); begin if rbPreActive.Checked or rbNoActive.Checked then rbActive.Checked := True; end; procedure TAttrActiveIntervalDlg.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; CanClose:= True; if (ModalResult = mrOK) and rbNotSure.Checked then begin if rbNotSure.Checked then if edtDateLow.IsEmpty then begin ShowMessage(sidXFieldEmptyErr); ActiveControl := edtDateLow; CanClose := False; Exit; end; { else if edtDateHigh.IsEmpty then begin ShowMessage(sidXFieldEmptyErr); ActiveControl := edtDateHigh; CanClose := False; Exit; end; } if (not edtDateLow.IsEmpty) and (not edtDateHigh.IsEmpty) then begin CanClose:= not (CompareDateTime(edtDateLow.Date, edtDateHigh.Date) = GreaterThanValue); if not CanClose then begin ActiveControl:= edtDateHigh; ShowMessage('Дата начала действия документа не может быть позже даты окончания действия'); end; end; end end; procedure TAttrActiveIntervalDlg.edtCommentDropDown(Sender: TObject); var lInsText : String; begin if GetInsText(lInsText) then edtComment.Text := lInsText; end; procedure TAttrActiveIntervalDlg.sbDateCalcClick(Sender: TObject); var aDate : TStDate; begin aDate := edtDateLow.StDate; if GetCalculateDate(aDate) then edtDateLow.StDate := aDate; end; procedure TAttrActiveIntervalDlg.edtCommentKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Key = VK_DOWN) and (ssAlt in Shift) then edtCommentDropDown(Sender); end; procedure TAttrActiveIntervalDlg.FormShow(Sender: TObject); begin inherited; evSetTextParaLimit(edtComment.TextSource, 1); end; end.
///<summary> This unit contains operating system dependent functions, at least some of them. </summary> unit GX_dzOsUtils; interface uses Windows, SysUtils, Classes; type EOsFunc = class(Exception); EOFNoFileinfo = class(EOsFunc); ///<summary> Reads a file's version information and returns the four parts of the version /// number. /// @param Filename is a string with the name of the file to check /// @param Major is a word returning the major version number /// @param Minor is a word returning the minor version number /// @param Revision is a word returning the revision number /// @param Build is a word returning the build number /// @returns True, if version information was found, /// False if the file does not contain any version information </summary> /// @note: There is also an overloaded version that returns words. function GetFileBuildInfo(_Filename: string; out _Major, _Minor, _Revision, _Build: Integer): Boolean; overload; ///<summary> Reads a file's version information and returns the four parts of the version /// number. /// @param Filename is a string with the name of the file to check /// @param Major is an integer returning the major version number /// @param Minor is an integer returning the minor version number /// @param Revision is an integer returning the revision number /// @param Build is an integer returning the build number /// @returns True, if version information was found, /// False if the file does not contain any version information </summary> /// @note: There is also an overloaded version that returns integers. function GetFileBuildInfo(const _Filename: string; out _Major, _Minor, _Revision, _Build: Word): Boolean; overload; ///<summary> @returns the filename of the current module </summary> function GetModuleFilename: string; overload; function GetModuleFilename(const _Module: Cardinal): string; overload; implementation uses Registry, ShellApi; function GetModuleFilename(const _Module: Cardinal): string; var Buffer: array[0..260] of Char; begin SetString(Result, Buffer, Windows.GetModuleFilename(_Module, Buffer, SizeOf(Buffer))) end; function GetModuleFilename: string; begin Result := GetModuleFilename(HInstance); end; function GetFileBuildInfo(_Filename: string; out _Major, _Minor, _Revision, _Build: Integer): Boolean; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; begin Assert(_Filename <> ''); VerInfoSize := GetFileVersionInfoSize(PChar(_Filename), Dummy); Result := (VerInfoSize <> 0); if Result then begin GetMem(VerInfo, VerInfoSize); try GetFileVersionInfo(PChar(_Filename), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin _Major := dwFileVersionMS shr 16; _Minor := dwFileVersionMS and $FFFF; _Revision := dwFileVersionLS shr 16; _Build := dwFileVersionLS and $FFFF; end; finally FreeMem(VerInfo, VerInfoSize); end; end; end; function GetFileProductInfo(_Filename: string; out _Major, _Minor, _Revision, _Build: Integer): Boolean; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; begin Assert(_Filename <> ''); VerInfoSize := GetFileVersionInfoSize(PChar(_Filename), Dummy); Result := (VerInfoSize <> 0); if Result then begin GetMem(VerInfo, VerInfoSize); try GetFileVersionInfo(PChar(_Filename), 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin _Major := dwProductVersionMS shr 16; _Minor := dwProductVersionMS and $FFFF; _Revision := dwProductVersionLS shr 16; _Build := dwProductVersionLS and $FFFF; end; finally FreeMem(VerInfo, VerInfoSize); end; end; end; function GetFileBuildInfo(const _Filename: string; out _Major, _Minor, _Revision, _Build: Word): Boolean; var Major, Minor, Revision, Build: Integer; begin Result := GetFileBuildInfo(_Filename, Major, Minor, Revision, Build); if Result then begin _Major := Major; _Minor := Minor; _Revision := Revision; _Build := Build; end; end; end.
{ Date Created: 6/2/00 4:10:37 PM } unit InfoTRANCODE_NEWTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoTRANCODE_NEWRecord = record PCode: String[2]; PDescription: String[30]; PGroup: Integer; PCertificateCoverage: Boolean; PActive: Boolean; End; TInfoTRANCODE_NEWBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoTRANCODE_NEWRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoTRANCODE_NEW = (InfoTRANCODE_NEWPrimaryKey); TInfoTRANCODE_NEWTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TIntegerField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: Integer); function GetPGroup:Integer; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetEnumIndex(Value: TEIInfoTRANCODE_NEW); function GetEnumIndex: TEIInfoTRANCODE_NEW; protected procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoTRANCODE_NEWRecord; procedure StoreDataBuffer(ABuffer:TInfoTRANCODE_NEWRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TIntegerField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: Integer read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; published property Active write SetActive; property EnumIndex: TEIInfoTRANCODE_NEW read GetEnumIndex write SetEnumIndex; end; { TInfoTRANCODE_NEWTable } procedure Register; implementation procedure TInfoTRANCODE_NEWTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TIntegerField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; end; { TInfoTRANCODE_NEWTable.CreateFields } procedure TInfoTRANCODE_NEWTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoTRANCODE_NEWTable.SetActive } procedure TInfoTRANCODE_NEWTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoTRANCODE_NEWTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoTRANCODE_NEWTable.SetPGroup(const Value: Integer); begin DFGroup.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPGroup:Integer; begin result := DFGroup.Value; end; procedure TInfoTRANCODE_NEWTable.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoTRANCODE_NEWTable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoTRANCODE_NEWTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 2, N'); Add('Description, String, 30, N'); Add('Group, Integer, 0, N'); Add('CertificateCoverage, Boolean, 0, N'); Add('Active, Boolean, 0, N'); end; end; procedure TInfoTRANCODE_NEWTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoTRANCODE_NEWTable.SetEnumIndex(Value: TEIInfoTRANCODE_NEW); begin case Value of InfoTRANCODE_NEWPrimaryKey : IndexName := ''; end; end; function TInfoTRANCODE_NEWTable.GetDataBuffer:TInfoTRANCODE_NEWRecord; var buf: TInfoTRANCODE_NEWRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; result := buf; end; procedure TInfoTRANCODE_NEWTable.StoreDataBuffer(ABuffer:TInfoTRANCODE_NEWRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; end; function TInfoTRANCODE_NEWTable.GetEnumIndex: TEIInfoTRANCODE_NEW; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoTRANCODE_NEWPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoTRANCODE_NEWTable, TInfoTRANCODE_NEWBuffer ] ); end; { Register } function TInfoTRANCODE_NEWBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('CODE','DESCRIPTION','GROUP','CERTIFICATECOVERAGE','ACTIVE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TInfoTRANCODE_NEWBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftBoolean; 5 : result := ftBoolean; end; end; function TInfoTRANCODE_NEWBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PGroup; 4 : result := @Data.PCertificateCoverage; 5 : result := @Data.PActive; end; end; end.
unit QuickList_QuoteInstant; interface uses QuickSortList, define_stock_quotes_instant; type PInstantQuoteListItem = ^TInstantQuoteListItem; TInstantQuoteListItem = record StockPackCode : integer; InstantQuote : PRT_InstantQuote; end; TQuoteInstantList = class(TALBaseQuickSortList) public function GetItem(Index: Integer): Integer; procedure SetItem(Index: Integer; const AStockPackCode: Integer); function GetInstantQuote(Index: Integer): PRT_InstantQuote; procedure PutInstantQuote(Index: Integer; AInstantQuote: PRT_InstantQuote); public procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure InsertItem(Index: Integer; const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote); function CompareItems(const Index1, Index2: Integer): Integer; override; public function IndexOf(AStockPackCode: Integer): Integer; function IndexOfInstantQuote(AInstantQuote: PRT_InstantQuote): Integer; Function AddInstantQuote(const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote): Integer; function Find(AStockPackCode: Integer; var Index: Integer): Boolean; procedure InsertObject(Index: Integer; const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote); //property Items[Index: Integer]: Integer read GetItem write SetItem; default; property StockPackCode[Index: Integer]: Integer read GetItem write SetItem; default; property InstantQuote[Index: Integer]: PRT_InstantQuote read GetInstantQuote write PutInstantQuote; end; implementation function TQuoteInstantList.AddInstantQuote(const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote): Integer; begin if not Sorted then begin Result := FCount end else if Find(AStockPackCode, Result) then begin case Duplicates of lstDupIgnore: Exit; lstDupError: Error(@SALDuplicateItem, 0); end; end; InsertItem(Result, AStockPackCode, AInstantQuote); end; {*****************************************************************************************} procedure TQuoteInstantList.InsertItem(Index: Integer; const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote); var tmpInstantQuoteListItem: PInstantQuoteListItem; begin New(tmpInstantQuoteListItem); tmpInstantQuoteListItem^.StockPackCode := AStockPackCode; tmpInstantQuoteListItem^.InstantQuote := AInstantQuote; try inherited InsertItem(index, tmpInstantQuoteListItem); except Dispose(tmpInstantQuoteListItem); raise; end; end; {***************************************************************************} function TQuoteInstantList.CompareItems(const Index1, Index2: integer): Integer; begin result := PInstantQuoteListItem(Get(Index1))^.StockPackCode - PInstantQuoteListItem(Get(Index2))^.StockPackCode; end; {***********************************************************************} function TQuoteInstantList.Find(AStockPackCode: Integer; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; C := GetItem(I) - AStockPackCode; if C < 0 then begin L := I + 1 end else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> lstDupAccept then L := I; end; end; end; Index := L; end; {*******************************************************} function TQuoteInstantList.GetItem(Index: Integer): Integer; begin Result := PInstantQuoteListItem(Get(index))^.StockPackCode; end; {******************************************************} function TQuoteInstantList.IndexOf(AStockPackCode: Integer): Integer; begin if not Sorted then Begin Result := 0; while (Result < FCount) and (GetItem(result) <> AStockPackCode) do Inc(Result); if Result = FCount then Result := -1; end else if not Find(AStockPackCode, Result) then Result := -1; end; {*******************************************************************************************} procedure TQuoteInstantList.InsertObject(Index: Integer; const AStockPackCode: integer; AInstantQuote: PRT_InstantQuote); var tmpInstantQuoteListItem: PInstantQuoteListItem; begin New(tmpInstantQuoteListItem); tmpInstantQuoteListItem^.StockPackCode := AStockPackCode; tmpInstantQuoteListItem^.InstantQuote := AInstantQuote; try inherited insert(index, tmpInstantQuoteListItem); except Dispose(tmpInstantQuoteListItem); raise; end; end; {***********************************************************************} procedure TQuoteInstantList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lstDeleted then dispose(ptr); inherited Notify(Ptr, Action); end; {********************************************************************} procedure TQuoteInstantList.SetItem(Index: Integer; const AStockPackCode: Integer); Var aPInstantQuoteListItem: PInstantQuoteListItem; begin New(aPInstantQuoteListItem); aPInstantQuoteListItem^.StockPackCode := AStockPackCode; aPInstantQuoteListItem^.InstantQuote := nil; Try Put(Index, aPInstantQuoteListItem); except Dispose(aPInstantQuoteListItem); raise; end; end; {*********************************************************} function TQuoteInstantList.GetInstantQuote(Index: Integer): PRT_InstantQuote; begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); Result := PInstantQuoteListItem(Get(index))^.InstantQuote; end; {***************************************************************} function TQuoteInstantList.IndexOfInstantQuote(AInstantQuote: PRT_InstantQuote): Integer; begin for Result := 0 to Count - 1 do begin if GetInstantQuote(Result) = AInstantQuote then begin Exit; end; end; Result := -1; end; {*******************************************************************} procedure TQuoteInstantList.PutInstantQuote(Index: Integer; AInstantQuote: PRT_InstantQuote); begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); PInstantQuoteListItem(Get(index))^.InstantQuote := AInstantQuote; end; end.
unit K620665614_C21100713; {* [RequestLink:620665614] } // Модуль: "w:\common\components\rtl\Garant\Daily\K620665614_C21100713.pas" // Стереотип: "TestCase" // Элемент модели: "K620665614_C21100713" MUID: (56FA6CE00222) // Имя типа: "TK620665614_C21100713" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK620665614_C21100713 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:620665614] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK620665614_C21100713 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56FA6CE00222impl_uses* //#UC END# *56FA6CE00222impl_uses* ; function TK620665614_C21100713.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK620665614_C21100713.GetFolder function TK620665614_C21100713.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56FA6CE00222'; end;//TK620665614_C21100713.GetModelElementGUID initialization TestFramework.RegisterTest(TK620665614_C21100713.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit SelectorValuesBaseTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ParserBaseTestCase, ValuesParsingBaseTest, WpcScriptCommons, WpcStatements, WpcScriptParser, WpcExceptions; type { TSelectorValuesBaseTest } TSelectorValuesBaseTest = class abstract(TValuesParsingBaseTest) protected const CHOOSER_ITEM_1 = 'wallpaper.jpg'; CHOOSER_ITEM_2 = 'background.png'; protected SELECTOR_STRING : String; A_SELECTOR_VALUE_STRING : String; A_SELECTOR_VALUE : LongWord; protected SELECTOR_VALUES_STRING : Array of String; SELECTOR_VALUES : Array of LongWord; SELECTOR_VALUES_ALIASES_STRING : Array of String; SELECTOR_VALUES_ALIASES : Array of LongWord; INVALID_SELECTOR_VALUES_STRING : Array of String; public constructor Create(); override; destructor Destroy(); override; protected procedure SetSelectorValuesTestData(SelectorsStrings : Array of String; SelectorValues : Array of LongWord); procedure SetSelectorValuesAliasesTestData(AliasesStrings : Array of String; AliasesValues : Array of LongWord); procedure SetInvalidSelectorValuesStrings(InvalidSelectorsStrings : Array of String); protected function ParseAndGetSelectorValue(ValueString : String) : LongWord; procedure ParseAndEnsureScriptParseException(ValueString : String); procedure ParseAndCheckSelectorValues(SelectorsStrings: Array of String; SelectorsValues: Array of LongWord); published procedure ShouldParseSelectorValue(); procedure ShouldParseSelectorValueByAlias(); procedure ShouldRaiseScriptParseExceptionIfInvalidSelectorValueGiven(); end; implementation { TSelectorValuesBaseTest } constructor TSelectorValuesBaseTest.Create(); begin SELECTOR_VALUES_STRING := nil; SELECTOR_VALUES := nil; SELECTOR_VALUES_ALIASES_STRING := nil; SELECTOR_VALUES_ALIASES := nil; INVALID_SELECTOR_VALUES_STRING := nil; end; destructor TSelectorValuesBaseTest.Destroy(); begin SetLength(SELECTOR_VALUES_STRING, 0); SetLength(SELECTOR_VALUES, 0); SetLength(SELECTOR_VALUES_ALIASES_STRING, 0); SetLength(SELECTOR_VALUES_ALIASES, 0); SetLength(INVALID_SELECTOR_VALUES_STRING, 0); end; procedure TSelectorValuesBaseTest.SetSelectorValuesTestData(SelectorsStrings : Array of String; SelectorValues: Array of LongWord); var i : Integer; Len : Integer; begin if (Length(SelectorsStrings) <> Length(SelectorValues)) then raise TWpcIllegalArgumentException.Create('Test data arrays should have the same length.'); Len := Length(SelectorsStrings); SetLength(SELECTOR_VALUES_STRING, Len); SetLength(SELECTOR_VALUES, Len); for i:=0 to (Len - 1) do begin SELECTOR_VALUES_STRING[i] := SelectorsStrings[i]; SELECTOR_VALUES[i] := SelectorValues[i]; end; end; procedure TSelectorValuesBaseTest.SetSelectorValuesAliasesTestData(AliasesStrings : Array of String; AliasesValues : Array of LongWord); var i : Integer; Len : Integer; begin if (Length(AliasesStrings) <> Length(AliasesValues)) then raise TWpcIllegalArgumentException.Create('Test data arrays should have the same length.'); Len := Length(AliasesStrings); SetLength(SELECTOR_VALUES_ALIASES_STRING, Len); SetLength(SELECTOR_VALUES_ALIASES, Len); for i:=0 to (Len - 1) do begin SELECTOR_VALUES_ALIASES_STRING[i] := AliasesStrings[i]; SELECTOR_VALUES_ALIASES[i] := AliasesValues[i]; end; end; procedure TSelectorValuesBaseTest.SetInvalidSelectorValuesStrings(InvalidSelectorsStrings : Array of String); var i : Integer; Len : Integer; begin Len := Length(InvalidSelectorsStrings); SetLength(INVALID_SELECTOR_VALUES_STRING, Len); for i:=0 to (Len - 1) do INVALID_SELECTOR_VALUES_STRING[i] := InvalidSelectorsStrings[i]; end; function TSelectorValuesBaseTest.ParseAndGetSelectorValue(ValueString : String) : LongWord; var ChooserItems : TListOfChooserItems; begin if (ScriptLines <> nil) then FreeAndNil(ScriptLines); ScriptLines := TStringList.Create(); try ScriptLines.Add(CHOOSE_KEYWORD + ' ' + WALLPAPER_KEYWORD + ' ' + BY_KEYWORD + ' ' + SELECTOR_STRING + ' ' + FROM_KEYWORD); ScriptLines.Add(CHOOSER_ITEM_1 + ' ' + SELECTOR_STRING + ' ' + A_SELECTOR_VALUE_STRING); ScriptLines.Add(CHOOSER_ITEM_2 + ' ' + SELECTOR_STRING + ' ' + ValueString); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_CHOOSER_STATEMENT_ID = MainBranchStatements[0].GetId()); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, A_SELECTOR_VALUE, ChooserItems[0].Weight); Result := ChooserItems[1].Weight; finally FreeAndNil(ScriptLines); FreeAndNil(Script); end; end; procedure TSelectorValuesBaseTest.ParseAndCheckSelectorValues(SelectorsStrings: Array of String; SelectorsValues: Array of LongWord); var i : Integer; Len : Integer; ChooserItems : TListOfChooserItems; begin if (Length(SelectorsStrings) <> Length(SelectorsValues)) then raise TWpcIllegalArgumentException.Create('Test data arrays should have the same length.'); if (ScriptLines <> nil) then FreeAndNil(ScriptLines); ScriptLines := TStringList.Create(); try Len := Length(SelectorsValues); ScriptLines.Add(CHOOSE_KEYWORD + ' ' + WALLPAPER_KEYWORD + ' ' + BY_KEYWORD + ' ' + SELECTOR_STRING + ' ' + FROM_KEYWORD); for i:=0 to (Len - 1) do ScriptLines.Add(CHOOSER_ITEM_1 + ' ' + SELECTOR_STRING + ' ' + SelectorsStrings[i]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_WALLPAPER_CHOOSER_STATEMENT_ID = MainBranchStatements[0].GetId()); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, Len, ChooserItems.Count); for i:=0 to (Len - 1) do AssertEquals(WRONG_SELECTOR_VALUE, SelectorsValues[i], ChooserItems[i].Weight); finally FreeAndNil(ScriptLines); FreeAndNil(Script); end; end; procedure TSelectorValuesBaseTest.ParseAndEnsureScriptParseException(ValueString : String); begin if (ScriptLines <> nil) then FreeAndNil(ScriptLines); ScriptLines := TStringList.Create(); try ScriptLines.Add(CHOOSE_KEYWORD + ' ' + WALLPAPER_KEYWORD + ' ' + BY_KEYWORD + ' ' + SELECTOR_STRING + ' ' + FROM_KEYWORD); ScriptLines.Add(CHOOSER_ITEM_1 + ' ' + SELECTOR_STRING + ' ' + A_SELECTOR_VALUE_STRING); ScriptLines.Add(CHOOSER_ITEM_2 + ' ' + SELECTOR_STRING + ' ' + ValueString); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AssertScriptParseExceptionOnParse(3); finally FreeAndNil(ScriptLines); end; end; procedure TSelectorValuesBaseTest.ShouldParseSelectorValue(); var i : Integer; begin for i:=0 to (Length(SELECTOR_VALUES_STRING) - 1) do begin AssertEquals(FAILED_TO_PARSE + SELECTOR_VALUES_STRING[i], SELECTOR_VALUES[i], ParseAndGetSelectorValue(SELECTOR_VALUES_STRING[i])); end; end; procedure TSelectorValuesBaseTest.ShouldParseSelectorValueByAlias(); var i : Integer; begin for i:=0 to (Length(SELECTOR_VALUES_ALIASES) - 1) do begin AssertEquals(FAILED_TO_PARSE + SELECTOR_VALUES_ALIASES_STRING[i], SELECTOR_VALUES_ALIASES[i], ParseAndGetSelectorValue(SELECTOR_VALUES_ALIASES_STRING[i])); end; end; procedure TSelectorValuesBaseTest.ShouldRaiseScriptParseExceptionIfInvalidSelectorValueGiven; var i : Integer; begin for i:=0 to (Length(INVALID_SELECTOR_VALUES_STRING) - 1) do begin ParseAndEnsureScriptParseException(INVALID_SELECTOR_VALUES_STRING[i]); end; end; end.
unit CDOClass; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CDOCons, comobj, variants, Dialogs,CDO_1_0_TLB, uFrmSplash; type TSMTP = (sNone,sGmail,sHotmail,sOutlook,sYahoo); TCDOMessage = Class; TCDOServer = Class; { TCDOServer } TCDOServer = class(TComponent) private FActive: Boolean; FSchema: String; FSendPassword: String; FSendUserName: String; FSendUsing: Integer; FSMTP: TSMTP; FSMTPAuthenticate: Boolean; FSMTPconnectionTimeOut: Integer; FSMTPServer: String; FSMTPServerPort: Integer; FSMTPUseSSL: Boolean; procedure SetActive(AValue: Boolean); procedure SetSchema(AValue: String); procedure SetSendPassword(AValue: String); procedure SetSendUserName(AValue: String); procedure SetSendUsing(AValue: Integer); procedure SetSMTP(AValue: TSMTP); procedure SetSMTPAuthenticate(AValue: Boolean); procedure SetSMTPconnectionTimeOut(AValue: Integer); procedure SetSMTPServer(AValue: String); procedure SetSMTPServerPort(AValue: Integer); procedure SetSMTPUseSSL(AValue: Boolean); function GetDefaultSchema : String; function GetActive : Boolean; { Private declarations } protected { Protected declarations } procedure SetConfig; public { Public declarations } SHandle : IConfiguration; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Open; virtual; procedure Close; virtual; property Schema : String read FSchema write SetSchema; published { Published declarations } property SMTPServer : String read FSMTPServer write SetSMTPServer; property SMTPServerPort : Integer read FSMTPServerPort write SetSMTPServerPort; property SendUsing : Integer read FSendUsing write SetSendUsing; property SMTPAuthenticate : Boolean read FSMTPAuthenticate write SetSMTPAuthenticate; property SMTPUseSSL : Boolean read FSMTPUseSSL write SetSMTPUseSSL; property SendUserName : String read FSendUserName write SetSendUserName; property SendPassword : String read FSendPassword write SetSendPassword; property SMTPconnectionTimeOut : Integer read FSMTPconnectionTimeOut write SetSMTPconnectionTimeOut; property Active : Boolean read GetActive write SetActive; property SMTP : TSMTP read FSMTP write SetSMTP; end; { TCDOMessage } TCDOMessage = class(TComponent) private FBCC: WideString; FCC: WideString; FFrom: WideString; FHTMLBody: WideString; FServerConfig: TCDOServer; FSubject: WideString; FTextBody: WideString; FTo_: WideString; FOnSend : TNotifyEvent; procedure SetBCC(AValue: WideString); procedure SetCC(AValue: WideString); procedure SetFrom(AValue: WideString); procedure SetHTMLBody(AValue: WideString); procedure SetServerConfig(AValue: TCDOServer); procedure SetSubject(AValue: WideString); procedure SetTextBody(AValue: WideString); procedure SetTo_(AValue: WideString); { Private declarations } protected { Protected declarations } procedure CreateMHandle; procedure ShowLoading; procedure HideLoading; public { Public declarations } MHandle : IMessage; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Send;virtual; procedure AddAttachment(URL : WideString); published { Published declarations } property ServerConfig : TCDOServer read FServerConfig write FServerConfig; property From : WideString read FFrom write SetFrom; property To_ : WideString read FTo_ write SetTo_; property CC : WideString read FCC write SetCC; property BCC : WideString read FBCC write SetBCC; property Subject : WideString read FSubject write SetSubject; property TextBody : WideString read FTextBody write SetTextBody; property HTMLBody : WideString read FHTMLBody write SetHTMLBody; property OnSend : TNotifyEvent read FOnSend write FOnSend; end; implementation {$I CDOClass.inc} end.
{ Subroutine SST_R_PAS_PROC_ARGS (PROC) * * Process the PARAMETER_DECLARATION syntax. PROC is the top level descriptor * for a routine (PROCEDURE or FUNCTION). The routine arguments chain will be * created and PROC.FIRST_ARG_P will point to the start of the arguments chain. * PROC.FIRST_ARG_P will be set to NIL if there are no arguments. PROC.N_ARGS * will be set to the number of arguments. } module sst_r_pas_PROC_ARGS; define sst_r_pas_proc_args; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_proc_args ( {process PARAMETER_DECLARATION syntax} in out proc: sst_proc_t); {top level procedure descriptor} var next_pp: ^sst_proc_arg_p_t; {pointer to current end of args chain pointer} tag: sys_int_machine_t; {syntax tag from .syn file} str_h: syo_string_t; {handle to string for a tag} arg_p: sst_proc_arg_p_t; {pointer to current arg descriptor} first_arg_p: sst_proc_arg_p_t; {points to first arg of same data type} arg: sst_proc_arg_t; {template for current argument descriptor} name: string_var80_t; {current call argument name} sz: sys_int_adr_t; {for calculating memory size} label group_loop, tag_loop; begin name.max := sizeof(name.str); {init var string} proc.n_args := 0; {init number of arguments found} proc.first_arg_p := nil; {init arguments chain to empty} next_pp := addr(proc.first_arg_p); {set pointer to current end of chain pointer} arg.next_p := nil; {init static fields in arg template} arg.sym_p := nil; arg.name_p := nil; arg.exp_p := nil; arg.dtype_p := nil; syo_level_down; {down into PARAMETER_DECLARATION syntax} group_loop: {back here for each new args group tag} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'proc_arg_decl_bad', nil, 0); if tag = syo_tag_end_k then begin {all done, no more argument declarations ?} syo_level_up; {up from PARAMETER_DECLARATION syntax} return; end; if tag <> 1 then begin syo_error_tag_unexp (tag, str_h); end; arg.pass := sst_pass_none_k; {default to passing method not yet known} arg.rwflag_int := []; {default to pass direction not specified} arg.rwflag_ext := []; arg.univ := false; {init to type checking not disabled} first_arg_p := nil; {init to no new arg created yet} syo_level_down; {down into PARAM_DECL_GROUP syntax} tag_loop: {back here each new tag in PARAM_DECL_GROUP} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'proc_arg_decl_bad', nil, 0); case tag of {what pass direction is specified ?} 1: begin {IN} arg.pass := sst_pass_ref_k; arg.rwflag_int := arg.rwflag_int + [sst_rwflag_read_k]; arg.rwflag_ext := arg.rwflag_int; {rout sees same permission as caller} end; 2: begin {OUT} arg.pass := sst_pass_ref_k; arg.rwflag_int := arg.rwflag_int + [sst_rwflag_write_k]; arg.rwflag_ext := arg.rwflag_int; {rout sees same permission as caller} end; 3: begin {VAR} arg.pass := sst_pass_ref_k; arg.rwflag_int := arg.rwflag_int + [sst_rwflag_read_k, sst_rwflag_write_k]; arg.rwflag_ext := arg.rwflag_int; {rout sees same permission as caller} end; 4: begin {tag is argument name} if arg.pass = sst_pass_none_k then begin {no passing mode keyword given ?} arg.pass := sst_pass_refcpy_k; {passed by reference, but rout makes copy} arg.rwflag_int := {all access is allowed to local copy} [sst_rwflag_read_k, sst_rwflag_write_k]; arg.rwflag_ext := [sst_rwflag_read_k]; {caller's arg will not be altered} end; sst_mem_alloc_scope (sizeof(arg_p^), arg_p); {allocate argument descriptor} if first_arg_p = nil then begin {this is first arg for this data type ?} first_arg_p := arg_p; {save pointer to first new arg in chain} end; next_pp^ := arg_p; {link new arg to end of old chain} next_pp := addr(arg_p^.next_p); {update pointer to new end of chain pointer} arg_p^ := arg; {init new arg descriptor from template} syo_get_tag_string (str_h, name); {get name of this call argument} string_downcase (name); sz := sizeof(string_var4_t) - 4 + name.len; {size of string to allocate} sst_mem_alloc_scope (sz, arg_p^.name_p); {allocate argument name string} arg_p^.name_p^.max := name.len; {copy name into newly allocated string} string_copy (name, arg_p^.name_p^); end; 5: begin {UNIV} arg.univ := true; end; 6: begin {tag is data type for previous arguments} arg.dtype_p := nil; {indicate to create new data type descriptor} sst_r_pas_data_type (arg.dtype_p); {make data type for this group of args} end; 7: begin {VAL} arg.pass := sst_pass_val_k; {caller will pass arg by value} arg.rwflag_int := {rout will make local copy, any access OK} [sst_rwflag_read_k, sst_rwflag_write_k]; arg.rwflag_ext := [sst_rwflag_read_k]; {caller's arg will not be altered} end; syo_tag_end_k: begin {no more tags in PARAM_DECL_GROUP} arg_p := first_arg_p; {init to first arg with this data type} while arg_p <> nil do begin {once for each arg with this data type} proc.n_args := proc.n_args + 1; {count one more call argument} arg_p^.dtype_p := arg.dtype_p; {point arg to its data type descriptor} arg_p^.univ := arg.univ; {update type checking disable flag} arg_p := arg_p^.next_p; {advance to next arg with this data type} end; syo_level_up; {up from PARAM_DECL_GROUP syntax} goto group_loop; {do next group of args with same data type} end; otherwise syo_error_tag_unexp (tag, str_h); end; {end of PARAM_DECL_GROUP tag cases} goto tag_loop; {back for next PARAM_DECL_GROUP tag} end;
unit DcefB_BasicEvents; interface uses Windows, Classes, Controls, Dcef3_cefgui, Dcef3_ceflib; type TOnProcessMessageReceived = procedure(const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage; out Result: Boolean) of object; TOnLoadingStateChange = procedure(const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean) of object; TOnLoadStart = procedure(const browser: ICefBrowser; const frame: ICefFrame) of object; TOnLoadEnd = procedure(const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer) of object; TOnLoadError = procedure(const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring) of object; TOnRenderProcessTerminated = procedure(const browser: ICefBrowser; status: TCefTerminationStatus) of object; TOnPluginCrashed = procedure(const browser: ICefBrowser; const pluginPath: ustring) of object; TOnTakeFocus = procedure(const browser: ICefBrowser; next: Boolean) of object; TOnSetFocus = procedure(const browser: ICefBrowser; source: TCefFocusSource; out Result: Boolean) of object; TOnGotFocus = procedure(const browser: ICefBrowser) of object; TOnBeforeContextMenu = procedure(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel) of object; TOnContextMenuCommand = procedure(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; out Result: Boolean) of object; TOnContextMenuDismissed = procedure(const browser: ICefBrowser; const frame: ICefFrame) of object; TOnPreKeyEvent = procedure(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean; out Result: Boolean) of object; TOnKeyEvent = procedure(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out Result: Boolean) of object; TOnAddressChange = procedure(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring) of object; TOnTitleChange = procedure(const browser: ICefBrowser; const title: ustring) of object; TOnTooltip = procedure(const browser: ICefBrowser; var text: ustring; out Result: Boolean) of object; TOnStatusMessage = procedure(const browser: ICefBrowser; const value: ustring) of object; TOnConsoleMessage = procedure(const browser: ICefBrowser; const message, source: ustring; line: Integer; out Result: Boolean) of object; TOnBeforeDownload = procedure(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback) of object; TOnDownloadUpdated = procedure(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback) of object; TOnRequestGeolocationPermission = procedure(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean) of object; TOnCancelGeolocationPermission = procedure(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer) of object; TOnJsdialog = procedure(const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; callback: ICefJsDialogCallback; out suppressMessage: Boolean; out Result: Boolean) of object; TOnBeforeUnloadDialog = procedure(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback; out Result: Boolean) of object; TOnResetDialogState = procedure(const browser: ICefBrowser) of object; TOnDialogClosed = procedure(const browser: ICefBrowser) of object; TOnBeforePopup = procedure(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean; out Result: Boolean) of object; TOnAfterCreated = procedure(const browser: ICefBrowser) of object; TOnBeforeClose = procedure(const browser: ICefBrowser) of object; TOnRunModal = procedure(const browser: ICefBrowser; out Result: Boolean) of object; TOnClose = procedure(const browser: ICefBrowser; out Result: Boolean) of object; TOnBeforeBrowse = procedure(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; out Result: Boolean) of object; TOnBeforeResourceLoad = procedure(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; out Result: Boolean) of object; TOnGetResourceHandler = procedure(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; out Result: ICefResourceHandler) of object; TOnResourceRedirect = procedure(const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring) of object; TOnGetAuthCredentials = procedure(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; out Result: Boolean) of object; TOnQuotaRequest = procedure(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback; out Result: Boolean) of object; TOnProtocolExecution = procedure(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean) of object; TOnBeforePluginLoad = procedure(const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo; out Result: Boolean) of object; TOnFileDialog = procedure(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback; out Result: Boolean) of object; TOnDragEnter = procedure(const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean) of object; TOnStartDragging = procedure(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean) of object; TOnUpdateDragCursor = procedure(const browser: ICefBrowser; operation: TCefDragOperation) of object; TOnCertificateError = procedure(certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback; out Result: Boolean) of object; TOnCursorChange = procedure(const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo) of object; { TOnGetRootScreenRect = procedure(const browser: ICefBrowser; rect: PCefRect; out Result: Boolean); TOnGetViewRect = procedure(const browser: ICefBrowser; rect: PCefRect; out Result: Boolean); TOnGetScreenPoint = procedure(const browser: ICefBrowser; viewX, viewY: Integer; screenX, screenY: PInteger; out Result: Boolean); TOnGetScreenInfo = procedure(const browser: ICefBrowser; screenInfo: PCefScreenInfo; Result: Boolean); TOnPopupShow = procedure(const browser: ICefBrowser; show: Boolean); TOnPopupSize = procedure(const browser: ICefBrowser; const rect: PCefRect); TOnPaint = procedure(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); TOnScrollOffsetChanged = procedure(const browser: ICefBrowser); } TBasicDcefBrowserEvents = class(TInterfacedObject, IChromiumEvents) private FOnProcessMessageReceived: TOnProcessMessageReceived; FOnLoadStart: TOnLoadStart; FOnLoadEnd: TOnLoadEnd; FOnLoadError: TOnLoadError; FOnRenderProcessTerminated: TOnRenderProcessTerminated; FOnPluginCrashed: TOnPluginCrashed; FOnTakeFocus: TOnTakeFocus; FOnSetFocus: TOnSetFocus; FOnGotFocus: TOnGotFocus; FOnBeforeContextMenu: TOnBeforeContextMenu; FOnContextMenuCommand: TOnContextMenuCommand; FOnContextMenuDismissed: TOnContextMenuDismissed; FOnPreKeyEvent: TOnPreKeyEvent; FOnKeyEvent: TOnKeyEvent; FOnLoadingStateChange: TOnLoadingStateChange; FOnAddressChange: TOnAddressChange; FOnTitleChange: TOnTitleChange; FOnTooltip: TOnTooltip; FOnStatusMessage: TOnStatusMessage; FOnConsoleMessage: TOnConsoleMessage; FOnBeforeDownload: TOnBeforeDownload; FOnDownloadUpdated: TOnDownloadUpdated; FOnRequestGeolocationPermission: TOnRequestGeolocationPermission; FOnCancelGeolocationPermission: TOnCancelGeolocationPermission; FOnJsdialog: TOnJsdialog; FOnBeforeUnloadDialog: TOnBeforeUnloadDialog; FOnResetDialogState: TOnResetDialogState; FOnDialogClosed: TOnDialogClosed; FOnBeforePopup: TOnBeforePopup; FOnAfterCreated: TOnAfterCreated; FOnBeforeClose: TOnBeforeClose; FOnRunModal: TOnRunModal; FOnClose: TOnClose; FOnBeforeBrowse: TOnBeforeBrowse; FOnBeforeResourceLoad: TOnBeforeResourceLoad; FOnGetResourceHandler: TOnGetResourceHandler; FOnResourceRedirect: TOnResourceRedirect; FOnGetAuthCredentials: TOnGetAuthCredentials; FOnQuotaRequest: TOnQuotaRequest; FOnProtocolExecution: TOnProtocolExecution; FOnBeforePluginLoad: TOnBeforePluginLoad; FOnFileDialog: TOnFileDialog; FOnDragEnter: TOnDragEnter; FOnStartDragging: TOnStartDragging; FOnUpdateDragCursor: TOnUpdateDragCursor; FOnCertificateError: TOnCertificateError; FOnCursorChange: TOnCursorChange; protected procedure GetSettings(var settings: TCefBrowserSettings); function doOnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage) : Boolean; virtual; procedure doOnLoadStart(const browser: ICefBrowser; const frame: ICefFrame); virtual; procedure doOnLoadEnd(const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); virtual; procedure doOnLoadError(const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring); virtual; procedure doOnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus); virtual; procedure doOnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); virtual; procedure doOnTakeFocus(const browser: ICefBrowser; next: Boolean); virtual; function doOnSetFocus(const browser: ICefBrowser; source: TCefFocusSource) : Boolean; virtual; procedure doOnGotFocus(const browser: ICefBrowser); virtual; procedure doOnBeforeContextMenu(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); virtual; function doOnContextMenuCommand(const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean; virtual; procedure doOnContextMenuDismissed(const browser: ICefBrowser; const frame: ICefFrame); virtual; function doOnPreKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean): Boolean; virtual; function doOnKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle): Boolean; virtual; procedure doOnLoadingStateChange(const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); virtual; procedure doOnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); virtual; procedure doOnTitleChange(const browser: ICefBrowser; const title: ustring); virtual; function doOnTooltip(const browser: ICefBrowser; var text: ustring) : Boolean; virtual; procedure doOnStatusMessage(const browser: ICefBrowser; const value: ustring); virtual; function doOnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean; virtual; procedure doOnBeforeDownload(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); virtual; procedure doOnDownloadUpdated(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); virtual; function doOnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; virtual; procedure doOnCancelGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer); virtual; function doOnJsdialog(const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; callback: ICefJsDialogCallback; out suppressMessage: Boolean) : Boolean; virtual; function doOnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean; virtual; procedure doOnResetDialogState(const browser: ICefBrowser); virtual; procedure doOnDialogClosed(const browser: ICefBrowser); virtual; function doOnBeforePopup(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean): Boolean; virtual; procedure doOnAfterCreated(const browser: ICefBrowser); virtual; procedure doOnBeforeClose(const browser: ICefBrowser); virtual; function doOnRunModal(const browser: ICefBrowser): Boolean; virtual; function doOnClose(const browser: ICefBrowser): Boolean; virtual; function doOnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean) : Boolean; virtual; function doOnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): Boolean; virtual; function doOnGetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest) : ICefResourceHandler; virtual; procedure doOnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring); virtual; function doOnGetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; virtual; function doOnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback): Boolean; virtual; procedure doOnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean); virtual; function doOnBeforePluginLoad(const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo) : Boolean; virtual; function doOnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback): Boolean; function doOnGetRootScreenRect(const browser: ICefBrowser; rect: PCefRect): Boolean; function doOnGetViewRect(const browser: ICefBrowser; rect: PCefRect): Boolean; function doOnGetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; screenX, screenY: PInteger): Boolean; function doOnGetScreenInfo(const browser: ICefBrowser; screenInfo: PCefScreenInfo): Boolean; procedure doOnPopupShow(const browser: ICefBrowser; show: Boolean); procedure doOnPopupSize(const browser: ICefBrowser; const rect: PCefRect); procedure doOnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); procedure doOnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); procedure doOnScrollOffsetChanged(const browser: ICefBrowser); function doOnDragEnter(const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations): Boolean; function doOnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean; procedure doOnUpdateDragCursor(const browser: ICefBrowser; operation: TCefDragOperation); function doOnCertificateError(certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback): Boolean; public destructor Destroy; override; property OnProcessMessageReceived: TOnProcessMessageReceived read FOnProcessMessageReceived write FOnProcessMessageReceived; property OnLoadStart: TOnLoadStart read FOnLoadStart write FOnLoadStart; property OnLoadEnd: TOnLoadEnd read FOnLoadEnd write FOnLoadEnd; property OnLoadError: TOnLoadError read FOnLoadError write FOnLoadError; property OnRenderProcessTerminated: TOnRenderProcessTerminated read FOnRenderProcessTerminated write FOnRenderProcessTerminated; property OnPluginCrashed: TOnPluginCrashed read FOnPluginCrashed write FOnPluginCrashed; property OnSetFocus: TOnSetFocus read FOnSetFocus write FOnSetFocus; property OnGotFocus: TOnGotFocus read FOnGotFocus write FOnGotFocus; property OnTakeFocus: TOnTakeFocus read FOnTakeFocus write FOnTakeFocus; property OnBeforeContextMenu: TOnBeforeContextMenu read FOnBeforeContextMenu write FOnBeforeContextMenu; property OnContextMenuCommand: TOnContextMenuCommand read FOnContextMenuCommand write FOnContextMenuCommand; property OnContextMenuDismissed: TOnContextMenuDismissed read FOnContextMenuDismissed write FOnContextMenuDismissed; property OnPreKeyEvent: TOnPreKeyEvent read FOnPreKeyEvent write FOnPreKeyEvent; property OnKeyEvent: TOnKeyEvent read FOnKeyEvent write FOnKeyEvent; property OnLoadingStateChange: TOnLoadingStateChange read FOnLoadingStateChange write FOnLoadingStateChange; property OnAddressChange: TOnAddressChange read FOnAddressChange write FOnAddressChange; property OnTitleChange: TOnTitleChange read FOnTitleChange write FOnTitleChange; property OnTooltip: TOnTooltip read FOnTooltip write FOnTooltip; property OnStatusMessage: TOnStatusMessage read FOnStatusMessage write FOnStatusMessage; property OnConsoleMessage: TOnConsoleMessage read FOnConsoleMessage write FOnConsoleMessage; property OnBeforeDownload: TOnBeforeDownload read FOnBeforeDownload write FOnBeforeDownload; property OnDownloadUpdated: TOnDownloadUpdated read FOnDownloadUpdated write FOnDownloadUpdated; property OnRequestGeolocationPermission: TOnRequestGeolocationPermission read FOnRequestGeolocationPermission write FOnRequestGeolocationPermission; property OnCancelGeolocationPermission: TOnCancelGeolocationPermission read FOnCancelGeolocationPermission write FOnCancelGeolocationPermission; property OnJsdialog: TOnJsdialog read FOnJsdialog write FOnJsdialog; property OnBeforeUnloadDialog: TOnBeforeUnloadDialog read FOnBeforeUnloadDialog write FOnBeforeUnloadDialog; property OnResetDialogState: TOnResetDialogState read FOnResetDialogState write FOnResetDialogState; property OnDialogClosed: TOnDialogClosed read FOnDialogClosed write FOnDialogClosed; property OnBeforePopup: TOnBeforePopup read FOnBeforePopup write FOnBeforePopup; property OnAfterCreated: TOnAfterCreated read FOnAfterCreated write FOnAfterCreated; property OnBeforeClose: TOnBeforeClose read FOnBeforeClose write FOnBeforeClose; property OnRunModal: TOnRunModal read FOnRunModal write FOnRunModal; property OnClose: TOnClose read FOnClose write FOnClose; property OnBeforeBrowse: TOnBeforeBrowse read FOnBeforeBrowse write FOnBeforeBrowse; property OnBeforeResourceLoad: TOnBeforeResourceLoad read FOnBeforeResourceLoad write FOnBeforeResourceLoad; property OnGetResourceHandler: TOnGetResourceHandler read FOnGetResourceHandler write FOnGetResourceHandler; property OnResourceRedirect: TOnResourceRedirect read FOnResourceRedirect write FOnResourceRedirect; property OnGetAuthCredentials: TOnGetAuthCredentials read FOnGetAuthCredentials write FOnGetAuthCredentials; property OnQuotaRequest: TOnQuotaRequest read FOnQuotaRequest write FOnQuotaRequest; property OnProtocolExecution: TOnProtocolExecution read FOnProtocolExecution write FOnProtocolExecution; property OnBeforePluginLoad: TOnBeforePluginLoad read FOnBeforePluginLoad write FOnBeforePluginLoad; property OnFileDialog: TOnFileDialog read FOnFileDialog write FOnFileDialog; property OnDragEnter: TOnDragEnter read FOnDragEnter write FOnDragEnter; property OnStartDragging: TOnStartDragging read FOnStartDragging write FOnStartDragging; property OnUpdateDragCursor: TOnUpdateDragCursor read FOnUpdateDragCursor write FOnUpdateDragCursor; property OnCertificateError: TOnCertificateError read FOnCertificateError write FOnCertificateError; property OnCursorChange: TOnCursorChange read FOnCursorChange write FOnCursorChange; end; implementation { TBrowserEvents } procedure TBasicDcefBrowserEvents.GetSettings(var settings : TCefBrowserSettings); begin end; destructor TBasicDcefBrowserEvents.Destroy; begin inherited; end; procedure TBasicDcefBrowserEvents.doOnAddressChange(const browser: ICefBrowser; const frame: ICefFrame; const url: ustring); begin if Assigned(FOnAddressChange) then FOnAddressChange(browser, frame, url); end; procedure TBasicDcefBrowserEvents.doOnAfterCreated(const browser: ICefBrowser); begin if Assigned(FOnAfterCreated) then FOnAfterCreated(browser); end; function TBasicDcefBrowserEvents.doOnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean; begin Result := False; if Assigned(FOnBeforeBrowse) then FOnBeforeBrowse(browser, frame, request, isRedirect, Result); end; procedure TBasicDcefBrowserEvents.doOnBeforeClose(const browser: ICefBrowser); begin if Assigned(FOnBeforeClose) then FOnBeforeClose(browser); end; procedure TBasicDcefBrowserEvents.doOnBeforeContextMenu(const browser : ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); begin if Assigned(FOnBeforeContextMenu) then FOnBeforeContextMenu(browser, frame, params, model); end; procedure TBasicDcefBrowserEvents.doOnBeforeDownload(const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); begin if Assigned(FOnBeforeDownload) then FOnBeforeDownload(browser, downloadItem, suggestedName, callback); end; function TBasicDcefBrowserEvents.doOnBeforePluginLoad(const browser : ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo): Boolean; begin Result := False; if Assigned(FOnBeforePluginLoad) then FOnBeforePluginLoad(browser, url, policyUrl, info, Result); end; function TBasicDcefBrowserEvents.doOnBeforePopup(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; var popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var noJavascriptAccess: Boolean): Boolean; begin Result := False; if Assigned(FOnBeforePopup) then FOnBeforePopup(browser, frame, targetUrl, targetFrameName, popupFeatures, windowInfo, client, settings, noJavascriptAccess, Result); end; function TBasicDcefBrowserEvents.doOnBeforeResourceLoad(const browser : ICefBrowser; const frame: ICefFrame; const request: ICefRequest): Boolean; begin Result := False; if Assigned(FOnBeforeResourceLoad) then FOnBeforeResourceLoad(browser, frame, request, Result); end; function TBasicDcefBrowserEvents.doOnBeforeUnloadDialog(const browser : ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean; begin Result := False; if Assigned(FOnBeforeUnloadDialog) then FOnBeforeUnloadDialog(browser, messageText, isReload, callback, Result); end; procedure TBasicDcefBrowserEvents.doOnCancelGeolocationPermission (const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer); begin if Assigned(FOnCancelGeolocationPermission) then FOnCancelGeolocationPermission(browser, requestingUrl, requestId); end; function TBasicDcefBrowserEvents.doOnCertificateError(certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback): Boolean; begin Result := False; if Assigned(FOnCertificateError) then FOnCertificateError(certError, requestUrl, callback, Result); end; function TBasicDcefBrowserEvents.doOnClose(const browser: ICefBrowser): Boolean; begin Result := False; if Assigned(FOnClose) then FOnClose(browser, Result); end; function TBasicDcefBrowserEvents.doOnConsoleMessage(const browser: ICefBrowser; const message, source: ustring; line: Integer): Boolean; begin Result := False; if Assigned(FOnConsoleMessage) then FOnConsoleMessage(browser, message, source, line, Result); end; function TBasicDcefBrowserEvents.doOnContextMenuCommand(const browser : ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags): Boolean; begin Result := False; if Assigned(FOnContextMenuCommand) then FOnContextMenuCommand(browser, frame, params, commandId, eventFlags, Result); end; procedure TBasicDcefBrowserEvents.doOnContextMenuDismissed (const browser: ICefBrowser; const frame: ICefFrame); begin if Assigned(FOnContextMenuDismissed) then FOnContextMenuDismissed(browser, frame); end; procedure TBasicDcefBrowserEvents.doOnCursorChange(const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); begin if Assigned(FOnCursorChange) then FOnCursorChange(browser, cursor, cursorType, customCursorInfo); end; procedure TBasicDcefBrowserEvents.doOnDialogClosed(const browser: ICefBrowser); begin if Assigned(FOnDialogClosed) then FOnDialogClosed(browser); end; procedure TBasicDcefBrowserEvents.doOnDownloadUpdated(const browser : ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); begin if Assigned(FOnDownloadUpdated) then FOnDownloadUpdated(browser, downloadItem, callback); end; function TBasicDcefBrowserEvents.doOnDragEnter(const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations): Boolean; begin Result := False; if Assigned(FOnDragEnter) then FOnDragEnter(browser, dragData, mask, Result); end; function TBasicDcefBrowserEvents.doOnFileDialog(const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback): Boolean; begin Result := False; if Assigned(FOnFileDialog) then FOnFileDialog(browser, mode, title, defaultFileName, acceptTypes, callback, Result); end; function TBasicDcefBrowserEvents.doOnGetAuthCredentials(const browser : ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; begin Result := False; if Assigned(FOnGetAuthCredentials) then FOnGetAuthCredentials(browser, frame, isProxy, host, port, realm, scheme, callback, Result); end; function TBasicDcefBrowserEvents.doOnGetResourceHandler(const browser : ICefBrowser; const frame: ICefFrame; const request: ICefRequest) : ICefResourceHandler; begin if Assigned(FOnGetResourceHandler) then FOnGetResourceHandler(browser, frame, request, Result) else Result := nil; end; function TBasicDcefBrowserEvents.doOnGetRootScreenRect(const browser : ICefBrowser; rect: PCefRect): Boolean; begin Result := False; { if Assigned(FOnGetRootScreenRect) then FOnGetRootScreenRect(Self, browser, rect, Result); } end; function TBasicDcefBrowserEvents.doOnGetScreenInfo(const browser: ICefBrowser; screenInfo: PCefScreenInfo): Boolean; begin Result := False; { if Assigned(FOnGetScreenInfo) then FOnGetScreenInfo(Self, browser, screenInfo, Result); } end; function TBasicDcefBrowserEvents.doOnGetScreenPoint(const browser: ICefBrowser; viewX, viewY: Integer; screenX, screenY: PInteger): Boolean; begin Result := False; { if Assigned(FOnGetScreenPoint) then FOnGetScreenPoint(Self, browser, viewX, viewY, screenX, screenY, Result); } end; function TBasicDcefBrowserEvents.doOnGetViewRect(const browser: ICefBrowser; rect: PCefRect): Boolean; begin Result := False; { if Assigned(FOnGetViewRect) then FOnGetViewRect(Self, browser, rect, Result); } end; procedure TBasicDcefBrowserEvents.doOnGotFocus(const browser: ICefBrowser); begin if Assigned(FOnGotFocus) then FOnGotFocus(browser); end; function TBasicDcefBrowserEvents.doOnJsdialog(const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean; begin Result := False; if Assigned(FOnJsdialog) then FOnJsdialog(browser, originUrl, acceptLang, dialogType, messageText, defaultPromptText, callback, suppressMessage, Result); end; function TBasicDcefBrowserEvents.doOnKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle): Boolean; begin Result := False; if Assigned(FOnKeyEvent) then FOnKeyEvent(browser, event, osEvent, Result); end; procedure TBasicDcefBrowserEvents.doOnLoadEnd(const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); begin if Assigned(FOnLoadEnd) then FOnLoadEnd(browser, frame, httpStatusCode); end; procedure TBasicDcefBrowserEvents.doOnLoadError(const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring); begin if Assigned(FOnLoadError) then FOnLoadError(browser, frame, errorCode, errorText, failedUrl); end; procedure TBasicDcefBrowserEvents.doOnLoadingStateChange(const browser : ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); begin if Assigned(FOnLoadingStateChange) then FOnLoadingStateChange(browser, isLoading, canGoBack, canGoForward); end; procedure TBasicDcefBrowserEvents.doOnLoadStart(const browser: ICefBrowser; const frame: ICefFrame); begin if Assigned(FOnLoadStart) then FOnLoadStart(browser, frame); end; procedure TBasicDcefBrowserEvents.doOnPaint(const browser: ICefBrowser; kind: TCefPaintElementType; dirtyRectsCount: NativeUInt; const dirtyRects: PCefRectArray; const buffer: Pointer; width, height: Integer); begin { if Assigned(FOnPaint) then FOnPaint(Self, browser, kind, dirtyRectsCount, dirtyRects, buffer, width, height); } end; procedure TBasicDcefBrowserEvents.doOnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); begin if Assigned(FOnPluginCrashed) then FOnPluginCrashed(browser, pluginPath); end; procedure TBasicDcefBrowserEvents.doOnPopupShow(const browser: ICefBrowser; show: Boolean); begin { if Assigned(FOnPopupShow) then FOnPopupShow(Self, browser, show); } end; procedure TBasicDcefBrowserEvents.doOnPopupSize(const browser: ICefBrowser; const rect: PCefRect); begin { if Assigned(FOnPopupSize) then FOnPopupSize(Self, browser, rect); } end; function TBasicDcefBrowserEvents.doOnPreKeyEvent(const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean): Boolean; begin Result := False; if Assigned(FOnPreKeyEvent) then FOnPreKeyEvent(browser, event, osEvent, isKeyboardShortcut, Result); end; function TBasicDcefBrowserEvents.doOnProcessMessageReceived (const browser: ICefBrowser; sourceProcess: TCefProcessId; const message: ICefProcessMessage): Boolean; begin Result := False; if Assigned(FOnProcessMessageReceived) then FOnProcessMessageReceived(browser, sourceProcess, message, Result); end; procedure TBasicDcefBrowserEvents.doOnProtocolExecution(const browser : ICefBrowser; const url: ustring; out allowOsExecution: Boolean); begin if Assigned(FOnProtocolExecution) then FOnProtocolExecution(browser, url, allowOsExecution); end; function TBasicDcefBrowserEvents.doOnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback): Boolean; begin Result := False; if Assigned(FOnQuotaRequest) then FOnQuotaRequest(browser, originUrl, newSize, callback, Result); end; procedure TBasicDcefBrowserEvents.doOnRenderProcessTerminated (const browser: ICefBrowser; status: TCefTerminationStatus); begin if Assigned(FOnRenderProcessTerminated) then FOnRenderProcessTerminated(browser, status); end; function TBasicDcefBrowserEvents.doOnRequestGeolocationPermission (const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; begin Result := False; if Assigned(FOnRequestGeolocationPermission) then FOnRequestGeolocationPermission(browser, requestingUrl, requestId, callback, Result); end; procedure TBasicDcefBrowserEvents.doOnResetDialogState(const browser : ICefBrowser); begin if Assigned(FOnResetDialogState) then FOnResetDialogState(browser); end; procedure TBasicDcefBrowserEvents.doOnResourceRedirect(const browser : ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring); begin if Assigned(FOnResourceRedirect) then FOnResourceRedirect(browser, frame, oldUrl, newUrl); end; function TBasicDcefBrowserEvents.doOnRunModal(const browser : ICefBrowser): Boolean; begin Result := False; if Assigned(FOnRunModal) then FOnRunModal(browser, Result); end; procedure TBasicDcefBrowserEvents.doOnScrollOffsetChanged (const browser: ICefBrowser); begin { if Assigned(FOnScrollOffsetChanged) then FOnScrollOffsetChanged(Self, browser); } end; function TBasicDcefBrowserEvents.doOnSetFocus(const browser: ICefBrowser; source: TCefFocusSource): Boolean; begin Result := False; if Assigned(FOnSetFocus) then FOnSetFocus(browser, source, Result); end; function TBasicDcefBrowserEvents.doOnStartDragging(const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer): Boolean; begin Result := False; if Assigned(FOnStartDragging) then FOnStartDragging(browser, dragData, allowedOps, x, y, Result); end; procedure TBasicDcefBrowserEvents.doOnStatusMessage(const browser: ICefBrowser; const value: ustring); begin if Assigned(FOnStatusMessage) then FOnStatusMessage(browser, value); end; procedure TBasicDcefBrowserEvents.doOnTakeFocus(const browser: ICefBrowser; next: Boolean); begin if Assigned(FOnTakeFocus) then FOnTakeFocus(browser, next); end; procedure TBasicDcefBrowserEvents.doOnTitleChange(const browser: ICefBrowser; const title: ustring); begin if Assigned(FOnTitleChange) then FOnTitleChange(browser, title); end; function TBasicDcefBrowserEvents.doOnTooltip(const browser: ICefBrowser; var text: ustring): Boolean; begin Result := False; if Assigned(FOnTooltip) then FOnTooltip(browser, text, Result); end; procedure TBasicDcefBrowserEvents.doOnUpdateDragCursor(const browser : ICefBrowser; operation: TCefDragOperation); begin if Assigned(FOnUpdateDragCursor) then FOnUpdateDragCursor(browser, operation) end; end.
unit evContentsNode; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Инишев Д.А. // Модуль: "w:/common/components/gui/Garant/Everest/evContentsNode.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::ContentsTree::TevContentsNode // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses l3Tree_TLB, l3VirtualNode ; type TevContentsNodeState = ( {* Состояние узла дерева оглавления. } ev_cntNotReady // Узел только что создан и не инициализирован. , ev_cntNeedUpdate // Нужно пересоздать дочерние , ev_cntReady // Узел готов к отображению и не требует обновления. , ev_cntInUpdate // Полный перебор. , ev_cntFirstFind // Поиск первого тега для узла. );//TevContentsNodeState TevContentsNode = class(Tl3VirtualFlagsNode) private // private fields f_AllChildrenCount : Integer; f_ThisChildrenCount : Integer; f_ParentNode : Pointer; f_PrevNode : Pointer; f_ChildNode : Il3Node; f_NextNode : Il3Node; f_NodeState : TevContentsNodeState; private // private methods function CheckChildren: Boolean; {* Проверяет есть ли у задания дочерние. } procedure TryGetChildren; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } function Get_AllChildrenCount: Integer; override; procedure IncAllChildrenCount(aInc: Integer); override; procedure ReleaseChilds; override; procedure Set_ChildNode(const aValue: Il3Node); override; function Get_ChildNode: Il3Node; override; function Get_ParentNode: Il3Node; override; function Get_NextNode: Il3Node; override; function Get_PrevNode: Il3Node; override; function GetThisChildrenCount: Integer; override; function IsLastNode: Boolean; override; function IsFirstNode: Boolean; override; procedure Set_ParentNode(const aValue: Il3Node); override; procedure Set_PrevNode(const aValue: Il3Node); override; procedure Set_NextNode(const aValue: Il3Node); override; function HasChildNode: Boolean; override; function IterateChild(Action: Tl3NodeAction; IterMode: Integer; const aFromNode: Il3Node = nil): Il3Node; override; protected // protected methods function NeedCreate: Boolean; function NotReady: Boolean; function NeedUpdate: Boolean; procedure IncThisChildrenCount; procedure DoTryGetChildren; virtual; abstract; function NeedMakeChildren: Boolean; virtual; public // public methods constructor Create; reintroduce; virtual; end;//TevContentsNode implementation uses l3InterfacesMisc, l3Types, l3Bits, l3TreeInterfaces ; // start class TevContentsNode function TevContentsNode.CheckChildren: Boolean; //#UC START# *4DFF17B70111_4DFEF11703D8_var* //#UC END# *4DFF17B70111_4DFEF11703D8_var* begin //#UC START# *4DFF17B70111_4DFEF11703D8_impl* if f_NodeState = ev_cntReady then Result := f_ThisChildrenCount > 0 else begin if f_NodeState in [ev_cntNeedUpdate, ev_cntFirstFind, ev_cntInUpdate] then Result := ChildNode <> nil else begin Result := False; if IsChanging then Exit; Assert(f_NodeState <> ev_cntInUpdate); f_NodeState := ev_cntFirstFind; TryGetChildren; Result := ChildNode <> nil; if Result then f_NodeState := ev_cntNeedUpdate else f_NodeState := ev_cntReady; // дочерних нет... end; end; //#UC END# *4DFF17B70111_4DFEF11703D8_impl* end;//TevContentsNode.CheckChildren procedure TevContentsNode.TryGetChildren; //#UC START# *4E09D24E0182_4DFEF11703D8_var* //#UC END# *4E09D24E0182_4DFEF11703D8_var* begin //#UC START# *4E09D24E0182_4DFEF11703D8_impl* if NeedMakeChildren then begin if f_NodeState = ev_cntInUpdate then Exit; if f_NodeState <> ev_cntFirstFind then f_NodeState := ev_cntInUpdate; try DoTryGetChildren; finally f_NodeState := ev_cntReady; end; end; // if NeedMakeChildren then //#UC END# *4E09D24E0182_4DFEF11703D8_impl* end;//TevContentsNode.TryGetChildren function TevContentsNode.NeedCreate: Boolean; //#UC START# *4E09C3EA0357_4DFEF11703D8_var* //#UC END# *4E09C3EA0357_4DFEF11703D8_var* begin //#UC START# *4E09C3EA0357_4DFEF11703D8_impl* Assert(f_NodeState <> ev_cntNeedUpdate); Result := (f_NodeState = ev_cntInUpdate) or (ChildNode = nil); //#UC END# *4E09C3EA0357_4DFEF11703D8_impl* end;//TevContentsNode.NeedCreate function TevContentsNode.NotReady: Boolean; //#UC START# *4E09C6110082_4DFEF11703D8_var* //#UC END# *4E09C6110082_4DFEF11703D8_var* begin //#UC START# *4E09C6110082_4DFEF11703D8_impl* Result := f_NodeState = ev_cntFirstFind; //#UC END# *4E09C6110082_4DFEF11703D8_impl* end;//TevContentsNode.NotReady function TevContentsNode.NeedUpdate: Boolean; //#UC START# *4E09E20A0130_4DFEF11703D8_var* //#UC END# *4E09E20A0130_4DFEF11703D8_var* begin //#UC START# *4E09E20A0130_4DFEF11703D8_impl* Result := f_NodeState = ev_cntInUpdate; //#UC END# *4E09E20A0130_4DFEF11703D8_impl* end;//TevContentsNode.NeedUpdate procedure TevContentsNode.IncThisChildrenCount; //#UC START# *4E26C5080278_4DFEF11703D8_var* //#UC END# *4E26C5080278_4DFEF11703D8_var* begin //#UC START# *4E26C5080278_4DFEF11703D8_impl* Inc(f_ThisChildrenCount); //#UC END# *4E26C5080278_4DFEF11703D8_impl* end;//TevContentsNode.IncThisChildrenCount constructor TevContentsNode.Create; //#UC START# *4DFEF25D0323_4DFEF11703D8_var* //#UC END# *4DFEF25D0323_4DFEF11703D8_var* begin //#UC START# *4DFEF25D0323_4DFEF11703D8_impl* inherited Create; f_ThisChildrenCount := 0; f_ParentNode := nil; f_NodeState := ev_cntNotReady; f_AllChildrenCount := 0; //#UC END# *4DFEF25D0323_4DFEF11703D8_impl* end;//TevContentsNode.Create function TevContentsNode.NeedMakeChildren: Boolean; //#UC START# *4DFF1C860175_4DFEF11703D8_var* //#UC END# *4DFF1C860175_4DFEF11703D8_var* begin //#UC START# *4DFF1C860175_4DFEF11703D8_impl* Result := (f_NodeState <> ev_cntReady) and not IsChanging; //#UC END# *4DFF1C860175_4DFEF11703D8_impl* end;//TevContentsNode.NeedMakeChildren procedure TevContentsNode.Cleanup; //#UC START# *479731C50290_4DFEF11703D8_var* //#UC END# *479731C50290_4DFEF11703D8_var* begin //#UC START# *479731C50290_4DFEF11703D8_impl* inherited; f_NextNode := nil; f_PrevNode := nil; f_ParentNode := nil; f_ThisChildrenCount := 0; f_NodeState := ev_cntNotReady; //#UC END# *479731C50290_4DFEF11703D8_impl* end;//TevContentsNode.Cleanup function TevContentsNode.Get_AllChildrenCount: Integer; //#UC START# *4ADEE8EE025E_4DFEF11703D8_var* //#UC END# *4ADEE8EE025E_4DFEF11703D8_var* begin //#UC START# *4ADEE8EE025E_4DFEF11703D8_impl* if f_AllChildrenCount < 0 then begin Result := inherited Get_AllChildrenCount; f_AllChildrenCount := Result; end else Result := f_AllChildrenCount; //#UC END# *4ADEE8EE025E_4DFEF11703D8_impl* end;//TevContentsNode.Get_AllChildrenCount procedure TevContentsNode.IncAllChildrenCount(aInc: Integer); //#UC START# *4ADEE9120163_4DFEF11703D8_var* //#UC END# *4ADEE9120163_4DFEF11703D8_var* begin //#UC START# *4ADEE9120163_4DFEF11703D8_impl* if (aInc <> 0) then begin if (f_AllChildrenCount >= 0) then f_AllChildrenCount := f_AllChildrenCount + aInc else Get_AllChildrenCount; if (ParentNode <> nil) then ParentNode.IncAllChildrenCount(aInc); end; //#UC END# *4ADEE9120163_4DFEF11703D8_impl* end;//TevContentsNode.IncAllChildrenCount procedure TevContentsNode.ReleaseChilds; //#UC START# *4ADEEA5A0206_4DFEF11703D8_var* var l_CurNode : Il3InternalNode; l_PrevNode : Il3InternalNode; l_IsLast : Boolean; //#UC END# *4ADEEA5A0206_4DFEF11703D8_var* begin //#UC START# *4ADEEA5A0206_4DFEF11703D8_impl* f_NodeState := ev_cntNotReady; if (f_ChildNode = nil) then Exit; l_CurNode := (f_ChildNode.PrevNode as Il3InternalNode); // Last repeat l_IsLast := l_CurNode.IsSame(f_ChildNode); l_PrevNode := (l_CurNode.PrevNode as Il3InternalNode); l_CurNode.ParentNode := nil; l_CurNode.NextNode := nil; l_CurNode._Release; l_CurNode := l_PrevNode; until l_IsLast; Set_ChildNode(nil); f_ThisChildrenCount := 0; AllChildrenCount := 0; Notify(ntChildClear, Self); //#UC END# *4ADEEA5A0206_4DFEF11703D8_impl* end;//TevContentsNode.ReleaseChilds procedure TevContentsNode.Set_ChildNode(const aValue: Il3Node); //#UC START# *4ADEEFA00164_4DFEF11703D8_var* //#UC END# *4ADEEFA00164_4DFEF11703D8_var* begin //#UC START# *4ADEEFA00164_4DFEF11703D8_impl* f_ChildNode := aValue; //#UC END# *4ADEEFA00164_4DFEF11703D8_impl* end;//TevContentsNode.Set_ChildNode function TevContentsNode.Get_ChildNode: Il3Node; //#UC START# *4ADEF5410241_4DFEF11703D8_var* //#UC END# *4ADEF5410241_4DFEF11703D8_var* begin //#UC START# *4ADEF5410241_4DFEF11703D8_impl* Result := f_ChildNode; //#UC END# *4ADEF5410241_4DFEF11703D8_impl* end;//TevContentsNode.Get_ChildNode function TevContentsNode.Get_ParentNode: Il3Node; //#UC START# *4DFF11E50055_4DFEF11703D8_var* //#UC END# *4DFF11E50055_4DFEF11703D8_var* begin //#UC START# *4DFF11E50055_4DFEF11703D8_impl* Result := Il3Node(f_ParentNode); //#UC END# *4DFF11E50055_4DFEF11703D8_impl* end;//TevContentsNode.Get_ParentNode function TevContentsNode.Get_NextNode: Il3Node; //#UC START# *4DFF12480351_4DFEF11703D8_var* //#UC END# *4DFF12480351_4DFEF11703D8_var* begin //#UC START# *4DFF12480351_4DFEF11703D8_impl* Result := f_NextNode; //#UC END# *4DFF12480351_4DFEF11703D8_impl* end;//TevContentsNode.Get_NextNode function TevContentsNode.Get_PrevNode: Il3Node; //#UC START# *4DFF1269012B_4DFEF11703D8_var* //#UC END# *4DFF1269012B_4DFEF11703D8_var* begin //#UC START# *4DFF1269012B_4DFEF11703D8_impl* if (f_PrevNode <> nil) then Result := Il3Node(f_PrevNode) else Result := nil; //#UC END# *4DFF1269012B_4DFEF11703D8_impl* end;//TevContentsNode.Get_PrevNode function TevContentsNode.GetThisChildrenCount: Integer; //#UC START# *4DFF132503B6_4DFEF11703D8_var* //#UC END# *4DFF132503B6_4DFEF11703D8_var* begin //#UC START# *4DFF132503B6_4DFEF11703D8_impl* Result := f_ThisChildrenCount; //#UC END# *4DFF132503B6_4DFEF11703D8_impl* end;//TevContentsNode.GetThisChildrenCount function TevContentsNode.IsLastNode: Boolean; //#UC START# *4DFF13AB0076_4DFEF11703D8_var* var l_Node: Il3Node; //#UC END# *4DFF13AB0076_4DFEF11703D8_var* begin //#UC START# *4DFF13AB0076_4DFEF11703D8_impl* l_Node := ParentNode; if l_Node = nil then Result := True else begin l_Node := l_Node.ChildNode; Result := (l_Node = nil) or l3IEQ(l_Node.Prev, Self); end; //#UC END# *4DFF13AB0076_4DFEF11703D8_impl* end;//TevContentsNode.IsLastNode function TevContentsNode.IsFirstNode: Boolean; //#UC START# *4DFF13C0006D_4DFEF11703D8_var* var l_Node: Il3Node; //#UC END# *4DFF13C0006D_4DFEF11703D8_var* begin //#UC START# *4DFF13C0006D_4DFEF11703D8_impl* l_Node := ParentNode; if l_Node = nil then Result := True else begin l_Node := l_Node.ChildNode; Result := (l_Node = nil) or l3IEQ(l_Node, Self); end; //#UC END# *4DFF13C0006D_4DFEF11703D8_impl* end;//TevContentsNode.IsFirstNode procedure TevContentsNode.Set_ParentNode(const aValue: Il3Node); //#UC START# *4DFF154E0063_4DFEF11703D8_var* //#UC END# *4DFF154E0063_4DFEF11703D8_var* begin //#UC START# *4DFF154E0063_4DFEF11703D8_impl* f_ParentNode := Pointer(aValue); //#UC END# *4DFF154E0063_4DFEF11703D8_impl* end;//TevContentsNode.Set_ParentNode procedure TevContentsNode.Set_PrevNode(const aValue: Il3Node); //#UC START# *4DFF15710135_4DFEF11703D8_var* //#UC END# *4DFF15710135_4DFEF11703D8_var* begin //#UC START# *4DFF15710135_4DFEF11703D8_impl* f_PrevNode := Pointer(aValue); //#UC END# *4DFF15710135_4DFEF11703D8_impl* end;//TevContentsNode.Set_PrevNode procedure TevContentsNode.Set_NextNode(const aValue: Il3Node); //#UC START# *4DFF15B3015B_4DFEF11703D8_var* //#UC END# *4DFF15B3015B_4DFEF11703D8_var* begin //#UC START# *4DFF15B3015B_4DFEF11703D8_impl* f_NextNode := aValue; //#UC END# *4DFF15B3015B_4DFEF11703D8_impl* end;//TevContentsNode.Set_NextNode function TevContentsNode.HasChildNode: Boolean; //#UC START# *4DFF21140378_4DFEF11703D8_var* //#UC END# *4DFF21140378_4DFEF11703D8_var* begin //#UC START# *4DFF21140378_4DFEF11703D8_impl* Result := (ChildNode <> nil) or CheckChildren; //#UC END# *4DFF21140378_4DFEF11703D8_impl* end;//TevContentsNode.HasChildNode function TevContentsNode.IterateChild(Action: Tl3NodeAction; IterMode: Integer; const aFromNode: Il3Node = nil): Il3Node; //#UC START# *4DFF22F202A1_4DFEF11703D8_var* //#UC END# *4DFF22F202A1_4DFEF11703D8_var* begin //#UC START# *4DFF22F202A1_4DFEF11703D8_impl* if not l3TestMask(IterMode, imExpandOnly) then TryGetChildren; Result := inherited IterateChild(Action, IterMode, aFromNode); //#UC END# *4DFF22F202A1_4DFEF11703D8_impl* end;//TevContentsNode.IterateChild end.
unit EditorMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, EditableObjects, Menus, Notifications; type TEditorMainForm = class(TForm, IHook) pnLeft: TPanel; pnRightContainer: TPanel; MainMenu1: TMainMenu; File1: TMenuItem; Save1: TMenuItem; Load1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; Splitter1: TSplitter; Panel1: TPanel; pnRight: TPanel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Load1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Exit1Click(Sender: TObject); private fMission : TEditableObject; fTemplates : TStringList; procedure RegisterEditors; procedure LoadTemplates; private procedure Handle( EventClass : TEventClass; var Info ); procedure SaveMission( filename : string ); procedure LoadMission( filename : string ); end; var EditorMainForm: TEditorMainForm; implementation uses NativeEdObjects, Editors, plainText, ComboBox, FileName, Percent, ObjectContainer, ObjectInspector, NewStepCreator, EditorEvents, NewStepClass, XMLFile, IniFiles; {$R *.DFM} procedure TEditorMainForm.FormCreate(Sender: TObject); var useless : integer; AppPath : string; begin CreateMetaObjectPool; RegisterEditors; AppPath := ExtractFilePath( Application.ExeName ); InitMetaObjectPool( AppPath + 'classes.xml' ); //TheMetaObjectPool.Save( AppPath + 'test2.ini' ); InitNotificationEngine; RegisterEventClass( evGetTemplates, 0 ); AddNotifier( evGetTemplates, self ); LoadTemplates; end; procedure TEditorMainForm.FormShow(Sender: TObject); var useless : integer; general : TEditableObject; begin fMission := TheMetaObjectPool.get( 'MetaMission' ).Instantiate( 'New Mission', '', useless ); fMission.Edit( VOP_SHOWINMAINCONTROL, pnLeft ); //fMission.getProperty( 'General' ).Edit( 0, pnRight ); end; procedure TEditorMainForm.RegisterEditors; begin TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'Mission', TObjectContainerEditor, TNewStepForm )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'MetaStep', TObjectContainerEditor, TNewStepClassForm )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'Step', TObjectInspectorEditor, nil )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'PlainText', TPlainTextEditor, nil )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'Percent', TPercentEditor, nil )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'Combobox', TComboBoxEditor, nil )); TheMetaObjectPool.registerEditor( TNativeObjectEditor.Create( 'FileName', TFilenameEditor, nil )); end; procedure TEditorMainForm.LoadTemplates; var IniFile : TIniFile; sections : TStringList; names : TStringList; i : integer; AppPath : string; begin fTemplates := TStringList.Create; AppPath := ExtractFilePath( Application.ExeName ); IniFile := TIniFile.Create( AppPath + 'templates.ini' ); try sections := TStringList.Create; IniFile.ReadSections( sections ); fTemplates.AddObject( 'Templates', sections ); for i := 0 to pred(sections.count) do begin names := TStringList.Create; IniFile.ReadSection( sections[i], Names ); fTemplates.AddObject( sections[i], Names ); end; finally IniFile.Free; end; end; procedure TEditorMainForm.Handle( EventClass : TEventClass; var Info ); var GetTemplateData : TGetTemplateData; Idx : integer; i : integer; begin case EventClass of evGetTemplates : begin GetTemplateData := TGetTemplateData(Info); Idx := fTemplates.IndexOf( GetTemplateData.Name ); if Idx <> -1 then GetTemplateData.Template.Assign( TStringList(fTemplates.Objects[Idx]) ) else if CompareText( GetTemplateData.Name, 'Steps' ) = 0 then for i := 0 to pred(fMission.Properties.Count) do if TEditableObject(fMission.Properties[i]).Name <> 'General' then GetTemplateData.Template.Add( TEditableObject(fMission.Properties[i]).Name ); end; end; end; procedure TEditorMainForm.SaveMission( filename : string ); const MaxRoles = 10; var Trainings : array[0..MaxRoles] of TStringList; Roles : TStringList; procedure getClientInfo; var i : integer; role : integer; prop : TEditableObject; tr : TEditableObject; idx : integer; begin for i := 0 to pred(fMission.Properties.Count) do with TEditableObject(fMission.Properties[i]) do begin role := 1; prop := getProperty( 'Role' + IntToStr(role) ); while prop <> nil do begin idx := Roles.IndexOf( prop.Value ); if idx = -1 then idx := Roles.Add( prop.Value ); tr := getProperty( 'Training' + IntToStr(role) ); if tr <> nil then begin if Trainings[idx].IndexOf( tr.Value ) = -1 then Trainings[idx].Add( tr.Value ); end; tr := getProperty( 'SecondaryTraining' + IntToStr(role) ); if tr <> nil then begin if (Trainings[idx].IndexOf( tr.Value ) = -1) and (tr.Value <> 'none') then Trainings[idx].Add( tr.Value ); end; inc( role ); prop := getProperty( 'Role' + IntToStr(role) ); end; end; end; var XMLServer : TXMLFile; XMLClient : TXMLFile; i : integer; j : integer; general : TEditableObject; node : TXMLNode; propNode : TXMLNode; infoNode : TXMLNode; trainNode : TXMLNode; begin XMLServer := TXMLFile.Create; XMLClient := TXMLFile.Create; try // Save the server side // save the general information first general := fMission.getProperty( 'General' ); node := XMLServer.CreateNode( '', 'General' ); node.WriteString( 'class', general.MetaClass.getFullName ); node.WriteString( 'Name', general.Name ); node.WriteString( 'value', general.Value ); for j := 0 to pred(general.Properties.Count) do begin propNode := node.CreateChild( TEditableObject(general.Properties[j]).Name ); propNode.setValueAsString( TEditableObject(general.Properties[j]).Value ); propNode.Free; end; node.Free; for i := 0 to pred(fMission.Properties.Count) do with TEditableObject(fMission.Properties[i]) do begin if Name <> 'General' then begin node := XMLServer.CreateNode( '', 'Property' ); node.WriteString( 'class', MetaClass.getFullName ); node.WriteString( 'Name', Name ); node.WriteString( 'value', Value ); for j := 0 to pred(Properties.Count) do begin propNode := node.CreateChild( TEditableObject(Properties[j]).Name ); propNode.setValueAsString( TEditableObject(Properties[j]).Value ); propNode.Free; end; node.Free; end; end; // save the client side Roles := TStringList.Create; for i := 0 to pred(MaxRoles) do Trainings[i] := TStringList.Create; try general := fMission.getProperty( 'General' ); infoNode := XMLClient.CreateNode( '', 'Info' ); infoNode.WriteString( 'Name', general.getProperty( 'MissionName' ).Value ); infoNode.WriteString( 'Description', general.getProperty( 'Description' ).Value ); infoNode.WriteString( 'Id', general.getProperty( 'Id' ).Value ); infoNode.Free; getClientInfo; for i := 0 to pred(Roles.Count) do begin node := XMLClient.CreateNode( '', 'Role' ); node.setValueAsString( Roles[i] ); for j := 0 to pred(Trainings[i].Count) do begin trainNode := node.CreateChild( 'Training' ); trainNode.setValueAsString( Trainings[i][j] ); trainNode.Free; end; node.Free; end; finally Roles.Free; for i := 0 to pred(MaxRoles) do Trainings[i].Free; end; XMLServer.Save( filename ); XMLClient.Save( filename + '.client' ); finally XMLServer.Free; XMLClient.Free; end; end; procedure TEditorMainForm.LoadMission( filename : string ); var XMLFile : TXMLFile; i, j : integer; prop : TEditableObject; prop1 : TEditableObject; classId : string; name : string; value : string; useless : integer; list : TList; proplist : TList; node : TXMLNode; propnode : TXMLNode; begin XMLFile := TXMLFile.Create; try if XMLFile.Load( filename ) then begin if fMission <> nil then fMission.Free; fMission := TheMetaObjectPool.get( 'MetaMission' ).Instantiate( 'New Mission', '', useless ); list := TList.Create; proplist := TList.Create; try XMLFile.getAllNodes( '', list ); for i := 0 to pred(list.Count) do begin node := TXMLNode(list[i]); classId := node.ReadString( 'class', '' ); name := node.ReadString( 'Name', '' ); value := node.ReadString( 'value', '' ); prop := fMission.getProperty( classId ); if prop = nil then begin prop := TheMetaObjectPool.get( classId ).Instantiate( name, value, useless ); fMission.Properties.Insert( prop ); end else begin prop.Name := name; prop.Value := value; end; proplist.Clear; node.getChilds( proplist ); for j := 0 to pred(proplist.Count) do begin propnode := TXMLNode(proplist[j]); prop1 := prop.getProperty( propnode.getName ); prop1.Value := propnode.ReadString( 'value', '' ); propnode.Free; end; end; fMission.Edit( VOP_SHOWINMAINCONTROL, pnLeft ); finally list.Free; proplist.Free; end; end else ShowMessage( 'Unable to open ' + filename ); finally XMLFile.Free; end; end; procedure TEditorMainForm.Save1Click(Sender: TObject); var AppPath : string; begin if SaveDialog1.Execute then begin AppPath := ExtractFilePath( Application.ExeName ); TheMetaObjectPool.Save( AppPath + 'Classes.xml' ); SaveMission( SaveDialog1.FileName ); end; end; procedure TEditorMainForm.Load1Click(Sender: TObject); begin if OpenDialog1.Execute then LoadMission( OpenDialog1.FileName ); end; procedure TEditorMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin DestroyMetaObjectPool; end; procedure TEditorMainForm.Exit1Click(Sender: TObject); begin Close; end; end.
unit HouseMapForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, DBCtrlsEh, ExtCtrls, DB, FIBDataSet, pFIBDataSet, PrjConst; type TFlat = record flat_no: string; flat_id: integer; customer_id: integer; Debt_SUM: Currency; customer_info: string; end; TFloor = record floor_id: integer; floor_n: string; // porch_id : Integer; // porch_n : string; flats_n: string; flats_cnt: integer; flats: array of TFlat; end; TPorch = record porch_id: integer; porch_n: string; floor_cnt: integer; garret: boolean; cellar: boolean; floors: array of TFloor; end; THouseMapForm = class(TForm) pnlSettings: TPanel; btnBuild: TButton; edtFC: TDBNumberEditEh; lbl1: TLabel; dsHouse: TpFIBDataSet; dsPORCH: TpFIBDataSet; dsCustomers: TpFIBDataSet; pnlMap: TScrollBox; procedure pnlFloorClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnBuildClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } fHouseId: integer; maxPorch: integer; maxFloor: integer; HasInfo: boolean; Porchs: array of TPorch; procedure SetHouseId(value: integer); procedure BuildMapInfo; procedure BuildMapGui; public { Public declarations } property HouseID: integer write SetHouseId; end; var HouseMapForm: THouseMapForm; implementation uses DM, AtrStrUtils, TextEditForma, pFIBQuery; {$R *.dfm} procedure THouseMapForm.SetHouseId(value: integer); begin fHouseId := value; BuildMapInfo; BuildMapGui; end; procedure THouseMapForm.BuildMapInfo; function GetFlatsArray(const flats: string): TStringArray; var i, b, e: integer; f, g: TStringArray; Count: integer; begin if flats = '' then begin Result := nil; Exit; end; // if Count := 0; f := Explode(',', flats); for i := 0 to Length(f) - 1 do begin if Pos('-', f[i]) > 0 then begin g := Explode('-', f[i]); b := 0; e := 0; TryStrToInt(g[0], b); TryStrToInt(g[1], e); while b <= e do begin SetLength(Result, Count + 1); Result[Count] := IntToStr(b); Inc(Count); Inc(b); end end else begin SetLength(Result, Count + 1); Result[Count] := f[i]; Inc(Count); end end; end; var cp, cf: integer; pp: integer; i: integer; s: string; af: TStringArray; begin dsHouse.Close; dsPORCH.Close; dsCustomers.Close; dsHouse.ParamByName('HOUSE_ID').AsInteger := fHouseId; dsPORCH.ParamByName('HOUSE_ID').AsInteger := fHouseId; dsCustomers.ParamByName('HOUSE_ID').AsInteger := fHouseId; dsHouse.Open; Height := dsHouse['map_height']; Width := dsHouse['map_width']; edtFC.value := dsHouse['map_flats']; dsPORCH.Open; dsCustomers.Open; dsHouse.DisableControls; dsPORCH.DisableControls; dsCustomers.DisableControls; maxPorch := 1; maxFloor := 1; cp := -1; pp := -1; cf := 0; while not dsPORCH.Eof do begin if (not dsPORCH.FieldByName('floor_n').IsNull) and (not dsPORCH.FieldByName('porch_n').IsNull) then begin if pp <> dsPORCH['porch_id'] then begin Inc(cp); SetLength(Porchs, cp + 1); // увеличение длины массива на 1 Porchs[cp].porch_id := dsPORCH['porch_id']; Porchs[cp].porch_n := dsPORCH['porch_n']; Porchs[cp].floor_cnt := 0; pp := dsPORCH['porch_id']; if cf > maxFloor then maxFloor := cf; cf := 0; end; // if pf <> dsPorch['floor_id'] // then begin SetLength(Porchs[cp].floors, cf + 1); // увеличение длины массива на 1 Porchs[cp].floor_cnt := cf + 1; Porchs[cp].floors[cf].floor_id := dsPORCH['floor_id']; Porchs[cp].floors[cf].floor_n := dsPORCH['floor_n']; if not dsPORCH.FieldByName('flats').IsNull then begin Porchs[cp].floors[cf].flats_n := dsPORCH['flats']; af := GetFlatsArray(dsPORCH['flats']); Porchs[cp].floors[cf].flats_cnt := Length(af); for i := 0 to Length(af) - 1 do begin SetLength(Porchs[cp].floors[cf].flats, i + 1); Porchs[cp].floors[cf].flats[i].flat_no := af[i]; s := ''; if dsCustomers.Locate('FLAT_NO', af[i], [loCaseInsensitive]) then begin Porchs[cp].floors[cf].flats[i].customer_id := dsCustomers['CUSTOMER_ID']; if not dsCustomers.FieldByName('ACCOUNT_NO').IsNull then s := s + format(rsAccountWT, [dsCustomers['ACCOUNT_NO']]) + rsEOL; if not dsCustomers.FieldByName('dogovor_no').IsNull then s := s + format(rsContractWT, [dsCustomers['dogovor_no']]) + rsEOL; s := s + format(rsFIOWT, [dsCustomers.FieldByName('surname').AsString + ' ' + dsCustomers.FieldByName('initials').AsString]) + rsEOL; if not dsCustomers.FieldByName('debt_sum').IsNull then s := s + format(rsSaldoWT, [dsCustomers.FieldByName('debt_sum').AsString]) + rsEOL; if (not dsCustomers.FieldByName('phone_no').IsNull) or (not dsCustomers.FieldByName('mobile_phone').IsNull) then s := s + format(rsPhone, [dsCustomers.FieldByName('phone_no').AsString, dsCustomers.FieldByName('mobile_phone').AsString]) + rsEOL; if not dsCustomers.FieldByName('cust_state_descr').IsNull then s := s + format(rsStateWT, [dsCustomers['cust_state_descr']]) + rsEOL; if not dsCustomers.FieldByName('notice').IsNull then s := s + format(rsNoticeWT, [dsCustomers['notice']]); Porchs[cp].floors[cf].flats[i].Debt_SUM := dsCustomers.FieldByName('debt_sum').AsCurrency; end else begin Porchs[cp].floors[cf].flats[i].customer_id := -1; Porchs[cp].floors[cf].flats[i].Debt_SUM := 0; s := rsNotCustomer end; Porchs[cp].floors[cf].flats[i].customer_info := s; end; end; Inc(cf); end; dsPORCH.Next; end; maxPorch := cp + 1; HasInfo := True; end; procedure THouseMapForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if fHouseId <> -1 then begin with TpFIBQuery.Create(Nil) do try DataBase := dmMain.dbTV; Transaction := dmMain.trWriteQ; SQL.Text := 'update HOUSE set MAP_FLATS = :MAP_FLATS, MAP_WIDTH = :MAP_WIDTH, MAP_HEIGHT = :MAP_HEIGHT where (HOUSE_ID = :HOUSE_ID)'; ParamByName('MAP_FLATS').value := edtFC.value; ParamByName('MAP_WIDTH').value := Width; ParamByName('MAP_HEIGHT').value := Height; ParamByName('HOUSE_ID').value := fHouseId; Transaction.StartTransaction; ExecQuery; Transaction.Commit; Close; finally Free; end; end; end; procedure THouseMapForm.FormCreate(Sender: TObject); begin HasInfo := False; fHouseId := -1; end; procedure THouseMapForm.FormResize(Sender: TObject); begin if HasInfo then BuildMapGui; end; procedure THouseMapForm.btnBuildClick(Sender: TObject); begin BuildMapInfo; BuildMapGui; end; procedure THouseMapForm.BuildMapGui; var Porch_width: integer; floor_height: integer; i, j, k: integer; pnl, fpnl: TPanel; flats_on_row: integer; flats_on_row_l: integer; flats_on_floor: integer; vRED_SUMM: Currency; gCustActiveDebt: TColor; fpnlw, fpnlh: integer; cr: TCursor; begin if (maxPorch = 0) or (maxFloor = 0) then Exit; cr := Screen.Cursor; Screen.Cursor := crHourGlass; vRED_SUMM := dmMain.GetSettingsValue('DOLG'); try gCustActiveDebt := StringToColor(dmMain.GetSettingsValue('COLOR_DOLG')); except gCustActiveDebt := clRed; end; flats_on_row := Trunc(edtFC.value); Porch_width := Trunc((pnlMap.Width - 5) / maxPorch); if Porch_width < 80 then Porch_width := 80; floor_height := Trunc((pnlMap.Height - 5) / maxFloor); if floor_height < 40 then floor_height := 40; while pnlMap.ControlCount > 0 do pnlMap.Controls[0].Free; for i := 0 to maxPorch - 1 do begin for j := 0 to Porchs[i].floor_cnt - 1 do begin pnl := TPanel.Create(pnlMap); pnl.Parent := pnlMap; pnl.Height := floor_height; pnl.Width := Porch_width - 1; pnl.Left := (i * Porch_width); pnl.BevelInner := bvRaised; pnl.BevelOuter := bvLowered; pnl.Top := pnlMap.Height - 5 - (j * floor_height) - pnl.Height; flats_on_floor := Porchs[i].floors[j].flats_cnt; if flats_on_floor = 0 then continue; if flats_on_floor < flats_on_row then flats_on_row_l := flats_on_floor else flats_on_row_l := flats_on_row; if (flats_on_floor mod flats_on_row_l) = 0 then fpnlh := Trunc((pnl.Height - 2) / (flats_on_floor div flats_on_row_l)) else fpnlh := Trunc((pnl.Height - 2) / ((flats_on_floor div flats_on_row_l) + 1)); fpnlh := fpnlh - 2; fpnlw := Trunc(pnl.Width / flats_on_row_l) - 2; for k := 0 to flats_on_floor - 1 do begin fpnl := TPanel.Create(pnlMap); fpnl.Parent := pnl; fpnl.Height := fpnlh; fpnl.Width := fpnlw; fpnl.Left := (k mod flats_on_row_l) * fpnl.Width + 2; fpnl.Top := pnl.Height - Trunc(k / flats_on_row_l) * fpnl.Height - fpnl.Height - 2; fpnl.Caption := Porchs[i].floors[j].flats[k].flat_no; fpnl.Hint := Porchs[i].floors[j].flats[k].customer_info; fpnl.ShowHint := True; fpnl.Tag := Porchs[i].floors[j].flats[k].customer_id; if Porchs[i].floors[j].flats[k].customer_id > -1 then fpnl.Font.Style := [fsBold]; if Porchs[i].floors[j].flats[k].Debt_SUM > vRED_SUMM then fpnl.Font.Color := gCustActiveDebt; fpnl.OnClick := pnlFloorClick; end; end end; Screen.Cursor := cr; end; procedure THouseMapForm.pnlFloorClick(Sender: TObject); var str: TStrings; begin str := TStringList.Create; try str.Text := (Sender as TPanel).Hint; EditText(str, rsFlat + ' ' + (Sender as TPanel).Caption); finally str.Free end; end; end.
unit RDOConnectionPool; interface uses Collection, RDOInterfaces, WinSockRDOConnection; const MaxCnns = $FF; type TRDOConnectionInfo = class; TRDOConnectionPool = class; TRDOConnectionInfo = class public constructor Create(Connection : IRDOConnectionInit); private fConnection : IRDOConnectionInit; fTimeOuts : integer; fRefCount : integer; public property Connection : IRDOConnectionInit read fConnection; property TimeOuts : integer read fTimeOuts; property RefCount : integer read fRefCount; end; TRDOConnectionPool = class public constructor Create; destructor Destroy; override; private fConnections : TLockableCollection; public function GetConnection : IRDOConnectionInit; procedure SetConnection(Index : integer; Connection : IRDOConnectionInit); procedure DropConnection(Connection : IRDOConnectionInit); procedure AddConnection(Connection : IRDOConnectionInit); procedure Lock; procedure Unlock; private function GetConnectionInfo(index : integer) : TRDOConnectionInfo; function GetConnetionCount : integer; public property Connections[index : integer] : TRDOConnectionInfo read GetConnectionInfo; property ConnetionCount : integer read GetConnetionCount; end; implementation // TRDOConnectionInfo constructor TRDOConnectionInfo.Create(Connection : IRDOConnectionInit); begin inherited Create; fConnection := Connection; fRefCount := 1; end; // TRDOConnectionPool constructor TRDOConnectionPool.Create; begin inherited Create; fConnections := TLockableCollection.Create(0, rkBelonguer); end; destructor TRDOConnectionPool.Destroy; begin fConnections.Free; inherited; end; function TRDOConnectionPool.GetConnection : IRDOConnectionInit; var cnt : integer; i, j : integer; MinRefCount : integer; begin fConnections.Lock; try cnt := fConnections.Count; j := 0; MinRefCount := MaxInt; for i := 0 to cnt-1 do with TRDOConnectionInfo(fConnections[i]) do if fConnection <> nil then if fRefCount < MinRefCount then begin MinRefCount := fRefCount; j := i; end; if MinRefCount = MaxInt then result := nil else begin result := TRDOConnectionInfo(fConnections[j]).fConnection; Inc(TRDOConnectionInfo(fConnections[j]).fRefCount); end; {while (i < cnt) and (TRDOConnectionInfo(fConnections[i]).fConnection = nil) do inc(i); if i < cnt then with TRDOConnectionInfo(fConnections[i]) do begin result := fConnection; inc(fRefCount); end else result := nil;} finally fConnections.Unlock; end; end; procedure TRDOConnectionPool.SetConnection(Index : integer; Connection : IRDOConnectionInit); begin fConnections.Lock; try with TRDOConnectionInfo(fConnections[index]) do begin fConnection := Connection; fRefCount := 0; end; finally fConnections.Unlock; end; end; procedure TRDOConnectionPool.DropConnection(Connection : IRDOConnectionInit); var cnt : integer; i : integer; begin fConnections.Lock; try cnt := fConnections.Count; i := 0; while (i < cnt) and (TRDOConnectionInfo(fConnections[i]).fConnection <> Connection) do inc(i); if i < cnt then with TRDOConnectionInfo(fConnections[i]) do begin fConnection := nil; fRefCount := 0; end; finally fConnections.Unlock; end; end; procedure TRDOConnectionPool.AddConnection(Connection : IRDOConnectionInit); var Info : TRDOConnectionInfo; begin Info := TRDOConnectionInfo.Create(Connection); fConnections.Insert(Info); end; procedure TRDOConnectionPool.Lock; begin fConnections.Lock; end; procedure TRDOConnectionPool.Unlock; begin fConnections.Unlock; end; function TRDOConnectionPool.GetConnectionInfo(index : integer) : TRDOConnectionInfo; begin result := TRDOConnectionInfo(fConnections[index]); end; function TRDOConnectionPool.GetConnetionCount : integer; begin result := fConnections.Count; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clEpp; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, msxml, Windows,{$IFDEF DEMO} Forms, clCertificate,{$ENDIF} {$ELSE} System.Classes, System.SysUtils, Winapi.msxml, Winapi.Windows,{$IFDEF DEMO} Vcl.Forms, clCertificate,{$ENDIF} {$ENDIF} clTcpClient, clTcpClientTls, clSocketUtils, clEppUtils; type EclEppError = class(EclTcpClientError); TclEppServerInfo = class private FId: string; FDate: string; FVersion: string; FLanguages: TStrings; FObjects: TStrings; FExtensions: TStrings; FAccess: string; FPurpose: string; FRecipient: string; FRetention: string; public constructor Create; destructor Destroy; override; procedure Parse(const AGreeting: IXMLDomNode); procedure Clear; property Id: string read FId; property Date: string read FDate; property Version: string read FVersion; property Languages: TStrings read FLanguages; property Objects: TStrings read FObjects; property Extensions: TStrings read FExtensions; property Access: string read FAccess; property Purpose: string read FPurpose; property Recipient: string read FRecipient; property Retention: string read FRetention; end; TclEpp = class(TclTcpClientTls) private FAuthorized: Boolean; FLastTransactionId: Integer; FStatusText: string; FStatusCode: Integer; FPassword: string; FUserName: string; FServerInfo: TclEppServerInfo; FResponse: TStrings; FRequest: TStrings; FRequestLanguages: TStrings; FRequestExtensions: TStrings; FRequestObjects: TStrings; procedure SetRequestLanguages(const Value: TStrings); procedure SetRequestExtensions(const Value: TStrings); procedure SetRequestObjects(const Value: TStrings); procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); function GetLastTransactionId: string; procedure ReadResponse; procedure ParseResponse; procedure ParseGreeting; function GetRequestTitle: string; function GetRequestLanguages: string; function GetNextTransactionId: string; function GetRequestServices: string; procedure SendRequestData; protected procedure DoDestroy; override; procedure InternalOpen; override; procedure InternalClose(ANotifyPeer: Boolean); override; function GetDefaultPort: Integer; override; procedure SendKeepAlive; override; public constructor Create(AOwner: TComponent); override; procedure SendRequest; procedure Hello; procedure Login; procedure Logout; procedure SendCommand(const ACommand: string); overload; procedure SendCommand(const ACommand: IXMLDomNode); overload; property Request: TStrings read FRequest; property Response: TStrings read FResponse; property StatusCode: Integer read FStatusCode; property StatusText: string read FStatusText; property LastTransactionId: string read GetLastTransactionId; property ServerInfo: TclEppServerInfo read FServerInfo; property Authorized: Boolean read FAuthorized; published property Port default DefaultEppPort; property UserName: string read FUserName write SetUserName; property Password: string read FPassword write SetPassword; property RequestObjects: TStrings read FRequestObjects write SetRequestObjects; property RequestExtensions: TStrings read FRequestExtensions write SetRequestExtensions; property RequestLanguages: TStrings read FRequestLanguages write SetRequestLanguages; end; resourcestring NoRequestObjects = 'No request object is specified'; ResponseInvalid = 'The response is invalid'; ObjectInaccessible = 'The object is inaccessible: %s'; const NoRequestObjectsCode = -200; ResponseInvalidCode = -201; ObjectInaccessibleCode = -202; ClientTransactionPrefix = 'cltr'; implementation uses clUtils, clSocket, clSspi, clXmlUtils{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclEpp } constructor TclEpp.Create(AOwner: TComponent); begin inherited Create(AOwner); FServerInfo := TclEppServerInfo.Create(); FResponse := TStringList.Create(); FRequest := TStringList.Create(); FRequestLanguages := TStringList.Create(); FRequestExtensions := TStringList.Create(); FRequestObjects := TStringList.Create(); FRequestLanguages.Add('en'); end; procedure TclEpp.DoDestroy; begin FRequestObjects.Free(); FRequestExtensions.Free(); FRequestLanguages.Free(); FRequest.Free(); FResponse.Free(); FServerInfo.Free(); inherited DoDestroy(); end; function TclEpp.GetDefaultPort: Integer; begin Result := DefaultEppPort; end; function TclEpp.GetLastTransactionId: string; begin Result := ClientTransactionPrefix + IntToStr(FLastTransactionId); end; function TclEpp.GetNextTransactionId: string; begin Inc(FLastTransactionId); Result := '<clTRID>' + ClientTransactionPrefix + IntToStr(FLastTransactionId) + '</clTRID>'; end; function TclEpp.GetRequestLanguages: string; var i: Integer; begin Result := ''; for i := 0 to RequestLanguages.Count - 1 do begin Result := Result + '<lang>' + RequestLanguages[i] + '</lang>'; end; end; function TclEpp.GetRequestServices: string; var i: Integer; begin if (RequestObjects.Count < 1) then begin raise EclEppError.Create(NoRequestObjects, NoRequestObjectsCode); end; for i := 0 to RequestObjects.Count - 1 do begin if (ServerInfo.Objects.IndexOf(RequestObjects[i]) < 0) then begin raise EclEppError.Create(Format(ObjectInaccessible, [RequestObjects[i]]), ObjectInaccessibleCode); end; end; for i := 0 to RequestExtensions.Count - 1 do begin if (ServerInfo.Extensions.IndexOf(RequestExtensions[i]) < 0) then begin raise EclEppError.Create(Format(ObjectInaccessible, [RequestExtensions[i]]), ObjectInaccessibleCode); end; end; Result := '<svcs>'; for i := 0 to RequestObjects.Count - 1 do begin Result := Result + '<objURI>' + RequestObjects[i] + '</objURI>'; end; if (RequestExtensions.Count > 0) then begin Result := Result + '<svcExtension>'; for i := 0 to RequestExtensions.Count - 1 do begin Result := Result + '<extURI>' + RequestExtensions[i] + '</extURI>'; end; Result := Result + '</svcExtension>'; end; Result := Result + '</svcs>'; end; function TclEpp.GetRequestTitle: string; begin Result := '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'; Result := Result + '<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" '; Result := Result + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '; Result := Result + 'xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">'; end; procedure TclEpp.Hello; begin Request.Clear(); Request.Add(GetRequestTitle()); Request.Add('<hello/>'); Request.Add('</epp>'); SendRequestData(); ReadResponse(); ParseGreeting(); end; procedure TclEpp.InternalClose(ANotifyPeer: Boolean); begin try if Active and (not InProgress) then begin try Logout(); except on EclSocketError do ; on EclSSPIError do ; end; end; finally inherited InternalClose(ANotifyPeer); end; end; procedure TclEpp.InternalOpen; begin inherited InternalOpen(); FLastTransactionId := 0; ReadResponse(); ParseGreeting(); end; procedure TclEpp.Login; begin FAuthorized := False; Request.Clear(); Request.Add(GetRequestTitle()); Request.Add('<command>'); Request.Add('<login>'); Request.Add('<clID>' + UserName + '</clID>'); Request.Add('<pw>' + Password + '</pw>'); Request.Add('<options><version>1.0</version>' + GetRequestLanguages() + '</options>'); Request.Add(GetRequestServices()); Request.Add('</login>'); Request.Add(GetNextTransactionId()); Request.Add('</command>'); Request.Add('</epp>'); SendRequest(); FAuthorized := True; end; procedure TclEpp.Logout; begin if (not Authorized) then Exit; Request.Clear(); Request.Add(GetRequestTitle()); Request.Add('<command>'); Request.Add('<logout/>'); Request.Add(GetNextTransactionId()); Request.Add('</command>'); Request.Add('</epp>'); SendRequest(); FAuthorized := False; end; procedure TclEpp.ParseGreeting; var doc: IXMLDomDocument; greeting: IXMLDomNode; begin doc := CoDOMDocument.Create(); doc.loadXML(WideString(Response.Text)); if (not doc.parsed) then begin raise EclEppError.Create(doc.parseError.reason, doc.parseError.errorCode); end; greeting := GetNodeByName(doc.documentElement, 'greeting'); if (greeting = nil) then begin raise EclEppError.Create(ResponseInvalid, ResponseInvalidCode); end; FServerInfo.Parse(greeting); end; procedure TclEpp.ParseResponse; var doc: IXMLDomDocument; resp, result: IXMLDomNode; begin doc := CoDOMDocument.Create(); doc.loadXML(WideString(Response.Text)); if (not doc.parsed) then begin raise EclEppError.Create(doc.parseError.reason, doc.parseError.errorCode); end; resp := GetNodeByName(doc.documentElement, 'response'); if (resp = nil) then begin raise EclEppError.Create(ResponseInvalid, ResponseInvalidCode); end; result := GetNodeByName(resp, 'result'); FStatusCode := StrToIntDef(GetAttributeValue(result, 'code'), 0); FStatusText := GetNodeValueByName(result, 'msg'); if (FStatusCode >= 2000) then begin raise EclEppError.Create(FStatusText, FStatusCode); end; end; procedure TclEpp.ReadResponse; var ms: TMemoryStream; dataPos: Int64; len: DWORD; utils: TclStringsUtils; encoding: string; begin Response.Clear(); ms := nil; utils := nil; try ms := TMemoryStream.Create(); Connection.ReadData(ms); ms.Position := 0; len := EppReadInt32(ms); dataPos := ms.Position; while (ms.Size < len) do begin Connection.ReadData(ms); end; utils := TclStringsUtils.Create(Response, 'UTF-8'); utils.BatchSize := BatchSize; ms.Position := dataPos; utils.LoadStrings(ms); encoding := GetXmlCharSet(Response.Text, 'UTF-8'); if (UpperCase(encoding) <> 'UTF-8') then begin utils.CharSet := encoding; ms.Position := dataPos; utils.LoadStrings(ms); end; finally utils.Free(); ms.Free(); end; end; procedure TclEpp.SendCommand(const ACommand: IXMLDomNode); begin SendCommand(string(ACommand.xml)); end; procedure TclEpp.SendCommand(const ACommand: string); begin Request.Clear(); Request.Add(GetRequestTitle()); Request.Add('<command>'); Request.Add(ACommand); Request.Add(GetNextTransactionId()); Request.Add('</command>'); Request.Add('</epp>'); SendRequest(); end; procedure TclEpp.SendKeepAlive; begin Hello(); end; procedure TclEpp.SendRequest; begin SendRequestData(); ReadResponse(); ParseResponse(); end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} procedure TclEpp.SendRequestData; var ms: TMemoryStream; utils: TclStringsUtils; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsCertDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} ms := nil; utils := nil; try ms := TMemoryStream.Create(); utils := TclStringsUtils.Create(Request, GetXmlCharSet(Request.Text, 'UTF-8')); EppWriteInt32(ms, DWORD(utils.GetStringsSize() + 4)); utils.SaveStrings(ms); ms.Position := 0; Connection.WriteData(ms); finally utils.Free(); ms.Free(); end; end; procedure TclEpp.SetPassword(const Value: string); begin if (FPassword <> Value) then begin FPassword := Value; Changed(); end; end; procedure TclEpp.SetRequestExtensions(const Value: TStrings); begin FRequestExtensions.Assign(Value); Changed(); end; procedure TclEpp.SetRequestLanguages(const Value: TStrings); begin FRequestLanguages.Assign(Value); Changed(); end; procedure TclEpp.SetRequestObjects(const Value: TStrings); begin FRequestObjects.Assign(Value); Changed(); end; procedure TclEpp.SetUserName(const Value: string); begin if (FUserName <> Value) then begin FUserName := Value; Changed(); end; end; { TclEppServerInfo } procedure TclEppServerInfo.Clear; begin FId := ''; FDate := ''; FVersion := ''; FLanguages.Clear(); FObjects.Clear(); FExtensions.Clear(); FAccess := ''; FPurpose := ''; FRecipient := ''; FRetention := ''; end; constructor TclEppServerInfo.Create; begin inherited Create(); FLanguages := TStringList.Create(); FObjects := TStringList.Create(); FExtensions := TStringList.Create(); Clear(); end; destructor TclEppServerInfo.Destroy; begin FExtensions.Free(); FObjects.Free(); FLanguages.Free(); inherited Destroy(); end; procedure TclEppServerInfo.Parse(const AGreeting: IXMLDomNode); var node, statement: IXMLDomNode; begin Clear(); FId := GetNodeValueByName(AGreeting, 'svID'); FDate := GetNodeValueByName(AGreeting, 'svDate'); node := GetNodeByName(AGreeting, 'svcMenu'); if (node = nil) then raise EclEppError.Create(ResponseInvalid, ResponseInvalidCode); FVersion := GetNodeValueByName(node, 'version'); GetNodeValueListByName(node, 'lang', FLanguages); GetNodeValueListByName(node, 'objURI', FObjects); node := GetNodeByName(node, 'svcExtension'); if (node <> nil) then begin GetNodeValueListByName(node, 'extURI', FExtensions); end; node := GetNodeByName(AGreeting, 'dcp'); if (node = nil) then raise EclEppError.Create(ResponseInvalid, ResponseInvalidCode); FAccess := GetNodeXmlByName(node, 'access'); statement := GetNodeByName(node, 'statement'); if (statement = nil) then raise EclEppError.Create(ResponseInvalid, ResponseInvalidCode); FPurpose := GetNodeXmlByName(statement, 'purpose'); FRecipient := GetNodeXmlByName(statement, 'recipient'); FRetention := GetNodeXmlByName(statement, 'retention'); end; end.
unit dcCominationEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, dcEdit, dcEditBtn; type TdcCominationEdit = class(TdcEdit) private FCombination: string; procedure SetCombination(const Value: string); { Private declarations } protected { Protected declarations } procedure KeyPress(var Key: Char); override; public { Public declarations } published { Published declarations } property Combination:string read FCombination write SetCombination; end; TdcCombinationEditBtn = class(TdcEditBtn) private FCombination: string; procedure SetCombination(const Value: string); { Private declarations } protected { Protected declarations } procedure KeyPress(var Key: Char); override; public { Public declarations } published { Published declarations } property Combination:string read FCombination write SetCombination; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Data Entry', [TdcCominationEdit, TdcCombinationEditBtn]); end; { TdcCominationEdit } procedure TdcCominationEdit.KeyPress(var Key: Char); var chk : string; begin key := upcase(key); chk := key; if pos(chk, Combination) > 0 then // it is a valid char begin if pos(chk, text) = 0 then inherited // it hasn't been used yet so do the default action else key := #0; end else key := #0; end; procedure TdcCominationEdit.SetCombination(const Value: string); begin FCombination := uppercase(Value); MaxLength := length(Value); end; { TdcCombinationEditBtn } procedure TdcCombinationEditBtn.KeyPress(var Key: Char); var chk : string; begin // handle backspace if key=Char(8) then begin Inherited; Exit; end; key := upcase(key); chk := key; if pos(chk, Combination) > 0 then // it is a valid char begin if pos(chk, text) = 0 then inherited // it hasn't been used yet so do the default action else key := #0; end else key := #0; end; procedure TdcCombinationEditBtn.SetCombination(const Value: string); begin FCombination := uppercase(Value); MaxLength := length(Value); end; end.
unit ExtractorMain; {$DEFINE USE_DZIP_UNPACK} // recommended interface uses Windows, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, ShellAPI, ExtCtrls, ComCtrls, ZipMstr19, ZMMsgStr19, ZMMsg19, ZMDelZip19, ZMCompat19, SFXBehavior, ShlObj; type TOverwriteDecision = (odUndefined, odOverwriteAll, odOverwriteNothing); TMainForm = class(TForm) ProgressBar: TProgressBar; WaitLabel: TLabel; CancelBtn: TButton; CurrentFileLabel: TLabel; AutoTimer: TTimer; itemBar: TProgressBar; procedure CancelBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AutoTimerTimer(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private ExtractionInProcess: boolean; uz: TZipMaster19; RenamingOldPrefix: string; RenamingNewPrefix: string; zb: TZIPBehavior; BaseDir: string; AbortUnzip: boolean; StopAskingPassword: boolean; LastTriedPassword: string; CachedOverwriteDecision: TOverwriteDecision; {$IFNDEF USE_DZIP_UNPACK} procedure ExtractDllFromResource(ADirectory: string); {$ENDIF} procedure ExtractZipHere(AZipfile: string); procedure EvExtFNChange(Sender: TObject; var FileName: TZMString; const BaseDir: TZMString; var IsChanged: Boolean); procedure EvProgress(Sender: TObject; details: TZMProgressDetails); procedure EvTick(Sender: TObject); procedure EvCheckTerminate(Sender: TObject; var abort: Boolean); procedure EvConfirmOverwrite(Sender: TObject; const ForFile: TZMString; IsOlder: Boolean; var DoOverwrite: Boolean; DirIndex: Integer); procedure EvPasswordEvent(Sender: TObject; IsZipAction: Boolean; var NewPassword: String; const ForFile: TZMString; var RepeatCount: Longword; var Action: TMsgDlgBtn); procedure EvSkipEvent(Sender: TObject; const ForFile: TZMString; SkipType: TZMSkipTypes; var ExtError: Integer); function StripBaseDir(const s: string): string; end; var MainForm: TMainForm; implementation uses ExtractorPassword, ExtractorError, Functions, SFXAutoRun, ExtractorComment, BrowseFolder; const EvPasswordTries = 15; {$R *.dfm} {$R zmstr1900102\DLL\ResDLL-Maker\ZMRes19_dll.res} function IsRootFile(s: string): boolean; var i: integer; begin if s = '' then begin result := false; Exit; end; if LooksLikeDir(s) then begin s := Copy(s, 1, Length(s)-1); end; for i := 1 to Length(s) do begin if s[i] = PathDelim then begin result := false; Exit; end; end; result := true; end; function FEListAll(theRec: TZMDirEntry; var Data): Integer; var l: TStringList absolute Data; s: string; begin Result := 0; s := theRec.FileName; l.Add(s); s := ExtractFilePath(s); if l.IndexOf(s) = -1 then l.Add(s); end; procedure ListRootFiles(uz: TZipMaster19; List: TStringList); var s: string; l: TStringList; i: Integer; resourcestring Lng_ForeachFailed = 'Dateiiteration fehlgeschlagen!'; begin List.Clear; l := TStringList.Create; try // Fill list (inclusive Directories) uz.FSpecArgs.Add('*'); if uz.ForEach(FEListAll, l) <> 0 then begin MessageDlg(Lng_ForeachFailed, mtError, [mbOk], 0); end; // Now look for root files for i := 0 to l.Count - 1 do begin s := l.Strings[i]; if IsRootFile(s) then begin List.Add(s); end; end; finally l.Free; end; end; procedure TMainForm.ExtractZipHere(AZipfile: string); var l: TStringList; s: string; ec: Integer; ar: TExecuteSFXAutoRunResult; GeneralBaseDir: string; ok: boolean; const C_Explorer_Open_Param = '"%s"'; C_Explorer_Select_Param = '/n,/select,"%s"'; EXPLORER_EXE = 'explorer'; resourcestring Lng_Aborted = 'Der laufende Prozess wurde abgebrochen. Das extrahierten Dateien sind somit unvollständig.'; Lng_Zip_Error = 'ZIP-Master Fehler "%s" (%d)'; Lng_AutoRunFailed = 'SFX-AutoRun fehlgeschlagen. Die entpackten Inhalte werden nun angezeigt.'; Lng_Unknown_Error = 'Unbekannter Fehler: Dateien sind nicht aufzufinden!'; Lng_SelectDir = 'Bitte wählen Sie ein Verzeichnis zum Extrahieren aus. Es wird maximal 1 Datei bzw. Ordner erstellt!'; Lng_WriteProtected = 'Das Verzeichnis ist nicht schreibbar! Bitte wählen Sie ein Anderes.'; begin AZipfile := ExpandUNCFileName(AZipfile); RenamingOldPrefix := ''; RenamingNewPrefix := ''; if Assigned(uz) then uz.Free; // uz ist global, damit AbortDLL aufgerufen werden kann uz := TZipMaster19.Create(nil); try ExtractionInProcess := true; {$IFNDEF USE_DZIP_UNPACK} uz.DLLDirectory := GetTempDirectory + DelZipDLL_Name; {$ENDIF} uz.DLL_Load := true; uz.ZipFileName := AZipFile; uz.Active := true; zb := ReadBehavior(uz.ZipComment); uz.Unattended := true; uz.ExtrOptions := [ExtrDirNames, ExtrOverWrite, ExtrFreshen, ExtrUpdate, ExtrForceDirs, ExtrNTFS]; uz.OnExtractOverwrite := EvConfirmOverwrite; uz.OnProgress := EvProgress; uz.OnTick := EvTick; uz.OnCheckTerminate := EvCheckTerminate; uz.OnPasswordError := EvPasswordEvent; uz.PasswordReqCount := EvPasswordTries; uz.OnSkipped := EvSkipEvent; uz.OnSetExtName := EvExtFNChange; // Find out base dirtory GeneralBaseDir := ''; if zb.ExtractionTarget = etExtractHere then begin GeneralBaseDir := ExtractFilePath(AZipfile); // Default if not IsDirectoryWritable(GeneralBaseDir) or IsAtFlobbyDisk(GeneralBaseDir) then begin zb.ExtractionTarget := etDesktop; end; end; if zb.ExtractionTarget = etDesktop then begin GeneralBaseDir := GetSpecialFolderPath(CSIDL_DESKTOP); if not IsDirectoryWritable(GeneralBaseDir) or IsAtFlobbyDisk(GeneralBaseDir) then begin zb.ExtractionTarget := etAsk; end; end; if zb.ExtractionTarget = etAsk then begin repeat GeneralBaseDir := MySelectDirectory(Lng_SelectDir); if GeneralBaseDir = '' then Exit; ok := IsDirectoryWritable(GeneralBaseDir); if not ok then begin MessageDlg(Lng_WriteProtected, mtWarning, [mbOk], 0); end; until ok; end; GeneralBaseDir := IncludeTrailingPathDelimiter(GeneralBaseDir); // Semantic scanning of ZIP to determinate the final extraction directory l := TStringList.Create; try // Count the root objects (files OR dirs) in the ZIP ListRootFiles(uz, l); if l.Count = 0 then begin // Empty ZIP or Extractor.exe was called without ZIP attached Exit; end else if l.Count = 1 then begin // 1 Object = Extract it right here! BaseDir := GeneralBaseDir; s := BaseDir + l.Strings[0]; RenamingOldPrefix := l.Strings[0]; // = StripBaseDir(S); if zb.ConflictBehavior = cbAvoid then begin s := SearchNextFreeName(s, LooksLikeDir(s)); end; RenamingNewPrefix := StripBaseDir(s); end else begin // 2+ Objects = Extract them in a separate folder s := GeneralBaseDir + ExtractFileNameWithoutExt(AZipfile) + PathDelim; if zb.ConflictBehavior = cbAvoid then begin s := SearchNextFreeName(s, true); MkDir(s); end else begin if not DirectoryExists(s) then MkDir(s); end; BaseDir := s; end; BaseDir := IncludeTrailingPathDelimiter(BaseDir); uz.ExtrBaseDir := BaseDir; // Pre-Extract-Dialog if zb.CommentPresentation = cpBeforeExtracting then begin if not CommentForm.ShowCommentModal(uz.ZipComment) then exit; end; // Extract ec := uz.Extract; if ec <> 0 then begin if ec = DS_Canceled then begin MessageDlg(Lng_Aborted, mtWarning, [mbOk], 0); end else begin MessageDlg(Format(Lng_Zip_Error, [uz.ErrMessage, ec]), mtError, [mbOk], 0); end; end; // Errors? if ErrorForm.ErrorsAvailable then begin Hide; ErrorForm.ShowModal; end; // Show After-Extracting comment? if zb.CommentPresentation = cpAfterExtracting then begin if not CommentForm.ShowCommentModal(uz.ZipComment) then exit; end; // Now search for an AutoRun.inf ar := ExecuteSFXAutoRun(BaseDir); if ar.AutoRunSectionAvailable and not ar.ExecutionSucceed then begin MessageDlg(Lng_AutoRunFailed, mtError, [mbOk], 0); ar.OpenUnzippedContent := true; end; // Now open the file for the user if not ar.AutoRunSectionAvailable or ar.OpenUnzippedContent then begin if DirectoryExists(s) then begin // If it is a folder, open it ShellExecute(0, 'open', EXPLORER_EXE, PChar(Format(C_Explorer_Open_Param, [s])), '', SW_NORMAL); end else if FileExists(s) then begin // If it is a file, then only select it // Que: Funktioniert das auch ohne "/n"? // Im Moment wird bei einem BESTEHENDEN Fenster // die Selektion nicht durchgeführt. ShellExecute(0, 'open', EXPLORER_EXE, PChar(Format(C_Explorer_Select_Param, [s])), '', SW_NORMAL); end else begin if not AbortUnzip then begin MessageDlg(Lng_Unknown_Error, mtError, [mbOk], 0); end; end; end; finally l.Free; end; finally uz.Free; ExtractionInProcess := false; end; end; procedure TMainForm.EvProgress(Sender: TObject; details: TZMProgressDetails); begin CurrentFileLabel.Caption := details.ItemName; progressBar.Position := details.TotalPosition; progressBar.Max := details.TotalSize; itemBar.Position := details.ItemPosition; itemBar.Max := details.ItemSize; Application.ProcessMessages; end; procedure TMainForm.EvExtFNChange(Sender: TObject; var FileName: TZMString; const BaseDir: TZMString; var IsChanged: Boolean); begin if RenamingOldPrefix = RenamingNewPrefix then Exit; FileName := RenamingNewPrefix + Copy(FileName, 1+Length(RenamingOldPrefix), Length(FileName)-Length(RenamingOldPrefix)); IsChanged := true; end; procedure TMainForm.EvTick(Sender: TObject); begin Application.ProcessMessages; end; procedure TMainForm.EvCheckTerminate(Sender: TObject; var abort: Boolean); begin abort := AbortUnzip; end; procedure TMainForm.EvConfirmOverwrite(Sender: TObject; const ForFile: TZMString; IsOlder: Boolean; var DoOverwrite: Boolean; DirIndex: Integer); resourcestring Lng_Overwrite = 'Bestehende Datei "%s" überschreiben?'; var res: Integer; begin if zb.ConflictBehavior = cbOverwrite then begin DoOverwrite := true; Exit; end else if zb.ConflictBehavior = cbNewer then begin DoOverwrite := IsOlder; // If file on DISK is older, then overwrite. Exit; end else if zb.ConflictBehavior = cbAsk then begin // Workaround: Verzeichnisse brauchen das nicht, // denn es wird bei den Dateien nochmal nachgefragt if LooksLikeDir(ForFile) then begin DoOverwrite := true; Exit; end; if CachedOverwriteDecision = odUndefined then begin res := MessageDlg(Format(Lng_Overwrite, [ForFile]), mtConfirmation, [mbYes, mbNo, mbYesToAll, mbNoToAll], 0); DoOverwrite := (res = mrYes) or (res = mrYesToAll); if res = mrNoToAll then CachedOverwriteDecision := odOverwriteNothing; if res = mrYesToAll then CachedOverwriteDecision := odOverwriteAll; end else begin DoOverwrite := CachedOverwriteDecision = odOverwriteAll; end; end else if zb.ConflictBehavior = cbAvoid then begin // Nothing to do end; end; procedure TMainForm.EvPasswordEvent(Sender: TObject; IsZipAction: Boolean; var NewPassword: String; const ForFile: TZMString; var RepeatCount: Longword; var Action: TMsgDlgBtn); var repc: integer; begin repc := EvPasswordTries - RepeatCount + 1; // Eine Passworteingabe wurde abgebrochen. Frage nicht mehr nach. if StopAskingPassword then Exit; // Wurde schonmal ein Passwort eingegeben? if LastTriedPassword <> '' then begin // Schauen, ob das letzte Passwort auch mit dieser Datei geht. if repc = 1 then begin // Ja, geht NewPassword := LastTriedPassword; Exit; end else begin // Leider nein LastTriedPassword := ''; end; end; if PasswordDlg.ShowModal(StripBaseDir(ForFile), repc, EvPasswordTries) = mrOk then begin NewPassword := PasswordDlg.Password.Text; if NewPassword = '' then NewPassword := ' '; // Neue Eingabe erzwingen. LastTriedPassword := NewPassword; end else begin StopAskingPassword := true; Action := mbCancel; end; end; procedure TMainForm.CancelBtnClick(Sender: TObject); resourcestring Lng_AbortExtract = 'Extrahieren abbrechen?'; begin if not ExtractionInProcess then begin Close; Exit; end; if MessageDlg(Lng_AbortExtract, mtConfirmation, mbYesNoCancel, 0) = mrYes then begin CancelBtn.Enabled := false; uz.AbortDLL; AbortUnzip := true; // Close wird durch den Timer durchgeführt Exit; end; end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if not ExtractionInProcess then begin CanClose := true; Exit; end; if not AbortUnzip then begin CanClose := false; CancelBtn.Click; end; end; procedure TMainForm.FormCreate(Sender: TObject); resourcestring Lng_Extracting = 'Extrahiere Dateien. Bitte warten...'; begin WaitLabel.Caption := Lng_Extracting; WaitLabel.Left := progressBar.Width div 2 - WaitLabel.Width div 2; CurrentFileLabel.Caption := ''; end; {$IFNDEF USE_DZIP_UNPACK} procedure TMainForm.ExtractDllFromResource(ADirectory: string); var s: TResourceStream; o: TFileStream; AOutFile: string; begin AOutFile := IncludeTrailingPathDelimiter(ADirectory) + DelZipDLL_Name; s := TResourceStream.Create(0, DZRES_Dll, RT_RCDATA); try try s.Seek(SizeOf(Integer), soFromBeginning); // Ref: ZMDllLoad19.pas:427 if FileExists(AOutFile) then o := TFileStream.Create(AOutFile, fmOpenWrite or fmShareDenyNone) else o := TFileStream.Create(AOutFile, fmCreate or fmShareDenyNone); try o.CopyFrom(s, s.Size-s.Position); finally o.Free; end; except if FileExists(AOutFile) then begin // Probably the file is write-locked (maybe some other Extractor is // using it right now? Even if we run into danger that the target DLL // is a write-protected old/incompatible version of DelZip190.dll, // we do count this as success, since the file exists. end else begin raise; end; end; finally s.Free; end; end; {$ENDIF} procedure TMainForm.AutoTimerTimer(Sender: TObject); resourcestring Lng_NakedSFX = 'Das selbstentpackende Archiv (SFX) beschädigt oder ungültig. Wenn Sie diese Datei aus dem Internet bezogen haben, laden Sie sie bitte erneut herunter.'; Lng_FileNotFound = 'Die durch Parameter angegebene Datei "%s" kann nicht gefunden werden!'; Lng_TooManyArguments = 'Zu viele Argumente!'; begin AutoTimer.Enabled := false; {$IFNDEF USE_DZIP_UNPACK} ExtractDllFromResource(GetTempDirectory); {$ENDIF} try if IsExtractable(ParamStr(0)) then begin ExtractZipHere(ParamStr(0)); end else begin // Der Extractor ist "nackt" oder das SFX beschädigt if ParamCount = 0 then begin MessageDlg(Lng_NakedSFX, mtError, [mbOk], 0); end else if ParamCount = 1 then begin // In diesem Zustand erlauben wir, fremde SFX zu entpacken (auch für Debugging-Zwecke) if FileExists(ParamStr(1)) then begin ExtractZipHere(ParamStr(1)); end else begin MessageDlg(Lng_FileNotFound, mtError, [mbOk], 0); end; end else if ParamCount = 2 then begin // Future: Mehr als nur 1 Parameter erlauben? MessageDlg(Lng_TooManyArguments, mtError, [mbOk], 0); end; end; finally Close; end; end; function TMainForm.StripBaseDir(const s: string): string; begin // Warnung: Es wird nicht überprüft, ob der String auch // wirklich mit dem BaseDir beginnt! result := Copy(s, Length(BaseDir)+1, Length(s)-Length(BaseDir)); end; procedure TMainForm.EvSkipEvent(Sender: TObject; const ForFile: TZMString; SkipType: TZMSkipTypes; var ExtError: Integer); resourcestring Lng_PasswordWrong = 'Das Passwort wurde zu oft falsch eingegeben. Die Datei "%s" wird nicht extrahiert.'; begin if (SkipType = stBadPassword) and not StopAskingPassword then begin MessageDlg(Format(Lng_PasswordWrong, [ForFile]), mtError, [mbOk], 0); LastTriedPassword := ''; end; ErrorForm.NewError(ForFile, SkipType); end; end.
unit Cloud.Client; interface uses System.SysUtils, System.Classes, System.JSON, System.DateUtils, Net.Socket, Lib.Timer, Cloud.Consts, Cloud.Types, Cloud.Utils; type TCloudClient = class private KeepAliveTimer: TTimer; Delegate: TCloudDelegate; Client: TTCPSocket; Workload: Boolean; Host: string; Port: Word; ConnectionID: string; ReceiveString: string; AccessToken: string; function GetConnected: Boolean; function GetAuthorized: Boolean; function GetReady: Boolean; function GetAccessToken: string; procedure DoResponse(const S: string); procedure DoRecoveryConnection; procedure SendRequest(const Command,Args: string; const ShowArgs: string=''); procedure SendResponse(const Command,Args: string); procedure OnKeepAliveTimer(Sender: TObject); private procedure OnClientConnect(Sender: TObject); procedure OnClientAfterConnect(Sender: TObject); procedure OnClientRead(Sender: TObject); procedure OnClientClose(Sender: TObject); procedure OnClientException(Sender: TObject); public KeepAlive: Boolean; constructor Create; destructor Destroy; override; procedure SetEndPoint(const Host: string; Port: Word); procedure SetRecoveryInterval(Interval: Cardinal); procedure SetDelegate(Delegate: TCloudDelegate); procedure Connect; procedure Disconnect; procedure Unauthorized; procedure Cancel; procedure SendRequestRaw(const Command: string); procedure SendRequestRegistration(const Email,Password: string; AccountID: Int64); procedure SendRequestLogin(const Email,Password: string); procedure SendRequestAddresses(const Port: string); procedure SendRequestTransactions(const Port: string); procedure SendRequestCreateAddress(const Port: string); procedure SendRequestAddress(); procedure SendRequestInfo(const Port: string); procedure SendRequestSendTo(const Address: string; Amount: Extended; Confirm: Integer; const Port: string); procedure SendRequestRatio(); procedure SendRequestForging(Owner,SymbolID: Integer; const PayPort: string; BuyAmount,PayAmount,Ratio,Commission1,Commission2: Extended); procedure SendResponseForging(const Request,Result: string); procedure SendResponseAccountBalance(AmountRLC,AmountGTN: Extended); procedure SendRequestCreateOffer(Direction,Coin1,Coin2: Integer; Amount,Ratio: Extended; EndDate: TDateTime); procedure SendRequestOffers(SymbolID1,SymbolID2: Integer); procedure SendRequestOfferAccount; procedure SendResponseTransfer; procedure SendResponseError(Code: Integer; const Text: string=''); procedure SendRequestKillOffers(const Offers: TArray<Int64>); procedure SendRequestActiveOffers; procedure SendRequestClosedOffers(BeginDate,EndDate: TDateTime); procedure SendRequestHistoryOffers(BeginDate,EndDate: TDateTime); procedure SendRequestPairsSummary; procedure SendRequestCandles(SymbolID1,SymbolID2: Integer; BeginDate: TDateTime; IntervalType: Integer); procedure SendRequestSetNotifications(Enabled: Boolean); procedure SendRequestTradingHistory(SymbolID1,SymbolID2,Count: Integer); property Workloaded: Boolean read Workload; property Ready: Boolean read GetReady; property Connected: Boolean read GetConnected; property Authorized: Boolean read GetAuthorized; end; implementation { TCloudClient } constructor TCloudClient.Create; begin Host:=CLOUD_HOST_DEVNET; Port:=CLOUD_PORT_DEFAULT; Client:=TTCPSocket.Create; Client.OnConnect:=OnClientConnect; Client.OnAfterConnect:=OnClientAfterConnect; Client.OnReceived:=OnClientRead; Client.OnClose:=OnClientClose; Client.OnExcept:=OnClientException; KeepAliveTimer:=TTimer.Create(nil); KeepAliveTimer.Enabled:=False; KeepAliveTimer.OnTimer:=OnKeepAliveTimer; SetRecoveryInterval(4000); end; destructor TCloudClient.Destroy; begin Client.Free; KeepAliveTimer.Free; inherited; end; procedure TCloudClient.SetEndPoint(const Host: string; Port: Word); begin Self.Host:=Host; Self.Port:=Port; end; procedure TCloudClient.SetRecoveryInterval(Interval: Cardinal); begin KeepAliveTimer.Interval:=Interval; end; procedure TCloudClient.SetDelegate(Delegate: TCloudDelegate); begin Self.Delegate:=Delegate; end; function TCloudClient.GetConnected: Boolean; begin Result:=Client.Connected; end; function TCloudClient.GetAuthorized: Boolean; begin Result:=AccessToken<>''; end; function TCloudClient.GetReady: Boolean; begin Result:=Connected and Authorized; end; function TCloudClient.GetAccessToken: string; begin Result:=AccessToken; if Result.IsEmpty then Result:='*'; end; procedure TCloudClient.Unauthorized; begin AccessToken:=''; end; procedure TCloudClient.Cancel; begin Workload:=False; end; procedure TCloudClient.OnKeepAliveTimer(Sender: TObject); begin KeepAliveTimer.Enabled:=False; Connect; end; procedure TCloudClient.DoRecoveryConnection; begin KeepAliveTimer.Enabled:=True; end; procedure TCloudClient.OnClientAfterConnect(Sender: TObject); begin end; procedure TCloudClient.OnClientClose(Sender: TObject); begin Delegate.OnEvent(EVENT_DISCONNECTED,'connection closed'); ConnectionID:=''; if KeepAlive then DoRecoveryConnection; end; procedure TCloudClient.OnClientConnect(Sender: TObject); begin Delegate.OnEvent(EVENT_CONNECTED,'client connected'); end; procedure TCloudClient.OnClientException(Sender: TObject); begin Delegate.OnEvent(EVENT_EXCEPT,Client.E.Message); if KeepAlive then DoRecoveryConnection else Workload:=False; end; procedure TCloudClient.OnClientRead(Sender: TObject); var P: Integer; Command: string; begin ReceiveString:=ReceiveString+Client.ReceiveString; P:=ReceiveString.IndexOfAny([#10,#13]); Workload:=not ReceiveString.EndsWith(#10); while P<>-1 do begin Command:=ReceiveString.Substring(0,P); ReceiveString:=ReceiveString.Substring(P+1); if not Command.Trim.IsEmpty then DoResponse(Command); P:=ReceiveString.IndexOfAny([#10,#13]); end; end; procedure TCloudClient.Connect; begin if Client.Connected then Exit; ReceiveString:=''; Workload:=True; Delegate.OnEvent(EVENT_CONNECTING,'connecting... to '+Host+':'+Port.ToString); Client.Connect(Host,Port); end; procedure TCloudClient.Disconnect; begin ReceiveString:=''; Workload:=False; ConnectionID:=''; AccessToken:=''; Client.Disconnect; end; procedure TCloudClient.DoResponse(const S: string); var Response: TCloudResponse; begin Delegate.OnEvent(EVENT_RESPONSE,S); Response:=S; if Response.Command='c2' then begin var Init:=TCloudResponseInit(Response); ConnectionID:=Init.ConnectionID; Delegate.OnInit(Init); end else if Response.Command='URKError' then Delegate.OnError(Response) else if Response.Command='_RegLight' then Delegate.OnRegistration(Response) else if Response.Command='_StartClient' then begin var StartClient:=TCloudResponseLogin(Response); AccessToken:=StartClient.AccessToken; Delegate.OnLogin(StartClient); end else if Response.Command='GetCloudAdreses' then Delegate.OnAddresses(Response) else if Response.Command='CreateNewAdres' then Delegate.OnCreateAddress(Response) else if Response.Command='listtransactions' then Delegate.OnTransactions(Response) else if Response.Command='_GetCurAddresses' then Delegate.OnAddress(Response) else if Response.Command='GetWaletFullInfo' then Delegate.OnInfo(Response) else if Response.Command='SendFrom' then Delegate.OnSendTo(Response) else if Response.Command='_GetCrRatio' then Delegate.OnRatio(Response) else if Response.Command='UForging2' then Delegate.OnRequestForging(Response) else if Response.Command='_UForging' then Delegate.OnForging(Response) else if Response.Command='GetAccountBalance' then Delegate.OnRequestAccountBalance(Response) else if Response.Command='_CreateOffer' then Delegate.OnCreateOffer(Response) else if Response.Command='_GetOffersD' then Delegate.OnOffers(Response) else if Response.Command='_GetOfferAccount' then Delegate.OnOfferAccount(Response) else if Response.Command='UTransfer' then Delegate.OnRequestTransfer(Response) else if Response.Command='_UTransfer' then // Delegate. else if Response.Command='_KillOffer' then Delegate.OnKillOffers(Response) else if Response.Command='_GetActiveOffers' then Delegate.OnActiveOffers(Response) else if Response.Command='_GetClosedOffers' then Delegate.OnClosedOffers(Response) else if Response.Command='_GetHistoryOffers' then Delegate.OnHistoryOffers(Response) else if Response.Command='_GetPairsSummary' then Delegate.OnPairsSummary(Response) else if Response.Command='_SetNotifications' then Delegate.OnSetNotifications(Response) else if Response.Command='NotifyEvent' then Delegate.OnNotifyEvent(Response) else if Response.Command='_GetCandles' then Delegate.OnCandles(Response) else if Response.Command='_GetCandles' then Delegate.OnCandles(Response) else if Response.Command='_GetTradingHistory' then Delegate.OnTradingHistory(Response) else Delegate.OnError('* * 0'); end; procedure TCloudClient.SendRequest(const Command,Args: string; const ShowArgs: string=''); var C,S: string; begin C:=Command+' '+ConnectionID+' '+Args; if ShowArgs='' then S:=C else S:=Command+' '+ConnectionID+' '+ShowArgs; Delegate.OnEvent(EVENT_REQUEST,S); Workload:=True; Client.Send(C+#13); end; procedure TCloudClient.SendResponse(const Command,Args: string); var C: string; begin C:=Command+' '+ConnectionID+' '+Args; Delegate.OnEvent(EVENT_REQUEST,C); Workload:=False; Client.Send(C+#13); end; procedure TCloudClient.SendRequestRaw(const Command: string); var Request: TCloudRequest; begin Request:=Command; SendRequest(Request.Command,GetAccessToken+' '+Request.Args); end; procedure TCloudClient.SendRequestRegistration(const Email,Password: string; AccountID: Int64); begin SendRequest('RegLight',Email+' '+Password+' '+AccountID.ToString+' '+Password, Email+' ****** '+AccountID.ToString+' ******'); end; procedure TCloudClient.SendRequestLogin(const Email,Password: string); begin SendRequest('CheckPW',Email+' '+Password+' ipa',Email+' ****** ipa'); end; procedure TCloudClient.SendRequestAddresses(const Port: string); begin SendRequest('GetCloudAdreses',GetAccessToken+' * '+Port); end; procedure TCloudClient.SendRequestTransactions(const Port: string); begin SendRequest('listtransactions',GetAccessToken+' * '+Port); end; procedure TCloudClient.SendRequestCreateAddress(const Port: string); begin SendRequest('CreateNewAdres',GetAccessToken+' * '+Port); end; procedure TCloudClient.SendRequestAddress(); begin SendRequest('GetCurAddresses',GetAccessToken); end; procedure TCloudClient.SendRequestInfo(const Port: string); begin SendRequest('GetWaletFullInfo',GetAccessToken+' * '+Port); end; procedure TCloudClient.SendRequestSendTo(const Address: string; Amount: Extended; Confirm: Integer; const Port: string); begin SendRequest('SendFromTo',GetAccessToken+' '+Address+' '+AmountToStrI(Amount)+' '+ Confirm.ToString+' '+Port); end; procedure TCloudClient.SendRequestRatio(); begin SendRequest('GetCrRatio',GetAccessToken); end; procedure TCloudClient.SendRequestForging(Owner,SymbolID: Integer; const PayPort: string; BuyAmount,PayAmount,Ratio,Commission1,Commission2: Extended); begin SendRequest('UForging',GetAccessToken+' '+Owner.ToString+' '+SymbolID.ToString+' '+PayPort+' '+ AmountToStrI(BuyAmount)+' '+AmountToStrI(PayAmount)+' '+AmountToStrI(Ratio)+' '+ AmountToStrI(Commission1)+' '+AmountToStrI(Commission2)); end; procedure TCloudClient.SendResponseForging(const Request,Result: string); begin SendResponse('_UForging2',GetAccessToken+' <'+Request+'> '+Result); end; procedure TCloudClient.SendResponseAccountBalance(AmountRLC,AmountGTN: Extended); begin SendResponse('_GetAccountBalance',GetAccessToken+' '+AmountToStrI(AmountRLC)+' '+ AmountToStrI(AmountGTN)); end; procedure TCloudClient.SendRequestCreateOffer(Direction,Coin1,Coin2: Integer; Amount,Ratio: Extended; EndDate: TDateTime); begin SendRequest('CreateOffer',GetAccessToken+' 1 '+Direction.ToString+' '+Coin1.ToString+' '+ Coin2.ToString+' '+AmountToStrI(Amount)+' '+AmountToStrI(Ratio)+' '+DateTimeToUnix(EndDate,False).ToString); end; // False - local date to UTC function DefValue(Value: Integer; Default: string='*'): string; begin if Value=0 then Result:=Default else Result:=Value.ToString; end; procedure TCloudClient.SendRequestOffers(SymbolID1,SymbolID2: Integer); begin SendRequest('GetOffersD',GetAccessToken+' '+DefValue(SymbolID1)+' '+DefValue(SymbolID2)); end; procedure TCloudClient.SendRequestOfferAccount; begin SendRequest('GetOfferAccount',GetAccessToken); end; procedure TCloudClient.SendResponseTransfer; begin SendResponse('_UTransfer',GetAccessToken); end; function Join(Condition: Boolean; const S: string): string; begin if Condition then Result:=S else Result:=''; end; procedure TCloudClient.SendResponseError(Code: Integer; const Text: string); begin SendResponse('URKError',GetAccessToken+' '+Code.ToString+Join(not Text.IsEmpty,' "'+Text+'"')); end; procedure TCloudClient.SendRequestKillOffers(const Offers: TArray<Int64>); begin SendRequest('KillOffer',GetAccessToken+' '+ArrayToString(Offers,' ')); end; procedure TCloudClient.SendRequestActiveOffers; begin SendRequest('GetActiveOffers',GetAccessToken); end; procedure TCloudClient.SendRequestClosedOffers(BeginDate,EndDate: TDateTime); begin SendRequest('GetClosedOffers',GetAccessToken+' '+DateTimeToUnix(BeginDate,False).ToString+' '+ DateTimeToUnix(EndDate,False).ToString); end; procedure TCloudClient.SendRequestHistoryOffers(BeginDate,EndDate: TDateTime); begin SendRequest('GetHistoryOffers',GetAccessToken+' '+DateTimeToUnix(BeginDate,False).ToString+' '+ DateTimeToUnix(EndDate,False).ToString); end; procedure TCloudClient.SendRequestPairsSummary; begin SendRequest('GetPairsSummary',GetAccessToken); end; procedure TCloudClient.SendRequestCandles(SymbolID1,SymbolID2: Integer; BeginDate: TDateTime; IntervalType: Integer); begin SendRequest('GetCandles',GetAccessToken+' '+DefValue(SymbolID1)+' '+DefValue(SymbolID2)+' '+ DateTimeToUnix(BeginDate,False).ToString+' '+IntervalType.ToString); end; procedure TCloudClient.SendRequestSetNotifications(Enabled: Boolean); const V: array[Boolean] of string=('0','1'); begin SendRequest('SetNotifications',GetAccessToken+' '+V[Enabled]); end; procedure TCloudClient.SendRequestTradingHistory(SymbolID1,SymbolID2,Count: Integer); begin SendRequest('GetTradingHistory',GetAccessToken+' '+DefValue(SymbolID1)+' '+ DefValue(SymbolID2)+' '+Count.ToString); end; end.
Program Aufgabe6; {$codepage utf8} Var UserName: String; UserGroup: String; Rechtewahl: String; Rechte: String = ''; Begin Write('Bitte gib den Benutzernamen ein: '); ReadLn(UserName); Write('Bitte gib die Gruppe des Nutzers an: '); ReadLn(UserGroup); Write('Welche Rechte willst du sehen? (F - Dateirechte | P - Druckerrechte): '); ReadLn(Rechtewahl); Case UserGroup Of 'Admins': If Rechtewahl = 'F' Then Rechte := 'Erstellen, Lesen, Löschen, Korrigieren, Rechte vergeben' Else If Rechtewahl = 'P' Then Rechte := 'Drucken, Aufträge verwalten, Rechte vergeben'; 'PowerUsers': If Rechtewahl = 'F' Then Rechte := 'Erstellen, Lesen, Löschen, Korrigieren' Else If Rechtewahl = 'P' Then Rechte := 'Drucken, Aufträge verwalten'; 'Users': If Rechtewahl = 'F' Then Rechte := 'Erstellen, Lesen, Korrigieren' Else If Rechtewahl = 'P' Then Rechte := 'Drucken'; 'Guests': If Rechtewahl = 'F' Then Rechte := 'Lesen' Else If Rechtewahl = 'P' Then Rechte := 'Drucken'; End; If (Rechtewahl <> 'F') and (Rechtewahl <> 'P') Then WriteLn('Es gab einen Fehler bei der Eingabe: Die Rechtekategorie ', Rechtewahl, ' existiert nicht.') Else If Rechte = '' Then WriteLn('Es gab einen Fehler bei der Eingabe: Die Gruppe ', UserGroup, ' existiert nicht.') Else WriteLn(UserName, ' (Gruppe ', UserGroup, ')', LineEnding, 'Rechte für ', Rechtewahl, ': ', Rechte); End.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.FaultControl Description : Thread workers retry and circuit break Author : Kike Pérez Version : 1.5 Created : 20/06/2019 Modified : 02/12/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.FaultControl; {$i QuickLib.inc} interface uses SysUtils, SyncObjs, Quick.Commons; type TRetryEvent = procedure(aRaisedException : Exception; var vStopRetries : Boolean) of object; TMaxRetriesEvent = procedure of object; TCircuitBreakEvent = procedure of object; TFaultPolicy = class private fMaxRetries : Integer; fWaitTimeBetweenRetries : Integer; fWaitTimeMultiplierFactor : Double; public constructor Create; property MaxRetries : Integer read fMaxRetries write fMaxRetries; property WaitTimeBetweenRetries : Integer read fWaitTimeBetweenRetries write fWaitTimeBetweenRetries; property WaitTimeMultiplierFactor : Double read fWaitTimeMultiplierFactor write fWaitTimeMultiplierFactor; end; TFaultControl = class private fMaxRetries : Integer; fWaitTimeBetweenRetries : Integer; fWaitTimeMultiplierFactor : Double; fWaitTimeArray : TArray<Integer>; fNumRetries : Integer; fLastException : Exception; fCircuitBreaked : Boolean; fOnRetry : TRetryEvent; fOnCircuitBreak : TCircuitBreakEvent; fTaskFailed : Boolean; procedure WaitBeforeRetry(aNumWaitMilliseconds : Integer); procedure SetWaitTimeMultiplierFactor(const Value: Double); public constructor Create; destructor Destroy; override; property MaxRetries : Integer read fMaxRetries write fMaxRetries; property WaitTimeBetweenRetriesMS : Integer read fWaitTimeBetweenRetries write fWaitTimeBetweenRetries; property WaitTimeMultiplierFactor : Double read fWaitTimeMultiplierFactor write SetWaitTimeMultiplierFactor; property WaitTimeMSArray : TArray<Integer> read fWaitTimeArray write fWaitTimeArray; property OnRetry : TRetryEvent read fOnRetry write fOnRetry; property OnCircuitBreak : TCircuitBreakEvent read fOnCircuitBreak write fOnCircuitBreak; property TaskFailed : Boolean read fTaskFailed; property CircuitBreaked : Boolean read fCircuitBreaked; property LastException : Exception read fLastException; property NumRetries : Integer read fNumRetries; procedure FailedExecution(aException : Exception); procedure SuccessExecution; procedure Reset; function NeedToRetry : Boolean; end; EFaultControlConfigError = class(Exception); implementation { TFaultControl } constructor TFaultControl.Create; begin fTaskFailed := False; fLastException := nil; fOnRetry := nil; fOnCircuitBreak := nil; fCircuitBreaked := False; fNumRetries := 0; fMaxRetries := 0; fWaitTimeBetweenRetries := 0; fWaitTimeMultiplierFactor := 1; {$IFDEF DELPHIXE7_UP} fWaitTimeArray := []; {$ELSE} fWaitTimeArray := nil; {$ENDIF} end; function TFaultControl.NeedToRetry: Boolean; var waitretryMS : Integer; begin Result := False; if fTaskFailed then begin if (fMaxRetries <> 0) and (not fCircuitBreaked) then begin if (fNumRetries < fMaxRetries) or (fMaxRetries = -1) then begin Inc(fNumRetries); if Assigned(fOnRetry) then begin //can cancel next retries fOnRetry(fLastException,fCircuitBreaked); //if cancelled next retries, decrease current retries if fCircuitBreaked then fNumRetries := fNumRetries - 1; Result := not fCircuitBreaked; end else Result := True; //wait between retries if (Result) and (fMaxRetries <> 0) then begin if IsEmptyArray(fWaitTimeArray) then begin if fWaitTimeMultiplierFactor = 1 then waitretryMS := fWaitTimeBetweenRetries else waitretryMS := fWaitTimeBetweenRetries * Round(fNumRetries * fWaitTimeMultiplierFactor); end else waitretryMS := fWaitTimeArray[fNumRetries - 1]; if waitretryMS > 0 then WaitBeforeRetry(waitretryMS); end; end else fCircuitBreaked := True; if fCircuitBreaked then begin if Assigned(fOnCircuitBreak) then fOnCircuitBreak; if Assigned(fLastException) then raise fLastException; end; end; end; end; procedure TFaultControl.Reset; begin fCircuitBreaked := False; fTaskFailed := False; fNumRetries := 0; fLastException := nil; end; procedure TFaultControl.SetWaitTimeMultiplierFactor(const Value: Double); begin if Value = 0 then raise EFaultControlConfigError.Create('WaitTimeMultiplierFactor cannot be 0') else fWaitTimeMultiplierFactor := Value; end; procedure TFaultControl.SuccessExecution; begin fTaskFailed := False; end; procedure TFaultControl.WaitBeforeRetry(aNumWaitMilliseconds: Integer); var fEvent : TSimpleEvent; begin //Sleep(aNumWaitMilliseconds); {$IFDEF FPC} fEvent := TSimpleEvent.Create; {$ELSE} fEvent := TSimpleEvent.Create(nil,True,False,''); {$ENDIF} try fEvent.WaitFor(aNumWaitMilliseconds); finally fEvent.SetEvent; fEvent.Free; end; end; destructor TFaultControl.Destroy; begin //if Assigned(fLastException) then fLastException.Free; inherited; end; procedure TFaultControl.FailedExecution(aException: Exception); begin fTaskFailed := True; //free older exception if Assigned(fLastException) then fLastException.Free; fLastException := aException; if fMaxRetries = 0 then raise aException else if fNumRetries = fMaxRetries then begin aException.Message := Format('Max %d retries reached: %s',[fMaxRetries,aException.Message]); raise fLastException; end; end; { TFaultPolicy } constructor TFaultPolicy.Create; begin fMaxRetries := 0; fWaitTimeBetweenRetries := 0; fWaitTimeMultiplierFactor := 1; end; end.
unit MFichas.Model.Entidade.VENDAPAGAMENTOS; interface uses DB, Classes, SysUtils, Generics.Collections, /// orm ormbr.types.blob, ormbr.types.lazy, ormbr.types.mapping, ormbr.types.nullable, ormbr.mapping.classes, ormbr.mapping.register, ormbr.mapping.attributes; type [Entity] [Table('VENDAPAGAMENTOS', '')] [PrimaryKey('GUUID', NotInc, NoSort, False, 'Chave primária')] TVENDAPAGAMENTOS = class private { Private declarations } FGUUID: String; FVENDA: String; FTIPO: Integer; FVALOR: Double; FPARCELAS: Integer; FBANDEIRA: Integer; FSTATUS: Integer; FDATACADASTRO: TDateTime; FDATAALTERACAO: TDateTime; function GetDATAALTERACAO: TDateTime; function GetDATACADASTRO: TDateTime; function GetGUUID: String; public { Public declarations } [Column('GUUID', ftString, 38)] [Dictionary('GUUID', 'Mensagem de validação', '', '', '', taLeftJustify)] property GUUID: String read GetGUUID write FGUUID; [Column('VENDA', ftString, 38)] [Dictionary('VENDA', 'Mensagem de validação', '', '', '', taLeftJustify)] property VENDA: String read FVENDA write FVENDA; [Column('TIPO', ftInteger)] [Dictionary('TIPO', 'Mensagem de validação', '', '', '', taCenter)] property TIPO: Integer read FTIPO write FTIPO; [Column('VALOR', ftBCD, 18, 4)] [Dictionary('VALOR', 'Mensagem de validação', '0', '', '', taRightJustify)] property VALOR: Double read FVALOR write FVALOR; [Column('PARCELAS', ftInteger)] [Dictionary('PARCELAS', 'Mensagem de validação', '', '', '', taCenter)] property PARCELAS: Integer read FPARCELAS write FPARCELAS; [Column('BANDEIRA', ftInteger)] [Dictionary('BANDEIRA', 'Mensagem de validação', '', '', '', taCenter)] property BANDEIRA: Integer read FBANDEIRA write FBANDEIRA; [Column('STATUS', ftInteger)] [Dictionary('STATUS', 'Mensagem de validação', '', '', '', taCenter)] property STATUS: Integer read FSTATUS write FSTATUS; [Column('DATACADASTRO', ftDateTime)] [Dictionary('DATACADASTRO', 'Mensagem de validação', '', '', '', taCenter)] property DATACADASTRO: TDateTime read GetDATACADASTRO write FDATACADASTRO; [Column('DATAALTERACAO', ftDateTime)] [Dictionary('DATAALTERACAO', 'Mensagem de validação', '', '', '', taCenter)] property DATAALTERACAO: TDateTime read GetDATAALTERACAO write FDATAALTERACAO; end; implementation { TVENDAPAGAMENTOS } function TVENDAPAGAMENTOS.GetDATAALTERACAO: TDateTime; begin FDATAALTERACAO := Now; Result := FDATAALTERACAO; end; function TVENDAPAGAMENTOS.GetDATACADASTRO: TDateTime; begin if FDATACADASTRO = StrToDateTime('30/12/1899') then FDATACADASTRO := Now; Result := FDATACADASTRO; end; function TVENDAPAGAMENTOS.GetGUUID: String; begin if FGUUID.IsEmpty then FGUUID := TGUID.NewGuid.ToString; Result := FGUUID; end; initialization TRegisterClass.RegisterEntity(TVENDAPAGAMENTOS) end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 <http://www.gnu.org/licenses/>. } unit frmDBASystemParameters; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, jpeg, ExtCtrls, StdCtrls, cxButtons, cxCheckBox, cxGroupBox, cxRadioGroup, cxTextEdit, cxMemo, cxControls, cxContainer, cxEdit, cxPC, Ora; type TDBASystemParametersFrm = class(TForm) Panel1: TPanel; btnOK: TcxButton; btnCancel: TcxButton; pc: TcxPageControl; tsParameters: TcxTabSheet; tsNLSParameters: TcxTabSheet; Image1: TImage; cxGroupBox1: TcxGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; memCurrent: TcxMemo; memNew: TcxMemo; edtComment: TcxTextEdit; rgrpApplay: TcxRadioGroup; cxGroupBox2: TcxGroupBox; cboxSession: TcxCheckBox; cboxSystem: TcxCheckBox; cxGroupBox3: TcxGroupBox; Label4: TLabel; Label5: TLabel; memCurrent2: TcxMemo; memNew2: TcxMemo; procedure cboxSystemPropertiesChange(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); private { Private declarations } FParamType: integer; FOraSession: TOraSession; procedure SetType; public { Public declarations } procedure Init(ParamType: integer; Name, CurrentSetting, NewSetting, Comment, Session, System: string; AOraSession: TOraSession); end; var DBASystemParametersFrm: TDBASystemParametersFrm; implementation {$R *.dfm} uses frmDBA, util, VisualOptions, DBQuery, GenelDM; procedure TDBASystemParametersFrm.Init(ParamType: integer; Name, CurrentSetting, NewSetting, Comment, Session, System: string; AOraSession: TOraSession); begin DBASystemParametersFrm := TDBASystemParametersFrm.Create(Application); Self := DBASystemParametersFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FOraSession := AOraSession; caption := Name; FParamType := ParamType; if ParamType = 1 then //Parameters begin pc.ActivePage := tsParameters; memCurrent.Text := CurrentSetting; memNew.Text := NewSetting; edtComment.Text := Comment; cboxSession.Checked := Session = 'YES'; cboxSystem.Checked := System = 'YES'; cboxSession.Enabled := Session = 'YES'; cboxSystem.Enabled := System = 'YES'; SetType; end; if ParamType = 2 then //NLSParameters begin pc.ActivePage := tsNLSParameters; memCurrent2.Text := CurrentSetting; memNew2.Text := NewSetting; end; ShowModal; Free; end; procedure TDBASystemParametersFrm.SetType; begin rgrpApplay.Enabled := cboxSystem.Checked; end; procedure TDBASystemParametersFrm.cboxSystemPropertiesChange( Sender: TObject); begin SetType; end; procedure TDBASystemParametersFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TDBASystemParametersFrm.btnOKClick(Sender: TObject); var s: string; begin if FParamType = 1 then begin if memNew.Text = '' then begin MessageDlg('You must be enter New Setting', mtWarning, [mbOk], 0); Abort; end; if cboxSession.Checked then s := 'ALTER SESSION SET '+caption + ' = ' +memNew.Text; if cboxSystem.Checked then s := 'ALTER SYSTEM SET '+caption + ' = ' +memNew.Text; if cboxSystem.Checked then begin if edtComment.Text <> '' then s := s + ' Comment = '+Str(edtComment.Text); if rgrpApplay.ItemIndex = 0 then s := s + ' SCOPE = MEMORY '; if rgrpApplay.ItemIndex = 1 then s := s + ' SCOPE = spfile '; if rgrpApplay.ItemIndex = 2 then s := s + ' SCOPE = both '; s := s + ' sid=''*'' '; end; end; //FParamType if FParamType = 2 then begin if memNew2.Text = '' then begin MessageDlg('You must be enter New Setting', mtWarning, [mbOk], 0); Abort; end; s := 'ALTER SESSION SET '+caption + ' = '+memNew2.Text; end; //FParamType ExecSQL(s, 'System Altered', FOraSession); close; end; end.
unit Model.Funcoes; interface type TFuncoes = class private FID: System.Integer; FDescricao: System.string; FLog: System.string; public property ID: System.integer read FID write FID; property Descricao: System.string read FDEscricao write FDescricao; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFID: System.Integer; pFDescricao: System.string; pFLog: System.string); overload; end; implementation constructor TFuncoes.Create; begin inherited Create; end; constructor TFuncoes.Create(pFID: Integer; pFDescricao: string; pFLog: string); begin FID := pFID; FDescricao := pFDescricao; FLog := pFLog; end; end.
unit DW.VirtualKeyboardRect.Android; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface implementation uses // RTL System.Types, System.Messaging, System.SysUtils, // Android Androidapi.Helpers, Androidapi.JNI.Util, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.App, // FMX {$IF CompilerVersion > 32} FMX.Platform.UI.Android, {$ENDIF} FMX.Platform, FMX.Platform.Android, // DW DW.Messaging; type TVirtualKeyboardRect = class; TGlobalLayoutListener = class(TJavaLocal, JViewTreeObserver_OnGlobalLayoutListener) private FVirtualKeyboardRect: TVirtualKeyboardRect; public { JViewTreeObserver_OnGlobalLayoutListener } procedure onGlobalLayout; cdecl; public constructor Create(const AVirtualKeyboardRect: TVirtualKeyboardRect); end; TVirtualKeyboardRect = class(TInterfacedObject) private FDecorView: JView; FListener: JViewTreeObserver_OnGlobalLayoutListener; procedure ApplicationEventMessageHandler(const Sender: TObject; const M: TMessage); procedure InstallListener; procedure RemoveListener; procedure UpdateDecorView; protected procedure GlobalLayoutChange; public constructor Create; destructor Destroy; override; end; { TGlobalLayoutListener } constructor TGlobalLayoutListener.Create(const AVirtualKeyboardRect: TVirtualKeyboardRect); begin inherited Create; FVirtualKeyboardRect := AVirtualKeyboardRect; end; procedure TGlobalLayoutListener.onGlobalLayout; begin FVirtualKeyboardRect.GlobalLayoutChange; end; { TVirtualKeyboardRect } constructor TVirtualKeyboardRect.Create; begin inherited; TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ApplicationEventMessageHandler); end; destructor TVirtualKeyboardRect.Destroy; begin if FListener <> nil then RemoveListener; TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ApplicationEventMessageHandler); inherited; end; procedure TVirtualKeyboardRect.ApplicationEventMessageHandler(const Sender: TObject; const M: TMessage); begin case TApplicationEventMessage(M).Value.Event of TApplicationEvent.BecameActive: begin if FListener = nil then InstallListener; end; end; end; procedure TVirtualKeyboardRect.GlobalLayoutChange; var LVisibleRect: JRect; LMetrics: JDisplayMetrics; LKeyboardRect: TRect; begin UpdateDecorView; LVisibleRect := TJRect.Create; FDecorView.getWindowVisibleDisplayFrame(LVisibleRect); LMetrics := FDecorView.getContext.getResources.getDisplayMetrics; LKeyboardRect := TRectF.Create(ConvertPixelToPoint(TPointF.Create(0, LVisibleRect.height)), ConvertPixelToPoint(TPointF.Create(LMetrics.widthPixels, LMetrics.heightPixels - LVisibleRect.top))).Truncate; TMessageManager.DefaultManager.SendMessage(Self, TVirtualKeyboardRectChangeMessage.Create(LKeyboardRect)); end; procedure TVirtualKeyboardRect.InstallListener; begin UpdateDecorView; FListener := TGlobalLayoutListener.Create(Self); FDecorView.getViewTreeObserver.addOnGlobalLayoutListener(FListener); end; procedure TVirtualKeyboardRect.RemoveListener; begin UpdateDecorView; FDecorView.getViewTreeObserver.removeGlobalOnLayoutListener(FListener); end; procedure TVirtualKeyboardRect.UpdateDecorView; begin if FDecorView = nil then FDecorView := TAndroidHelper.Activity.getWindow.getDecorView; end; var VirtualKeyboardRect: TVirtualKeyboardRect; initialization VirtualKeyboardRect := TVirtualKeyboardRect.Create; end.
unit uProOrcamento; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils, Data.DB, uControleEstoque, uEnun, RxMemDS; type TOrcamento = class private ConexaoDB:TZConnection; F_OrcamentoId:Integer; F_clienteId:Integer; F_dataOrcamento:TDateTime; F_totalOrcamento: Double; F_Obs :string; F_Veiculo :string; F_FormaPagto :string; F_Status :string; F_TipoPeca :string; function EsteItemExiste(OrcamentoId, produtoId: Integer): Boolean; function InNot(cds: TRxMemoryData): String; function AtualizarItem(cds: TRxMemoryData): Boolean; function ApagaItens(cds: TRxMemoryData): Boolean; function InserirItens(cds: TRxMemoryData; IdVenda: Integer): Boolean; procedure RetornarEstoque(sCodigo: String; Acao:TAcaoExcluirEstoque); procedure BaixarEstoque(produtoId:Integer; Quantidade:Double); procedure GravaReceita(pIdOrcamento,pCliente :Integer; pValor :Double; pStatus :string); public constructor Create(aConexao:TZConnection); destructor Destroy; override; function Inserir(cds:TRxMemoryData):Integer; function Atualizar(cds:TRxMemoryData):Boolean; function Apagar:Boolean; function Selecionar(id:Integer; var cds:TRxMemoryData):Boolean; published property OrcamentoId:Integer read F_OrcamentoId write F_OrcamentoId; property ClienteId:Integer read F_clienteId write F_clienteId; property DataOrcamento:TDateTime read F_dataOrcamento write F_dataOrcamento; property TotalOrcamento:Double read F_totalOrcamento write F_totalOrcamento; property Obs : string read F_Obs write F_Obs; property Veiculo : string read F_Veiculo write F_Veiculo; property FormaPagto:string read F_FormaPagto write F_FormaPagto; property Status :string read F_Status write F_Status; property TipoPeca :string read F_TipoPeca write F_TipoPeca; end; implementation { TCategoria } {$region 'Constructor and Destructor'} constructor TOrcamento.Create(aConexao:TZConnection); begin ConexaoDB:=aConexao; end; destructor TOrcamento.Destroy; begin inherited; end; {$endRegion} {$region 'CRUD'} function TOrcamento.Apagar: Boolean; var Qry:TZQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Venda Nro: '+IntToStr(F_OrcamentoId),mtConfirmation,[mbYes, mbNo],0)=mrNo then begin Result:=false; abort; end; try Result:=true; ConexaoDB.StartTransaction; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; //Apaga os Itens Primeiro Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM OrcamentoItens '+ ' WHERE OrcItens_CodId=:OrcItens_CodId '); Qry.ParamByName('OrcItens_CodId').AsInteger :=F_OrcamentoId; Try Qry.ExecSQL; //Apaga a Tabela Master Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM ORCAMENTO '+ ' WHERE Orc_OrcId=:Orc_OrcId '); Qry.ParamByName('Orc_OrcId').AsInteger :=F_OrcamentoId; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.InNot(cds:TRxMemoryData):String; var sInNot:String; begin sInNot:=EmptyStr; cds.First; while not cds.Eof do begin if sInNot=EmptyStr then sInNot := cds.FieldByName('Prod_Cod').AsString else sInNot := sInNot +','+cds.FieldByName('Prod_Cod').AsString; cds.Next; end; Result:=sInNot; end; function TOrcamento.Atualizar(cds:TRxMemoryData): Boolean; var Qry:TZQuery; begin try Result:=true; ConexaoDB.StartTransaction; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE ORCAMENTO '+ ' SET Orc_CodCli=:Orc_CodCli '+ ' ,Orc_DataOrcamento=:Orc_DataOrcamento '+ ' ,Orc_TotalOrcamento=:Orc_TotalOrcamento '+ ' ,Orc_Obs =:Orc_Obs'+ ' ,Orc_Veiculo =:Orc_Veicluo'+ ' ,Orc_FormPagto =:orc_FormPagto'+ ' ,Orc_Status =:Orc_Status'+ ' WHERE Orc_OrcId=:Orc_OrcId '); Qry.ParamByName('Orc_OrcId').AsInteger :=Self.F_OrcamentoId; Qry.ParamByName('Orc_CodCli').AsInteger :=Self.F_clienteId; Qry.ParamByName('Orc_DataOrcamento').AsDateTime :=Self.F_dataOrcamento; Qry.ParamByName('totalVenda').AsFloat :=Self.F_totalOrcamento; Qry.ParamByName('Orc_Obs').AsString :=Self.F_Obs; Qry.ParamByName('Orc_Veiculo').AsString :=Self.F_Veiculo; Qry.ParamByName('Orc_FormPagto').AsString := Self.F_FormaPagto; Qry.ParamByName('Orc_Status').AsString := Self.F_Status; Try //Update Qry.ExecSQL; //Apagar Itens no banco que foram apagados na tela ApagaItens(cds); cds.First; while not cds.Eof do begin if EsteItemExiste(Self.F_OrcamentoId, cds.FieldByName('Prod_Cod').AsInteger) then begin AtualizarItem(cds); end else begin InserirItens(cds, Self.F_OrcamentoId); end; cds.Next; end; ConexaoDB.Commit; Except Result:=false; ConexaoDB.Rollback; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.AtualizarItem(cds:TRxMemoryData): Boolean; var Qry:TZQuery; begin try Result:=true; RetornarEstoque(cds.FieldByName('Prod_Cod').AsString, aeeAlterar); Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE OrcamentoItens '+ ' SET OrcItens_ValorUnitario =:OrcItens_ValorUnitario '+ ' ,OrcItens_Quantidade =:OrcItens_Quantidade '+ ' ,OrcItens_TotalProduto =:OrcItens_TotalProduto '+ ' ,OrcItens_Operacao =:OrcItens_Operacao '+ ' ,OrcItens_Desc =:OrcItens_Desc'+ ' ,OrcItens_Hora =:OrcItens_Hora'+ ' ,OrcItens_Pintura =:OrcItens_Pintura'+ ' WHERE OrcItens_CodId=:OrcItens_CodId AND OrcItens_prodId=:OrcItens_prodId '); Qry.ParamByName('OrcItens_CodId').AsInteger :=Self.F_OrcamentoId; Qry.ParamByName('OrcItens_prodId').AsInteger :=cds.FieldByName('OrcItens_prodId').AsInteger; Qry.ParamByName('OrcItens_ValorUnitario').AsFloat:=cds.FieldByName('OrcItens_ValorUnitario').AsFloat; Qry.ParamByName('OrcItens_Quantidade').AsFloat :=cds.FieldByName('OrcItens_Quantidade').AsFloat; Qry.ParamByName('OrcItens_TotalProduto').AsFloat :=cds.FieldByName('OrcItens_TotalProduto').AsFloat; Qry.ParamByName('OrcItens_Operacao').AsString :=cds.FieldByName('OrcItens_Operacao').AsString; Qry.ParamByName('OrcItens_Desc').AsFloat :=cds.FieldByName('OrcItens_Desc').AsFloat; Qry.ParamByName('OrcItens_Hora').AsFloat :=cds.FieldByName('OrcItens_Hora').AsFloat; Qry.ParamByName('OrcItens_Pintura').AsFloat :=cds.FieldByName('OrcItens_Pintura').AsFloat; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; BaixarEstoque(cds.FieldByName('OrcItens_prodId').AsInteger, cds.FieldByName('OrcItens_Quantidade').AsFloat); Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; Procedure TOrcamento.RetornarEstoque(sCodigo:String; Acao:TAcaoExcluirEstoque); var Qry:TZQuery; oControleEstoque:TControleEstoque; begin Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add( ' SELECT OrcItens_prodId, OrcItens_Quantidade '+ ' FROM OrcamentoItens '+ ' WHERE OrcItens_CodId=:OrcItens_CodId '); if Acao=aeeApagar then Qry.SQL.Add(' AND OrcItens_prodId NOT IN ('+sCodigo+') ') else Qry.SQL.Add(' AND OrcItens_prodId = ('+sCodigo+') '); Qry.ParamByName('OrcItens_prodId').AsInteger :=Self.F_OrcamentoId; Try oControleEstoque:=TControleEstoque.Create(ConexaoDB); Qry.Open; Qry.First; while not Qry.Eof do begin oControleEstoque.ProdutoId :=Qry.FieldByName('OrcItens_prodId').AsInteger; oControleEstoque.Quantidade :=Qry.FieldByName('OrcItens_Quantidade').AsFloat; oControleEstoque.RetornarEstoque; Qry.Next; end; Finally if Assigned(oControleEstoque) then FreeAndNil(oControleEstoque); End; end; Procedure TOrcamento.BaixarEstoque(produtoId:Integer; Quantidade:Double); var oControleEstoque:TControleEstoque; begin Try oControleEstoque:=TControleEstoque.Create(ConexaoDB); oControleEstoque.ProdutoId :=produtoId; oControleEstoque.Quantidade :=Quantidade; oControleEstoque.BaixarEstoque; Finally if Assigned(oControleEstoque) then FreeAndNil(oControleEstoque); End; end; function TOrcamento.ApagaItens(cds:TRxMemoryData): Boolean; var Qry:TZQuery; sCodNoCds:String; begin try Result:=true; //Pega os codigos que estão no Cliente para Selecionar o In Not no Banco de Dados sCodNoCds:= InNot(cds); //Retorna ao Estoque RetornarEstoque(sCodNoCds, aeeApagar); Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(' DELETE '+ ' FROM OrcamentoItens '+ ' WHERE OrcItens_CodId=:OrcItens_CodId '+ ' AND OrcItens_prodId NOT IN ('+sCodNoCds+') '); Qry.ParamByName('OrcItens_CodId').AsInteger :=Self.F_OrcamentoId; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.Inserir(cds:TRxMemoryData): Integer; var Qry:TZQuery; IdVendaGerado:Integer; begin try ConexaoDB.StartTransaction; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; //Faz a Inclusão no Banco de Dados Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO ORCAMENTO (Orc_CodCli, Orc_DataOrcamento, Orc_TotalOrcamento,orc_Obs,Orc_Veiculo,orc_FormaPagto,Orc_Status) '+ ' VALUES (:Orc_CodCli,:Orc_DataOrcamento,:Orc_TotalOrcamento,:Orc_Obs,:Orc_Veiculo,:Orc_FormaPagto,:Orc_Status )'); Qry.ParamByName('Orc_CodCli').AsInteger :=Self.F_clienteId; Qry.ParamByName('Orc_DataOrcamento').AsDateTime :=Self.F_dataOrcamento; Qry.ParamByName('Orc_TotalOrcamento').AsFloat :=Self.F_totalOrcamento; Qry.ParamByName('Orc_Obs').AsString :=Self.F_Obs; Qry.ParamByName('Orc_Veiculo').AsString :=Self.F_Veiculo; Qry.ParamByName('Orc_formaPagto').AsString :=Self.FormaPagto; Qry.ParamByName('Orc_Status').AsString :=Self.F_Status; Try Qry.ExecSQL; //Recupera o ID Gerado no Insert Qry.SQL.Clear; Qry.SQL.Add('SELECT SCOPE_IDENTITY() AS ID'); Qry.Open; //Id da tabela Master (Venda) IdVendaGerado:=Qry.FieldByName('ID').AsInteger; {$region 'Gravar na tabela VendasItens'} cds.First; while not cds.Eof do begin InserirItens(cds, IdVendaGerado); cds.Next; end; {$endRegion} if Trim(Self.F_Status) = 'FECHADO' then begin GravaReceita(Qry.FieldByName('ID').AsInteger,Self.F_clienteId,Self.F_totalOrcamento,Self.F_Status) end; ConexaoDB.Commit; Result := IdVendaGerado; Except ConexaoDB.Rollback; Result:=-1; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; procedure TOrcamento.GravaReceita(pIdOrcamento,pCliente:Integer;pValor:Double;pStatus:String); var Qry:TZQuery; begin try Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO RECEITA'+ '(Rec_Tipo, '+ ' Rec_Descricao,'+ ' Rec_DataVencimento,'+ ' Rec_Valor,'+ ' Rec_Status'+ ' VALUES' + '(:Rec_Tipo, '+ ' :Rec_Descricao, '+ ' :Rec_DtVencimento,'+ ' :Rec_Valor,'+ ' :Rec_Status)'); Qry.ParamByName('Rec_Tipo').AsInteger := 1; Qry.ParamByName('Rec_Descricao').AsString := 'Recebimento do Orçamento: '+ IntToStr( pIdOrcamento) + 'do Cliente :'+IntToStr(pCliente); Qry.ParamByName('Rec_DtVencimento').AsDateTime :=Now; Qry.ParamByName('Rec_Valor').AsFloat :=pValor; Qry.ParamByName('Rec_Status').AsString :=pStatus; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.InserirItens(cds:TRxMemoryData; IdVenda:Integer):Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO OrcamentoItens ( OrcItens_OrcId'+ ',OrcItens_prodId'+ ',OrcItens_ValorUnitario'+ ',OrcItens_Quantidade'+ ', OrcItens_TotalProduto'+ ',OrcItens_Operacao'+ ',OrcItens_Desc'+ ',OrcItens_Hora'+ ',OrcItens_Pintura'+ ') '+ ' VALUES (:OrcItens_OrcId'+ ',:OrcItens_prodId'+ ',:OrcItens_ValorUnitario'+ ',:OrcItens_Quantidade'+ ',:OrcItens_TotalProduto'+ ',:OrcItens_Operacao'+ ',:OrcItens_Desc'+ ',:OrcItens_Hora'+ ',:OrcItens_Pintura'+ ') '); Qry.ParamByName('OrcItens_OrcId').AsInteger := IdVenda; Qry.ParamByName('OrcItens_prodId').AsInteger := cds.FieldByName('OrcItens_prodId').AsInteger; Qry.ParamByName('OrcItens_ValorUnitario').AsFloat:= cds.FieldByName('OrcItens_ValorUnitario').AsFloat; Qry.ParamByName('OrcItens_Quantidade').AsFloat := cds.FieldByName('OrcItens_Quantidade').AsFloat; Qry.ParamByName('OrcItens_TotalProduto').AsFloat := cds.FieldByName('OrcItens_TotalProduto').AsFloat; Qry.ParamByName('OrcItens_Operacao').AsString :=cds.FieldByName('OrcItens_Operacao').AsString; Qry.ParamByName('OrcItens_Desc').AsFloat :=cds.FieldByName('OrcItens_Desc').AsFloat; Qry.ParamByName('OrcItens_Hora').AsFloat :=cds.FieldByName('OrcItens_Hora').AsFloat; Qry.ParamByName('OrcItens_Pintura').AsFloat :=cds.FieldByName('OrcItens_Pintura').AsFloat; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; BaixarEstoque(cds.FieldByName('OrcItens_prodId').AsInteger, cds.FieldByName('OrcItens_Quantidade').AsFloat); Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.Selecionar(id: Integer; var cds:TRxMemoryData): Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT Orc_OrcId '+ ' ,Orc_CodCli '+ ' ,Orc_DataOrcamento '+ ' ,Orc_TotalOrcamento '+ ' ,Orc_Veiculo '+ ' ,Orc_Formapagto '+ ' ,Orc_Status '+ ' ,Orc_Obs '+ ' FROM ORCAMENTO '+ ' WHERE Orc_OrcId=:Orc_OrcId'); Qry.ParamByName('Orc_OrcId').AsInteger:=id; Try Qry.Open; Self.F_OrcamentoId := Qry.FieldByName('Orc_OrcId').AsInteger; Self.F_clienteId := Qry.FieldByName('Orc_CodCli').AsInteger; Self.F_dataOrcamento := Qry.FieldByName('Orc_DataOrcamento').AsDateTime; Self.F_totalOrcamento := Qry.FieldByName('Orc_TotalOrcamento').AsFloat; Self.F_Obs := Qry.FieldByName('Orc_Obs').AsString; Self.F_Veiculo := Qry.FieldByName('Orc_Veiculo').AsString; Self.F_FormaPagto := Qry.FieldByName('Orc_FormaPagto').AsString; Self.F_Status := Qry.FieldByName('Orc_Status').AsString; {$region 'SELECIONAR na tabela VendasItens'} //Apaga o ClientDataSet Caso esteja com Registro cds.First; while not cds.Eof do begin cds.Delete; end; //Seleciona os Itens do Banco de dados com a propriedade F_VendaId Qry.Close; Qry.SQL.Clear; Qry.SQL.Add('SELECT OrcamentoItens.OrcItens_CodId, '+ ' Produtos.Prod_Nome, '+ ' OrcamentoItens.OrcItens_prodId,'+ ' OrcamentoItens.OrcItens_ValorUnitario, '+ ' OrcamentoItens.OrcItens_Quantidade, '+ ' OrcamentoItens.OrcItens_TotalProduto, '+ ' OrcamentoItens.OrcItens_Operacao,' + ' OrcamentoItens.OrcItens_Desc,'+ ' OrcamentoItens.OrcItens_Hora,'+ ' OrcamentoItens.OrcItens_Pintura'+ ' FROM OrcamentoItens '+ ' INNER JOIN produtos On Produtos.Prod_Cod = OrcamentoItens.OrcItens_prodId '+ ' WHERE OrcamentoItens.OrcItens_CodId=:OrcItens_CodId '); Qry.ParamByName('OrcItens_CodId').AsInteger := Self.F_OrcamentoId; Qry.Open; //Pega da Query e Coloca no ClientDataSet Qry.First; while not Qry.Eof do begin cds.Append; cds.FieldByName('OrcItens_prodId').AsInteger := Qry.FieldByName('OrcItens_prodId').AsInteger; cds.FieldByName('Prod_Nome').AsString := Qry.FieldByName('Prod_Nome').AsString; cds.FieldByName('OrcItens_ValorUnitario').AsFloat := Qry.FieldByName('OrcItens_ValorUnitario').AsFloat; cds.FieldByName('OrcItens_Quantidade').AsFloat := Qry.FieldByName('OrcItens_Quantidade').AsFloat; cds.FieldByName('OrcItens_TotalProduto').AsFloat := Qry.FieldByName('OrcItens_TotalProduto').AsFloat; cds.FieldByName('OrcItens_Operacao').AsString := Qry.FieldByName('OrcItens_Operacao').AsString; cds.FieldByName('OrcItens_Desc').AsFloat := Qry.FieldByName('OrcItens_Desc').AsFloat; cds.FieldByName('OrcItens_Hora').AsFloat := Qry.FieldByName('OrcItens_Hora').AsFloat; cds.FieldByName('OrcItens_Pintura').AsFloat := Qry.FieldByName('OrcItens_Pintura').AsFloat; cds.Post; Qry.Next; end; cds.First; {$endRegion} Except Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TOrcamento.EsteItemExiste(OrcamentoId: Integer; produtoId:Integer): Boolean; var Qry:TZQuery; begin try Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT Count(OrcItens_CodId) AS Qtde '+ ' FROM OrcamentoItens '+ ' WHERE OrcItens_CodId=:OrcItens_CodId and OrcItens_prodId=:OrcItens_prodId '); Qry.ParamByName('OrcItens_CodId').AsInteger :=OrcamentoId; Qry.ParamByName('produtoId').AsInteger :=produtoId; Try Qry.Open; if Qry.FieldByName('Qtde').AsInteger>0 then Result:=true else Result:=False; {$endRegion} Except Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; {$endregion} end.
unit ExtAIStates; interface uses Classes, SysUtils, ExtAIMsgStates, ExtAIStatesTerrain, ExtAINetClient, ExtAISharedInterface; // States of the ExtAI type TExtAIStates = class private fMsg: TExtAIMsgStates; fClient: TExtAINetClient; // Game variables fTerrain: TExtAIStatesTerrain; // Send state via client procedure SendState(aData: Pointer; aLength: Cardinal); public constructor Create(aClient: TExtAINetClient); destructor Destroy(); override; // Connect Msg directly with creator of ExtAI so he can type Actions.XY instead of Actions.Msg.XY property Msg: TExtAIMsgStates read fMsg; property Terrain: TExtAIStatesTerrain read fTerrain; // States from perspective of the ExtAI function MapHeight(): Word; function MapWidth(): Word; function TileIsPassable(aHeight,aWidth: Word): boolean; function Passability(): TBoolArr; function TileIsFertile(aHeight,aWidth: Word): boolean; function Fertility(): TBoolArr; end; implementation { TExtAIStates } constructor TExtAIStates.Create(aClient: TExtAINetClient); begin Inherited Create; fClient := aClient; fMsg := TExtAIMsgStates.Create(); fTerrain := TExtAIStatesTerrain.Create(fMsg); // Connect callbacks fMsg.OnSendState := SendState; end; destructor TExtAIStates.Destroy(); begin fMsg.Free; fTerrain.Free; fClient := nil; Inherited; end; procedure TExtAIStates.SendState(aData: Pointer; aLength: Cardinal); begin Assert(fClient <> nil, 'State cannot be send because client = nil'); fClient.SendMessage(aData, aLength); end; function TExtAIStates.MapHeight(): Word; begin Result := Terrain.MapHeight; end; function TExtAIStates.MapWidth(): Word; begin Result := Terrain.MapWidth; end; function TExtAIStates.TileIsPassable(aHeight,aWidth: Word): boolean; begin Result := False; if (aHeight > 0) AND (aHeight <= Terrain.MapHeight) AND (aWidth > 0) AND (aWidth <= Terrain.MapWidth) AND (Length(Terrain.Passability) > aWidth * aHeight + aWidth) then Result := Terrain.Passability[Terrain.MapWidth * aHeight + aWidth]; end; function TExtAIStates.Passability(): TBoolArr; begin Result := Terrain.Passability; end; function TExtAIStates.TileIsFertile(aHeight,aWidth: Word): boolean; begin Result := False; if (aHeight > 0) AND (aHeight <= Terrain.MapHeight) AND (aWidth > 0) AND (aWidth <= Terrain.MapWidth) AND (Length(Terrain.Fertility) > aWidth * aHeight + aWidth) then Result := Terrain.Fertility[Terrain.MapWidth * aHeight + aWidth]; end; function TExtAIStates.Fertility(): TBoolArr; begin Result := Terrain.Fertility; end; end.
unit uSceneCraft; interface uses uScene, Graphics, uGraph, uResFont, uButton; type TSceneCraft = class(TSceneCustom) private FT: Integer; FF, FK, FBG, FLogo, VL, HL: TBitmap; FGraph: TGraph; FFont: TResFont; FLeft, FTop: Integer; FVCursorPos, FHCursorPos: Integer; FCraftBtn, FCloseBtn: TButton; procedure Craft(); procedure Close(); public //** Конструктор. constructor Create; destructor Destroy; override; procedure Draw(); override; function Enum(): TSceneEnum; override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; procedure MakeBG; end; var SceneCraft: TSceneCraft; implementation uses SysUtils, uUtils, uIni, uSounds, uVars, uSCR, uSaveLoad, uGUIBorder, uColors, uBox, uInvBox; { TCraftScene } constructor TSceneCraft.Create; begin FTop := 100; FLeft := 50; FVCursorPos := 0; FHCursorPos := 0; FGraph := TGraph.Create(Path + 'Data\Images\GUI\'); FFont := TResFont.Create; FFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); FLogo := TBitmap.Create; FBG := TBitmap.Create; FGraph.LoadImage('BG.bmp', FBG); FBG.Width := 700; FBG.Height := 400; FBG.Canvas.Draw(400, 0, FBG); GUIBorder.Make(FBG); VL := TBitmap.Create; VL.Assign(GUIBorder.VLine); VL.Height := 381; HL := TBitmap.Create; HL.Assign(GUIBorder.HLine); HL.Width := 260; FK := TBitmap.Create; FF := TBitmap.Create; FF.Canvas.Font.Name := FFont.FontName; FF.Canvas.Brush.Style := bsClear; FF.Canvas.Font.Size := 16; FF.Canvas.Font.Color := cNormRare; FCraftBtn := TButton.Create(330, 440, FF.Canvas, 'Создать'); FCloseBtn := TButton.Create(540, 440, FF.Canvas, 'Закрыть'); end; function TSceneCraft.Enum: TSceneEnum; begin Result := scCraft; end; destructor TSceneCraft.Destroy; begin FGraph.Free; FCraftBtn.Free; FCloseBtn.Free; FFont.Free; FLogo.Free; FBG.Free; VL.Free; HL.Free; FF.Free; FK.Free; inherited; end; procedure TSceneCraft.Draw; var FC, IID: Integer; procedure AddRecept(ItemID: Integer); var T: Integer; begin with FF.Canvas do begin Font.Size := 16; if (FT = FVCursorPos) then begin Font.Color := cLightRare; IID := ItemID; end else Font.Color := cNormRare; T := FT * 20 + 116; Draw(67, T + 4, InvBox.SmallInvBitmap[InvBox.InvItems[ItemID].ImageIndex]); TextOut(85, T, InvBox.InvItems[ItemID].Name); Inc(FT); end; end; procedure CraftItemInfo(); var L: Integer; S: string; begin with FF.Canvas do begin Font.Size := 24; Font.Color := cLightRare; S := Trim(InvBox.InvItems[IID].Name); L := 546 - (TextWidth(S) div 2); Draw(L - 35, 108, InvBox.InvBitmap[InvBox.InvItems[IID].ImageIndex]); TextOut(L, 108, S); Font.Color := cNormRare; Font.Size := 16; S := InvBox.InvItems[IID].Description; TextOut(530 - (TextWidth(S) div 2), 140, S); S := InvBox.InvItems[IID].Hint; TextOut(530 - (TextWidth(S) div 2), 160, S); Font.Color := cLightRare; Font.Size := 20; S := 'Рецепт:'; TextOut(530 - (TextWidth(S) div 2), 190, S); Font.Color := cNormRare; Font.Size := 16; end; end; procedure AddIngrid(ItemID: Integer); var S: string; T, I, C: Integer; begin with FF.Canvas do begin Font.Size := 16; T := FC * 20 + 220; Draw(330, T + 4, InvBox.SmallInvBitmap[InvBox.InvItems[ItemID].ImageIndex]); I := InvBox.GetItemCount(ItemID); // Количество предметов в инвентаре C := 1; // Кол-во предметов в рецепте крафта if (I < C) then Font.Color := cDarkRare else Font.Color := cNormRare; TextOut(348, T, Format('%s (нужно: %d/есть: %d)', [InvBox.InvItems[ItemID].Name, C, I])); Inc(FC); end; end; begin FT := 0; FC := 0; FF.Assign(FLogo); with FF.Canvas do begin // Рецепты AddRecept(46); AddRecept(47); AddRecept(48); AddRecept(202); AddRecept(50); // Рамка для списка рецептов Draw(60, 110, HL); Draw(60, 490, HL); Draw(60, 110, VL); Draw(320, 110, VL); // Кнопки FCraftBtn.Sellected := (FHCursorPos = 0); FCraftBtn.Draw; FCloseBtn.Sellected := (FHCursorPos = 1); FCloseBtn.Draw; // Название предмета и его описание CraftItemInfo(); // Ингридиенты, необходимые для крафта AddIngrid(71); AddIngrid(72); AddIngrid(73); AddIngrid(74); AddIngrid(75); AddIngrid(76); AddIngrid(77); AddIngrid(78); AddIngrid(79); AddIngrid(80); end; SCR.BG.Canvas.Draw(0, 0, FF); end; function TSceneCraft.Keys(var Key: Word): Boolean; begin Result := True; case Key of 27: Close(); 13: begin case FHCursorPos of 0: Craft(); 1: Close(); end; end; 37, 39: begin FHCursorPos := FHCursorPos + (Key - 38); if (FHCursorPos < 0) then FHCursorPos := 1; if (FHCursorPos > 1) then FHCursorPos := 0; Sound.PlayClick(4); SceneManager.Draw; end; 38, 40: begin FVCursorPos := FVCursorPos + (Key - 39); if (FVCursorPos < 0) then FVCursorPos := FT - 1; if (FVCursorPos > FT - 1) then FVCursorPos := 0; Sound.PlayClick(4); SceneManager.Draw; end; end; end; procedure TSceneCraft.Close; begin SCR.BG.Canvas.Draw(0, 0, FK); Sound.PlayClick(); SceneManager.DeleteScene(scCraft); end; procedure TSceneCraft.Craft; begin // Создаем новые предметы Sound.Play(2); SceneManager.Draw; end; procedure TSceneCraft.MakeBG; begin FK.Assign(SCR.BG); FLogo.Assign(SCR.BG); FLogo.Canvas.Draw(FLeft + 0, FTop + 0, FBG); Sound.PlayClick(); end; function TSceneCraft.Click(Button: TMouseBtn): Boolean; var I: Integer; begin Result := False; case Button of mbLeft: begin if FCraftBtn.MouseOver then Craft; if FCloseBtn.MouseOver then Close; if IsMouseInRect(60, 116, 320, 486) then begin I := (MouseY - 116) div 20; if (I < 0) then I := 0; if (I > FT - 1) then I := FT - 1; FVCursorPos := I; Sound.PlayClick(4); SceneManager.Draw; end; end; end; end; function TSceneCraft.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; begin Result := False; FCraftBtn.MouseDown(X, Y); FCloseBtn.MouseDown(X, Y); SceneManager.Draw; end; function TSceneCraft.MouseMove(X, Y: Integer): Boolean; begin Result := False; FCraftBtn.Draw; FCloseBtn.Draw; SceneManager.Draw; end; initialization SceneCraft := TSceneCraft.Create; finalization SceneCraft.Free; end.
unit StdBmpForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TStdBmpViewer = class(TForm) ePath: TEdit; btnStart: TButton; Label1: TLabel; Label2: TLabel; eFilter: TEdit; procedure btnStartClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var StdBmpViewer: TStdBmpViewer; implementation {$R *.DFM} function OpenBitmap(path : string) : TBitmap; var Stream : TStream; begin result := nil; try Stream := TFileStream.Create(path, fmOpenRead); try result := TBitmap.Create; result.LoadFromStream(Stream); finally Stream.Free; end; except if result <> nil then result.Free; result := nil; end; end; procedure SaveBitmap(path : string; Bmp : TBitmap); var Stream : TStream; begin Stream := TFileStream.Create(path, fmCreate); try Bmp.SaveToStream(Stream); finally Stream.Free; end; end; procedure FilterBitmap(Template, Bmp : TBitmap); var x, y : integer; tc : TColor; c1 : TColor; begin tc := Bmp.Canvas.Pixels[0, 0]; c1 := Template.Canvas.Pixels[0, 0]; for x := 0 to pred(Bmp.Width) do for y := 0 to pred(Bmp.Height) do if Template.Canvas.Pixels[x, y] = c1 then Bmp.Canvas.Pixels[x, y] := tc; end; procedure TStdBmpViewer.btnStartClick(Sender: TObject); var Template : TBitmap; Path : string; Filter : string; found : integer; Search : TSearchRec; TmpBmp : TBitmap; begin Path := ExtractFilePath(ParamStr(0)); Template := OpenBitmap(Path + 'template.bmp'); Filter := UpperCase(eFilter.Text); if Template <> nil then begin Path := ePath.Text; if Path[length(Path)] <> '\' then Path := Path + '\'; CreateDir(Path + 'New'); found := FindFirst(Path + '*.bmp', faArchive, Search); try btnStart.Enabled := false; while found = 0 do begin if pos(Filter, UpperCase(Search.Name)) = 0 then begin TmpBmp := OpenBitmap(Path + Search.Name); FilterBitmap(Template, TmpBmp); SaveBitmap(Path + 'New\' + Search.Name, TmpBmp); Application.ProcessMessages; end; found := FindNext(Search); end; btnStart.Enabled := true; finally FindClose(Search); end; end; end; end.
unit ModelServerReportForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Buttons; const ModelServerKey = '\Software\Oceanus\Five\ModelServer\'; type TModelServerReport = class(TForm) Panel1: TPanel; Image1: TImage; PageControl1: TPageControl; General: TTabSheet; CreateWorld: TButton; TabSheet1: TTabSheet; Label5: TLabel; isHostAddress: TEdit; Label6: TLabel; isServerPort: TEdit; isConnect: TButton; TabSheet2: TTabSheet; Label8: TLabel; csHostAddress: TEdit; Label9: TLabel; csServerPort: TEdit; Label10: TLabel; csCallbackPort: TEdit; TabSheet3: TTabSheet; Log: TListBox; TabSheet4: TTabSheet; Label11: TLabel; daPort: TEdit; TabSheet5: TTabSheet; RegisteredExtensions: TListBox; Label12: TLabel; AddExtension: TButton; OpenExtension: TOpenDialog; Label1: TLabel; BaseDir: TEdit; Label2: TLabel; StatsTimer: TTimer; TabSheet6: TTabSheet; BPS: TLabel; SimSpeed: TTrackBar; Label3: TLabel; Label4: TLabel; DASpeed: TTrackBar; LoadProgress: TProgressBar; MailSheet: TTabSheet; Label7: TLabel; Label14: TLabel; msHostAddress: TEdit; MailServerPort: TEdit; WorldName: TEdit; procedure CreateWorldClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure AddExtensionClick(Sender: TObject); procedure isConnectClick(Sender: TObject); procedure StatsTimerTimer(Sender: TObject); procedure DASpeedChange(Sender: TObject); private fProgessBarPos : byte; private procedure UpdateProgress(aPos : byte); end; var ModelServerReport: TModelServerReport; implementation {$R *.DFM} uses ModelServer, LogFile, Registry; procedure TModelServerReport.CreateWorldClick(Sender: TObject); procedure InsertExtensionNames; var i : integer; begin RegisteredExtensions.Items.Clear; for i := 0 to pred(TheModelServer.ExtensionList.Count) do RegisteredExtensions.Items.Add( ExtractFileName(TheModelServer.ExtensionList[i]) ); end; var Reg : TRegistry; begin try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey( ModelServerKey, true ) then begin Reg.WriteString('BaseDir', BaseDir.Text); Reg.WriteString('WorldName', WorldName.Text); Reg.WriteString('CacheServer', csHostAddress.Text); Reg.WriteString('InterfaceServer', isHostAddress.Text); Reg.WriteString('MailServer', msHostAddress.Text); end; finally Reg.Free; end; except end; try TheModelServer.InitWorld( WorldName.Text, UpdateProgress, BaseDir.Text, csHostAddress.Text, StrToInt(daPort.Text), StrToInt(csCallbackPort.Text), StrToInt(csServerPort.Text), TThreadPriority(SimSpeed.Position), msHostAddress.Text, StrToInt(MailServerPort.Text) ); AddExtension.Enabled := true; InsertExtensionNames; CreateWorld.Enabled := false; SimSpeed.Enabled := false; DASpeed.Enabled := false; except on E : Exception do Application.MessageBox( pchar('Cannot create world!'#13#10 + E.Message), 'Model Server', MB_ICONERROR or MB_OK ); end; end; procedure TModelServerReport.FormDestroy(Sender: TObject); begin try TheModelServer.Free; except end; end; procedure TModelServerReport.FormCreate(Sender: TObject); var Reg : TRegistry; aux : string; begin TheModelServer := TModelServer.Create; SetLogFile( ExtractFilePath(Application.ExeName) + 'ModelServer.log' ); try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey( ModelServerKey, false ) then begin aux := Reg.ReadString( 'BaseDir' ); if aux <> '' then BaseDir.Text := aux; aux := Reg.ReadString( 'WorldName' ); if aux <> '' then WorldName.Text := aux; aux := Reg.ReadString( 'CacheServer' ); if aux <> '' then csHostAddress.Text := aux; aux := Reg.ReadString( 'InterfaceServer' ); if aux <> '' then isHostAddress.Text := aux; aux := Reg.ReadString( 'MailServer' ); if aux <> '' then msHostAddress.Text := aux; end; finally Reg.Free; end; except end; end; procedure TModelServerReport.AddExtensionClick(Sender: TObject); begin if (OpenExtension.Execute) and (OpenExtension.FileName <> '') then try TheModelServer.RegisterModelExtension( OpenExtension.FileName ); RegisteredExtensions.Items.Add( ExtractFileName(OpenExtension.FileName) ); except Application.MessageBox( pchar('Cannot register ' + OpenExtension.FileName), 'Model Server', MB_ICONERROR or MB_OK ); end; end; procedure TModelServerReport.isConnectClick(Sender: TObject); begin try TheModelServer.InitInterfaceServerEvents( isHostAddress.Text, StrToInt(isServerPort.Text) ); //isConnect.Enabled := false; except Application.MessageBox( pchar('Cannot register ' + OpenExtension.FileName), 'Model Server', MB_ICONERROR or MB_OK ); end end; procedure TModelServerReport.StatsTimerTimer(Sender: TObject); begin if TheModelServer <> nil then BPS.Caption := IntToStr(TheModelServer.BPS) + ' facilities per second.'; end; procedure TModelServerReport.DASpeedChange(Sender: TObject); begin if Sender = DASpeed then SimSpeed.Position := SimSpeed.Max - DASpeed.Position else DASpeed.Position := DASpeed.Max - SimSpeed.Position end; procedure TModelServerReport.UpdateProgress(aPos : byte); begin if fProgessBarPos <> aPos then begin fProgessBarPos := aPos; LoadProgress.Position := aPos; LoadProgress.Repaint; end; end; end.
unit MailServerInterfaces; interface uses Classes; type IMailServer = interface function NewMailAccount(Account, Alias, FwdAddr : string; KeepMsg : boolean) : boolean; function DeleteAccount (Account : string) : boolean; function SetForwardRule(Account, FwdAddr : string; KeepMsg : boolean) : boolean; function SendMessage(From, Dest, Subject : string; Lines : TStringList; html : boolean) : boolean; function SendHTMLMessage(From, Dest, Subject, URL : string) : boolean; procedure UpdateDate(date : TDateTime); end; implementation end.
unit App; { Based on 022_parallax_map.cpp example from oglplus (http://oglplus.org/) } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App, Sample.Geometry; type TParallaxMapApp = class(TApplication) private FProgram: TGLProgram; FVerts: TGLBuffer; FNormals: TGLBuffer; FTangents: TGLBuffer; FTexCoords: TGLBuffer; FIndices: TGLBuffer; FTexture: TGLTexture; FUniProjectionMatrix: TGLUniform; FUniCameraMatrix: TGLUniform; FUniModelMatrix: TGLUniform; FUniLightPos: TGLUniform; FCube: TCubeGeometry; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; procedure Resize(const AWidth, AHeight: Integer); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Math, Sample.Assets, Sample.Texture; { TParallaxMapApp } procedure TParallaxMapApp.Initialize; var VertexShader, FragmentShader: TGLShader; VertAttr: TGLVertexAttrib; Uniform: TGLUniform; begin TAssets.Initialize; VertexShader.New(TGLShaderType.Vertex, 'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+ 'uniform vec3 LightPos;'#10+ 'attribute vec3 Position;'#10+ 'attribute vec3 Normal;'#10+ 'attribute vec3 Tangent;'#10+ 'attribute vec2 TexCoord;'#10+ 'varying vec3 vertEye;'#10+ 'varying vec3 vertLight;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec2 vertTexCoord;'#10+ 'varying vec3 vertViewTangent;'#10+ 'varying mat3 NormalMatrix;'#10+ 'void main(void)'#10+ '{'#10+ ' vec4 EyePos = '#10+ ' CameraMatrix *'#10+ ' ModelMatrix *'#10+ ' vec4(Position, 1.0);'#10+ ' vertEye = EyePos.xyz;'#10+ ' vec3 fragTangent = ('#10+ ' CameraMatrix *'#10+ ' ModelMatrix *'#10+ ' vec4(Tangent, 0.0)).xyz;'#10+ ' vertNormal = ('#10+ ' CameraMatrix *'#10+ ' ModelMatrix *'#10+ ' vec4(Normal, 0.0)).xyz;'#10+ ' vertLight = ('#10+ ' CameraMatrix *'#10+ ' vec4(LightPos - vertEye, 1.0)).xyz;'#10+ ' NormalMatrix = mat3('#10+ ' fragTangent,'#10+ ' cross(vertNormal, fragTangent),'#10+ ' vertNormal);'#10+ ' vertViewTangent = vec3('#10+ ' dot(NormalMatrix[0], vertEye),'#10+ ' dot(NormalMatrix[1], vertEye),'#10+ ' dot(NormalMatrix[2], vertEye));'#10+ ' vertTexCoord = TexCoord;'#10+ ' gl_Position = ProjectionMatrix * EyePos;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'uniform sampler2D BumpTex;'#10+ 'uniform int BumpTexWidth;'#10+ 'uniform int BumpTexHeight;'#10+ 'float DepthMult = 0.1;'#10+ 'varying vec3 vertEye;'#10+ 'varying vec3 vertLight;'#10+ 'varying vec3 vertNormal;'#10+ 'varying vec2 vertTexCoord;'#10+ 'varying vec3 vertViewTangent;'#10+ 'varying mat3 NormalMatrix;'#10+ 'void main(void)'#10+ '{'#10+ ' vec3 ViewTangent = normalize(vertViewTangent);'#10+ ' float perp = -dot(normalize(vertEye), vertNormal);'#10+ ' float sampleInterval = 1.0 / length('#10+ ' vec2(BumpTexWidth, BumpTexHeight));'#10+ ' vec3 sampleStep = ViewTangent * sampleInterval;'#10+ ' float prevD = 0.0;'#10+ ' float depth = texture2D(BumpTex, vertTexCoord).w;'#10+ ' float maxOffs = min((depth * DepthMult) / -ViewTangent.z, 1.0);'#10+ ' vec3 viewOffs = vec3(0.0, 0.0, 0.0);'#10+ ' vec2 offsTexC = vertTexCoord + viewOffs.xy;'#10+ ' while (length(viewOffs) < maxOffs)'#10+ ' {'#10+ ' if ((offsTexC.x <= 0.0) || (offsTexC.x >= 1.0))'#10+ ' break;'#10+ ' if ((offsTexC.y <= 0.0) || (offsTexC.y >= 1.0))'#10+ ' break;'#10+ ' if ((depth * DepthMult * perp) <= -viewOffs.z)'#10+ ' break;'#10+ ' viewOffs += sampleStep;'#10+ ' offsTexC = vertTexCoord + viewOffs.xy;'#10+ ' prevD = depth;'#10+ ' depth = texture2D(BumpTex, offsTexC).w;'#10+ ' }'#10+ ' offsTexC = vec2('#10+ ' clamp(offsTexC.x, 0.0, 1.0),'#10+ ' clamp(offsTexC.y, 0.0, 1.0));'#10+ ' float b = floor(mod('#10+ ' 1.0 +'#10+ ' floor(mod(offsTexC.x * 16.0, 2.0))+'#10+ ' floor(mod(offsTexC.y * 16.0, 2.0)), 2.0));'#10+ ' vec3 c = vec3(b, b, b);'#10+ ' vec3 n = texture2D(BumpTex, offsTexC).xyz;'#10+ ' vec3 finalNormal = NormalMatrix * n;'#10+ ' float l = length(vertLight);'#10+ ' float d = (l > 0.0) ? dot('#10+ ' normalize(vertLight), '#10+ ' finalNormal) / l : 0.0;'#10+ ' float i = 0.1 + 2.5 * max(d, 0.0);'#10+ ' gl_FragColor = vec4(c * i, 1.0);'#10+ '}'); FragmentShader.Compile; FProgram.New(VertexShader, FragmentShader); FProgram.Link; VertexShader.Delete; FragmentShader.Delete; FProgram.Use; FCube.Generate; { Positions } FVerts.New(TGLBufferType.Vertex); FVerts.Bind; FVerts.Data<TVector3>(FCube.Positions); VertAttr.Init(FProgram, 'Position'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Normals } FNormals.New(TGLBufferType.Vertex); FNormals.Bind; FNormals.Data<TVector3>(FCube.Normals); VertAttr.Init(FProgram, 'Normal'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Tangents } FTangents.New(TGLBufferType.Vertex); FTangents.Bind; FTangents.Data<TVector3>(FCube.Tangents); VertAttr.Init(FProgram, 'Tangent'); VertAttr.SetConfig<TVector3>; VertAttr.Enable; { Texture coordinates } FTexCoords.New(TGLBufferType.Vertex); FTexCoords.Bind; FTexCoords.Data<TVector2>(FCube.TexCoords); VertAttr.Init(FProgram, 'TexCoord'); VertAttr.SetConfig<TVector2>; VertAttr.Enable; { Indices } FIndices.New(TGLBufferType.Index); FIndices.Bind; FIndices.Data<UInt16>(FCube.Indices); { Don't need data anymore } FCube.Clear; { Texture } FTexture := LoadTexture('texture.tga'); FTexture.WrapS(TGLWrapMode.NormalRepeat); FTexture.WrapT(TGLWrapMode.NormalRepeat); { Uniforms } Uniform.Init(FProgram, 'BumpTexWidth'); Uniform.SetValue(512); Uniform.Init(FProgram, 'BumpTexHeight'); Uniform.SetValue(512); Uniform.Init(FProgram, 'BumpTex'); Uniform.SetValue(0); FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix'); FUniCameraMatrix.Init(FProgram, 'CameraMatrix'); FUniModelMatrix.Init(FProgram, 'ModelMatrix'); FUniLightPos.Init(FProgram, 'LightPos'); gl.ClearColor(0.1, 0.1, 0.1, 0); gl.ClearDepth(1); gl.Enable(TGLCapability.DepthTest); gl.Enable(TGLCapability.CullFace); gl.FrontFace(TGLFaceOrientation.CounterClockwise); end; procedure TParallaxMapApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TParallaxMapApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); var LightAzimuth, S, C: Single; CameraMatrix, ModelMatrix: TMatrix4; begin { Clear the color and depth buffer } gl.Clear([TGLClear.Color, TGLClear.Depth]); { Use the program } FProgram.Use; { Set light position } LightAzimuth := -Pi * ATotalTimeSec; FastSinCos(LightAzimuth, S, C); FUniLightPos.SetValue(-C * 2, 2, -S * 2); { Set the matrix for camera orbiting the origin } OrbitCameraMatrix(TVector3.Zero, 3.0, Radians(-45), Radians(FastSin(Pi * ATotalTimeSec / 15) * 70), CameraMatrix); FUniCameraMatrix.SetValue(CameraMatrix); { Update and render the cube } ModelMatrix.InitRotation(Vector3(1, 1, 1), -Pi * ATotalTimeSec * 0.025); FUniModelMatrix.SetValue(ModelMatrix); gl.CullFace(TGLFace.Back); FCube.DrawWithBoundIndexBuffer; end; procedure TParallaxMapApp.Resize(const AWidth, AHeight: Integer); var ProjectionMatrix: TMatrix4; begin inherited; ProjectionMatrix.InitPerspectiveFovRH(Radians(54), AWidth / AHeight, 1, 10); FProgram.Use; FUniProjectionMatrix.SetValue(ProjectionMatrix); end; procedure TParallaxMapApp.Shutdown; begin { Release resources } FIndices.Delete; FTexCoords.Delete; FTangents.Delete; FNormals.Delete; FVerts.Delete; FProgram.Delete; FTexture.Delete; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.13 9/30/2004 2:26:04 PM BGooijen wrong property was referenced Rev 1.12 2004.02.03 4:17:12 PM czhower For unit name changes. Rev 1.11 2004.01.20 10:03:38 PM czhower InitComponent Rev 1.10 09.11.2003 14:05:52 ARybin AV Rev 1.9 08.11.2003 20:03:20 ARybin run-time active bug Rev 1.8 10/15/2003 8:48:58 PM DSiders Added resource strings for exceptions raised when setting thread component properties. Rev 1.7 2003.10.11 9:58:04 PM czhower Several bug fixes Rev 1.6 2003.10.11 5:51:54 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support Rev 1.5 2003.09.30 7:48:02 PM czhower Fixed Loop and ThreadName Rev 1.4 9/18/2003 07:40:52 PM JPMugaas Removed IdGlobal. Rev 1.3 9/16/2003 04:47:22 PM JPMugaas Made some code follow the Indy conventions so it's easier to debug. Rev 1.2 2003.07.01 4:14:38 PM czhower ThreadName and Loop added. Other bugs fixed. Rev 1.1 06.03.2003 12:16:52 ARybin adapted for new IdThread Rev 1.0 11/13/2002 08:03:06 AM JPMugaas 2002-05-03 -Andrew P.Rybin -Stéphane Grobéty (Fulgan) suggestion: component is Data owner, don't FreeAndNIL Data property -special TThread.OnTerminate support (it is sync-event) 2002-05-23 -APR -right support for Thread terminate } unit IdThreadComponent; { UnitName: IdThreadComponent Author: Andrew P.Rybin [magicode@mail.ru] Creation: 12.03.2002 Version: 0.1.0 Purpose: History: Based on my TmcThread } interface {$I IdCompilerDefines.inc} //Put FPC into Delphi mode uses Classes, IdBaseComponent, IdException, IdGlobal, IdThread, SysUtils; const IdThreadComponentDefaultPriority = tpNormal; IdThreadComponentDefaultStopMode = smTerminate; type TIdThreadComponent = class; TIdExceptionThreadComponentEvent = procedure(Sender: TIdThreadComponent; AException: Exception) of object; TIdExceptionThreadComponentEventEx = procedure(Sender: TIdThreadComponent; AException: Exception; var VHandled: Boolean) of object; TIdNotifyThreadComponentEvent = procedure(Sender: TIdThreadComponent) of object; //TIdSynchronizeThreadComponentEvent = procedure(Sender: TIdThreadComponent; AData: Pointer) of object; TIdThreadComponent = class(TIdBaseComponent) protected FActive: Boolean; FLoop: Boolean; FPriority : TIdThreadPriority; FStopMode : TIdThreadStopMode; FThread: TIdThread; FThreadName: string; // FOnAfterExecute: TIdNotifyThreadComponentEvent; FOnAfterRun: TIdNotifyThreadComponentEvent; FOnBeforeExecute: TIdNotifyThreadComponentEvent; FOnBeforeRun: TIdNotifyThreadComponentEvent; FOnCleanup: TIdNotifyThreadComponentEvent; FOnException: TIdExceptionThreadComponentEvent; FOnRun: TIdNotifyThreadComponentEvent; FOnStopped: TIdNotifyThreadComponentEvent; FOnTerminate: TIdNotifyThreadComponentEvent; FOnHandleRunException: TIdExceptionThreadComponentEventEx; // procedure DoAfterExecute; virtual; procedure DoAfterRun; virtual; procedure DoBeforeExecute; virtual; procedure DoBeforeRun; virtual; procedure DoCleanup; virtual; procedure DoException(AThread: TIdThread; AException: Exception); virtual; //thev function DoHandleRunException(AException: Exception): Boolean; virtual; procedure DoRun; virtual; procedure DoStopped(AThread: TIdThread); virtual; //thev procedure DoTerminate(Sender: TObject); virtual; //thev function GetActive: Boolean; function GetData: TObject; function GetHandle: TIdThreadHandle; function GetPriority: TIdThreadPriority; function GetReturnValue: Integer; function GetStopMode: TIdThreadStopMode; function GetStopped: Boolean; function GetSuspended: Boolean; function GetTerminatingException: string; function GetTerminatingExceptionClass: TClass; function GetTerminated: Boolean; procedure InitComponent; override; function IsRunning: Boolean; procedure Loaded; override; procedure SetActive(const AValue: Boolean); virtual; procedure SetData(const AValue: TObject); procedure SetLoop(const AValue: Boolean); procedure SetThreadName(const AValue: string); procedure SetOnTerminate(const AValue: TIdNotifyThreadComponentEvent); procedure SetPriority(const AValue: TIdThreadPriority); procedure SetReturnValue(const AValue: Integer); procedure SetStopMode(const AValue: TIdThreadStopMode); public destructor Destroy; override; procedure Start; virtual; procedure Stop; virtual; procedure Synchronize(AMethod: TThreadMethod); procedure Terminate; virtual; procedure TerminateAndWaitFor; virtual; function WaitFor: LongWord; // Properties property Data: TObject read GetData write SetData; property Handle: TIdThreadHandle read GetHandle; property ReturnValue: Integer read GetReturnValue write SetReturnValue; property Stopped: Boolean read GetStopped; property Suspended: Boolean read GetSuspended; property TerminatingException: string read GetTerminatingException; property TerminatingExceptionClass: TClass read GetTerminatingExceptionClass; property Terminated: Boolean read GetTerminated; published property Active: Boolean read GetActive write SetActive; property Loop: Boolean read FLoop write SetLoop; property Priority: TIdThreadPriority read GetPriority write SetPriority; property StopMode: TIdThreadStopMode read GetStopMode write SetStopMode; property ThreadName: string read FThreadName write SetThreadName; // Events property OnAfterExecute: TIdNotifyThreadComponentEvent read FOnAfterExecute write FOnAfterExecute; property OnAfterRun: TIdNotifyThreadComponentEvent read FOnAfterRun write FOnAfterRun; property OnBeforeExecute: TIdNotifyThreadComponentEvent read FOnBeforeExecute write FOnBeforeExecute; property OnBeforeRun: TIdNotifyThreadComponentEvent read FOnBeforeRun write FOnBeforeRun; property OnCleanup: TIdNotifyThreadComponentEvent read FOnCleanup write FOnCleanup; property OnException: TIdExceptionThreadComponentEvent read FOnException write FOnException; property OnHandleRunException: TIdExceptionThreadComponentEventEx read FOnHandleRunException write FOnHandleRunException; property OnRun: TIdNotifyThreadComponentEvent read FOnRun write FOnRun; property OnStopped: TIdNotifyThreadComponentEvent read FOnStopped write FOnStopped; property OnTerminate: TIdNotifyThreadComponentEvent read FOnTerminate write SetOnTerminate; end; //For Component-writers ONLY! TIdThreadEx = class(TIdThread) protected FThreadComponent: TIdThreadComponent; // procedure AfterRun; override; procedure AfterExecute; override; procedure BeforeExecute; override; procedure BeforeRun; override; procedure Cleanup; override; function HandleRunException(AException: Exception): Boolean; override; procedure Run; override; public constructor Create(AThreadComponent: TIdThreadComponent); reintroduce; end; implementation uses IdResourceStringsCore; { TIdThreadEx } procedure TIdThreadEx.AfterExecute; begin try FThreadComponent.DoAfterExecute; finally FThreadComponent.FActive := FALSE; end; end; procedure TIdThreadEx.AfterRun; begin FThreadComponent.DoAfterRun; end; procedure TIdThreadEx.BeforeExecute; begin FThreadComponent.DoBeforeExecute; end; procedure TIdThreadEx.BeforeRun; begin FThreadComponent.DoBeforeRun; end; procedure TIdThreadEx.Cleanup; begin inherited Cleanup; FThreadComponent.DoCleanup; end; constructor TIdThreadEx.Create(AThreadComponent: TIdThreadComponent); begin inherited Create(True, AThreadComponent.Loop, iif(AThreadComponent.ThreadName = '' , AThreadComponent.Name, AThreadComponent.ThreadName)); Exclude(FOptions, itoDataOwner); //TIdThreadComponent is data owner FThreadComponent := AThreadComponent; FOnException := FThreadComponent.DoException; FOnStopped := FThreadComponent.DoStopped; end; function TIdThreadEx.HandleRunException(AException: Exception): Boolean; begin Result := FThreadComponent.DoHandleRunException(AException); end; procedure TIdThreadEx.Run; begin FThreadComponent.DoRun; end; { TIdThreadComponent } procedure TIdThreadComponent.DoAfterExecute; begin if Assigned(FOnAfterExecute) then begin FOnAfterExecute(SELF); end; end; procedure TIdThreadComponent.DoAfterRun; begin if Assigned(FOnAfterRun) then begin FOnAfterRun(SELF); end; end; procedure TIdThreadComponent.DoBeforeExecute; begin if Assigned(FOnBeforeExecute) then begin FOnBeforeExecute(SELF); end; end; procedure TIdThreadComponent.DoBeforeRun; begin if Assigned(FOnBeforeRun) then begin FOnBeforeRun(SELF); end; end; procedure TIdThreadComponent.DoCleanup; begin if Assigned(FOnCleanup) then begin FOnCleanup(SELF); end; end; destructor TIdThreadComponent.Destroy; begin {FThread.TerminateAndWaitFor;} //make sure thread is not active before we attempt to destroy it if Assigned(FThread) then begin FThread.Terminate; FThread.Start;//resume for terminate end; FreeAndNil(FThread); inherited Destroy; end; procedure TIdThreadComponent.DoException(AThread: TIdThread; AException: Exception); begin if Assigned(FOnException) then begin FOnException(SELF,AException); end; end; function TIdThreadComponent.DoHandleRunException(AException: Exception): Boolean; begin Result := FALSE;//not handled if Assigned(FOnHandleRunException) then begin FOnHandleRunException(SELF,AException,Result); end; end; procedure TIdThreadComponent.DoStopped(AThread: TIdThread); begin if Assigned(FOnStopped) then begin FOnStopped(SELF); end; end; procedure TIdThreadComponent.DoTerminate; begin if Assigned(FOnTerminate) then begin FOnTerminate(SELF); end; end; function TIdThreadComponent.GetData: TObject; begin Result := FThread.Data; end; function TIdThreadComponent.GetHandle: TIdThreadHandle; begin Result := GetThreadHandle(FThread); end; function TIdThreadComponent.GetReturnValue: Integer; begin Result := FThread.ReturnValue; end; function TIdThreadComponent.GetStopMode: TIdThreadStopMode; begin if FThread = NIL then begin Result := FStopMode; end else begin Result := FThread.StopMode; end; end; function TIdThreadComponent.GetStopped: Boolean; begin if Assigned(FThread) then begin Result := FThread.Stopped; end else begin Result := TRUE; end; end; function TIdThreadComponent.GetSuspended: Boolean; begin Result := FThread.Suspended; end; function TIdThreadComponent.GetTerminated: Boolean; begin if Assigned(FThread) then begin Result := FThread.Terminated; end else begin Result := TRUE; end; end; function TIdThreadComponent.GetTerminatingException: string; begin Result := FThread.TerminatingException; end; function TIdThreadComponent.GetTerminatingExceptionClass: TClass; begin Result := FThread.TerminatingExceptionClass; end; procedure TIdThreadComponent.Loaded; begin inherited Loaded; // Active = True must not be performed before all other props are loaded if Assigned(FThread) and Assigned(OnTerminate) then begin FThread.OnTerminate := DoTerminate; end; if FActive then begin // Retoggle for load since we ignore during loading until all properties // are ready FActive := False; Active := True; end; end; procedure TIdThreadComponent.DoRun; begin if Assigned(FOnRun) then begin FOnRun(SELF); end; end; procedure TIdThreadComponent.SetActive(const AValue: Boolean); begin if IsDesignTime or IsLoading then begin FActive := AValue; end else if Active <> AValue then begin if AValue then begin Start; end else begin Stop; end; FActive := AValue; end; end; procedure TIdThreadComponent.SetData(const AValue: TObject); begin // this should not be accessed at design-time. FThread.Data := AValue; end; procedure TIdThreadComponent.SetReturnValue(const AValue: Integer); begin // this should not be accessed at design-time. FThread.ReturnValue := AValue; end; procedure TIdThreadComponent.SetStopMode(const AValue: TIdThreadStopMode); begin if Assigned(FThread) and NOT FThread.Terminated then begin FThread.StopMode := AValue; end; FStopMode := AValue; end; procedure TIdThreadComponent.Start; begin if not IsDesignTime then begin if Assigned(FThread) and FThread.Terminated then begin FreeAndNil(FThread); end; if not Assigned(FThread) then begin FThread := TIdThreadEx.Create(Self); end; // MUST read from F variants as thread is now created if Assigned(FOnTerminate) then begin FThread.OnTerminate := DoTerminate; end else begin FThread.OnTerminate := nil; end; FThread.Name := FThreadName; FThread.Loop := FLoop; FThread.Priority := FPriority; FThread.StopMode := FStopMode; FThread.Start; end; end; procedure TIdThreadComponent.Stop; begin if Assigned(FThread) then begin FThread.Stop; end; end; procedure TIdThreadComponent.Synchronize(AMethod: TThreadMethod); begin FThread.Synchronize(AMethod); end; procedure TIdThreadComponent.Terminate; begin FThread.Terminate; end; procedure TIdThreadComponent.TerminateAndWaitFor; begin FThread.TerminateAndWaitFor; end; function TIdThreadComponent.WaitFor: LongWord; begin Result := FThread.WaitFor; end; function TIdThreadComponent.GetPriority: TIdThreadPriority; begin if FThread <> nil then begin Result := FThread.Priority; end else begin Result := FPriority; end; end; procedure TIdThreadComponent.SetPriority(const AValue: TIdThreadPriority); begin if Assigned(FThread) then begin if not FThread.Terminated then begin FThread.Priority := AValue; end; end; FPriority := AValue; end; function TIdThreadComponent.GetActive: Boolean; begin Result := False; if IsDesignTime then begin Result := FActive; end else if FThread <> nil then begin Result := IsRunning; end; end; procedure TIdThreadComponent.SetOnTerminate(const AValue: TIdNotifyThreadComponentEvent); begin FOnTerminate := AValue; if Assigned(FThread) then begin if Assigned(AValue) then begin FThread.OnTerminate := DoTerminate; end else begin FThread.OnTerminate := nil; end; end; end; procedure TIdThreadComponent.SetLoop(const AValue: Boolean); begin if IsRunning then begin EIdException.Toss(RSThreadComponentLoopAlreadyRunning); end; FLoop := AValue; end; procedure TIdThreadComponent.SetThreadName(const AValue: string); begin if IsRunning then begin EIdException.Toss(RSThreadComponentThreadNameAlreadyRunning); end; FThreadName := AValue; end; function TIdThreadComponent.IsRunning: Boolean; begin if FThread = nil then begin Result := False; end else begin Result := not FThread.Stopped end; end; procedure TIdThreadComponent.InitComponent; begin inherited InitComponent; StopMode := IdThreadComponentDefaultStopMode; Priority := IdThreadComponentDefaultPriority; end; end.
unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Sensors, System.Sensors.Components, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Layouts, OpenWeatherAPI, Classes, FMX.Edit, FMX.Gestures, System.Threading, FMX.Effects, FMX.VirtualKeyboard, FMX.Platform; type TVirtualKeyboardState = (vkAtivo, vkInativo); {Define o Tipo TVirtualKeyboardState que vai ser utilizado para saber o estado do teclado do dispositivo de forma simplificada} TfrmMain = class(TForm) lytTop: TLayout; lytCidade: TLayout; lytWeatherImage: TLayout; lytTemperatura: TLayout; lblTemp1: TLabel; img1: TImage; lytMid: TLayout; lytBottom: TLayout; lytMidLeft: TLayout; Layout2: TLayout; lytImgWeatherMLeft: TLayout; img2: TImage; Layout4: TLayout; lblTemp2: TLabel; lytMidRight: TLayout; Layout6: TLayout; lytImgWeatherMRight: TLayout; img3: TImage; Layout8: TLayout; lblTemp3: TLabel; lytBottomLeft: TLayout; Layout5: TLayout; lytImgWeatherBLeft: TLayout; img4: TImage; Layout10: TLayout; lblTemp4: TLabel; lytBottomRight: TLayout; Layout12: TLayout; lytImgWeatherBRight: TLayout; imgIndex: TImage; Layout14: TLayout; lblTemp5: TLabel; StyleBook1: TStyleBook; img5: TImage; lblCidade5: TLabel; lblCidade4: TLabel; lblCidade2: TLabel; lblCidade3: TLabel; lblCidade1: TLabel; Rectangle1: TRectangle; Rectangle2: TRectangle; Rectangle3: TRectangle; Rectangle4: TRectangle; Rectangle5: TRectangle; Rectangle6: TRectangle; Label1: TLabel; GestureManager1: TGestureManager; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; rectPesquisar: TRectangle; ShadowEffect1: TShadowEffect; btnFecharPesquisa: TButton; edtPesquisar: TEdit; btnClearEdtPesquisar: TClearEditButton; Button6: TButton; procedure FormResize(Sender: TObject); procedure edtPesquisarTyping(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure btnFecharPesquisaTap(Sender: TObject; const Point: TPointF); procedure btnClearEdtPesquisarTap(Sender: TObject; const Point: TPointF); procedure FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure Button5Tap(Sender: TObject; const Point: TPointF); procedure Button4Tap(Sender: TObject; const Point: TPointF); procedure Button1Tap(Sender: TObject; const Point: TPointF); procedure Button3Tap(Sender: TObject; const Point: TPointF); procedure Button2Tap(Sender: TObject; const Point: TPointF); procedure Button6Tap(Sender: TObject; const Point: TPointF); private PosicaoCidade : Integer; FAPI: TOpenWeatherAPI; FImagesPath: string; oVirtualKeyboardState : TVirtualKeyboardState; //Declara uma variável do tipo TVirtualKeyboardState procedure Start; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation {$R *.fmx} uses System.IOUtils, Constantes, BitmapHelper; { TfrmMain } procedure TfrmMain.btnClearEdtPesquisarTap(Sender: TObject; const Point: TPointF); begin edtPesquisar.Text:=''; btnClearEdtPesquisar.Visible := False; end; procedure TfrmMain.btnFecharPesquisaTap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := False; end; procedure TfrmMain.Button1Tap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := True; edtPesquisar.Text := ''; edtPesquisar.SetFocus; PosicaoCidade := 3; end; procedure TfrmMain.Button2Tap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := True; edtPesquisar.Text := ''; edtPesquisar.SetFocus; PosicaoCidade := 5; end; procedure TfrmMain.Button3Tap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := True; edtPesquisar.Text := ''; edtPesquisar.SetFocus; PosicaoCidade := 4; end; procedure TfrmMain.Button4Tap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := True; edtPesquisar.Text := ''; edtPesquisar.SetFocus; PosicaoCidade := 2; end; procedure TfrmMain.Button5Tap(Sender: TObject; const Point: TPointF); begin rectPesquisar.Visible := True; edtPesquisar.Text := ''; edtPesquisar.SetFocus; PosicaoCidade := 1; end; procedure TfrmMain.Button6Tap(Sender: TObject; const Point: TPointF); begin case PosicaoCidade of 1 : FAPI.GetURLPorCidade(edtPesquisar.Text.Trim,lblCidade1,lblTemp1, img1); 2 : FAPI.GetURLPorCidade(edtPesquisar.Text.Trim,lblCidade2,lblTemp2, img2); 3 : FAPI.GetURLPorCidade(edtPesquisar.Text.Trim,lblCidade3,lblTemp3, img3); 4 : FAPI.GetURLPorCidade(edtPesquisar.Text.Trim,lblCidade4,lblTemp4, img4); 5 : FAPI.GetURLPorCidade(edtPesquisar.Text.Trim,lblCidade5,lblTemp5, img5); end; end; constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FAPI := TOpenWeatherAPI.Create; Start; end; destructor TfrmMain.Destroy; begin FAPI.Free; inherited; end; procedure TfrmMain.edtPesquisarTyping(Sender: TObject); begin btnClearEdtPesquisar.Visible := not(edtPesquisar.Text.IsEmpty); end; procedure TfrmMain.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var FService : IFMXVirtualKeyboardService; begin inherited; if (Key = vkHardwareBack) then begin TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService)); if ((FService <> nil) and (oVirtualKeyboardState = vkAtivo)) then begin //Botao back pressionado e teclado visivel, apenas fecha o teclado end else begin //Botao back pressionado e teclado nao visivel if rectPesquisar.Visible then begin Key := 0; rectPesquisar.Visible := False; end; end; end; end; procedure TfrmMain.FormResize(Sender: TObject); begin lytTop.Height := (Self.ClientHeight - 40) / 3; lytMid.Height := lytTop.Height; lytBottom.Height := lytTop.Height; lytMidLeft.Width := lytMid.Width / 2; lytBottomLeft.Width := lytBottom.Width / 2; lytWeatherImage.Width := lytTop.Width / 3; lytImgWeatherMLeft.Width := lytMidLeft.Width / 3; lytImgWeatherMRight.Width := lytMidRight.Width / 3; lytImgWeatherBLeft.Width := lytBottomLeft.Width / 3; lytImgWeatherBRight.Width := lytBottomRight.Width / 3; end; procedure TfrmMain.FormShow(Sender: TObject); begin rectPesquisar.Visible := False; btnClearEdtPesquisar.Visible := False; end; procedure TfrmMain.FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin oVirtualKeyboardState := vkInativo; end; procedure TfrmMain.FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin oVirtualKeyboardState := vkAtivo; end; procedure TfrmMain.Start; begin TThread.CreateAnonymousThread(procedure begin FAPI.GetURLPorCidade('Vertentes', lblCidade1, lblTemp1, img1); FAPI.GetURLPorCidade('Surubim', lblCidade2, lblTemp2, img2); FAPI.GetURLPorCidade('Caruaru', lblCidade3, lblTemp3, img3); FAPI.GetURLPorCidade('Toritama', lblCidade4, lblTemp4, img4); FAPI.GetURLPorCidade('Bezerros', lblCidade5, lblTemp5, img5); end).start(); end; end.
unit CoreMisc; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} interface uses CoreTypes; //Increse, and Decrease but with a result (Similar to i++, and i-- in C) function Asc(var i: Int32): Int32; Inline; overload; //i++ function Asc(var i: uInt32): uInt32; Inline; overload; //i++ function Asc(var i: Int64): Int64; Inline; overload; //i++ function Asc(var i: uInt64): uInt64; Inline; overload; //i++ function Desc(var i: Int32): Int32; Inline; overload; //i-- function Desc(var i: uInt32): uInt32; Inline; overload; //i-- function Desc(var i: Int64): Int64; Inline; overload; //i-- function Desc(var i: uInt64): uInt64; Inline; overload; //i-- //Swapping / exchanging procedure Exch(var A,B:uInt8); Inline; overload; procedure Exch(var A,B:uInt16); Inline; overload; procedure Exch(var A,B:uInt32); Inline; overload; procedure Exch(var A,B:uInt64); Inline; overload; procedure Exch(var A,B:Int8); Inline; overload; procedure Exch(var A,B:Int16); Inline; overload; procedure Exch(var A,B:Int32); Inline; overload; procedure Exch(var A,B:Int64); Inline; overload; procedure Exch(var A,B:Extended); Inline; overload; procedure Exch(var A,B:Double); Inline; overload; procedure Exch(var A,B:Single); Inline; overload; procedure Exch(var A,B:TPoint); Inline; overload; procedure Exch(var A,B:TBox); Inline; overload; // Excahnging values: only if a > b procedure ExchMin(var a,b:UInt8); Inline; Overload; procedure ExchMin(var a,b:UInt16); Inline; Overload; procedure ExchMin(var a,b:UInt32); Inline; Overload; procedure ExchMin(var a,b:UInt64); Inline; Overload; procedure ExchMin(var a,b:Int8); Inline; Overload; procedure ExchMin(var a,b:Int16); Inline; Overload; procedure ExchMin(var a,b:Int32); Inline; Overload; procedure ExchMin(var a,b:Int64); Inline; Overload; procedure ExchMin(var a,b:Single); Inline; Overload; procedure ExchMin(var a,b:Double); Inline; Overload; procedure ExchMin(var a,b:Extended); Inline; Overload; //Safe move functionallity //procedure Move(const InArr:AnsiString; var DestArr:AnsiString; source, dest, size:Integer); overload; //procedure Move(const InArr:TIntArray; var DestArr:TIntArray; source, dest, size:Integer); overload; //procedure Move(const InArr:TExtArray; var DestArr:TExtArray; source, dest, size:Integer); overload; //procedure Move(const InArr:TPointArray; var DestArr:TPointArray; source, dest, size:Integer); overload; //----------------------------------------------------------------------- implementation (* Increase of the value (value+1), returning the current value (i++) *) function Asc(var i: Int32): Int32; Inline; begin Result:=i; i+=1; end; function Asc(var i: uInt32): uInt32; Inline; begin Result:=i; i+=1; end; function Asc(var i: Int64): Int64; Inline; begin Result:=i; i+=1; end; function Asc(var i: uInt64): uInt64; Inline; begin Result:=i; i+=1; end; (* Decrease the value (value+1), returning the current value (i--) *) function Desc(var i: Int32): Int32; Inline; begin Result:=i; i-=1; end; function Desc(var i: uInt32): uInt32; Inline; begin Result:=i; i-=1; end; function Desc(var i: Int64): Int64; Inline; begin Result:=i; i-=1; end; function Desc(var i: uInt64): uInt64; Inline; begin Result:=i; i-=1; end; (* Excahnging values between A and B *) procedure Exch(var A,B:uInt8); Inline; overload; var t: uInt8; begin t := A; A := B; B := t; end; procedure Exch(var A,B:uInt16); Inline; overload; var t: uInt16; begin t := A; A := B; B := t; end; procedure Exch(var A,B:uInt32); Inline; overload; var t: uInt32; begin t := A; A := B; B := t; end; procedure Exch(var A,B:uInt64); Inline; overload; var t: uInt64; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Int8); Inline; overload; var t: Int8; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Int16); Inline; overload; var t: Int16; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Int32); Inline; overload; var t: Int32; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Int64); Inline; overload; var t: Int64; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Extended); Inline; overload; var t: Extended; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Double); Inline; overload; var t: Double; begin t := A; A := B; B := t; end; procedure Exch(var A,B:Single); Inline; overload; var t: Single; begin t := A; A := B; B := t; end; procedure Exch(var A,B:TPoint); Inline; overload; var t: TPoint; begin t := A; A := B; B := t; end; procedure Exch(var A,B:TBox); Inline; overload; var t: TBox; begin t := A; A := B; B := t; end; (* Excahnging values between A and B, but only if a > b. *) procedure ExchMin(var a,b:UInt8); Inline; Overload; var t:UInt8; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:UInt16); Inline; Overload; var t:UInt16; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:UInt32); Inline; Overload; var t:UInt32; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:UInt64); Inline; Overload; var t:UInt64; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Int8); Inline; Overload; var t:Int8; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Int16); Inline; Overload; var t:Int16; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Int32); Inline; Overload; var t:Int32; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Int64); Inline; Overload; var t:Int64; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Single); Inline; Overload; var t:Single; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Double); Inline; Overload; var t:Double; begin if (a > b) then begin t := a; a := b; b := t; end; end; procedure ExchMin(var a,b:Extended); Inline; Overload; var t:Extended; begin if (a > b) then begin t := a; a := b; b := t; end; end; (* Move functionallity (safe) and routines related to it !! Deprecated !! *) (* function ChopSize(D,S,L: Integer): Integer; Inline; begin Result := S; if ((D + S) >= L) then Result := (L - D) + 1; end; procedure Move(const InArr:AnsiString; var DestArr:AnsiString; source, dest, size:Integer); overload; var L:Integer; begin L := Length(InArr); if (L = 0) or (source >= L) then Exit; Move(InArr[source], DestArr[dest], size); end; procedure Move(const InArr:TIntArray; var DestArr:TIntArray; source, dest, size:Integer); overload; var L:Integer; begin L := Length(InArr); if (L = 0) or (source >= L) then Exit; Move(InArr[source], DestArr[dest], size* SizeOf(Integer)); end; procedure Move(const InArr:TExtArray; var DestArr:TExtArray; source, dest, size:Integer); overload; var L:Integer; begin L := Length(InArr); if (L = 0) or (source >= L) then Exit; Move(InArr[source], DestArr[dest], size * SizeOf(Extended)); end; procedure Move(const InArr:TPointArray; var DestArr:TPointArray; source, dest, size:Integer); overload; var L:Integer; begin L := Length(InArr); if (L = 0) or (source >= L) then Exit; Move(InArr[source], DestArr[dest], size * SizeOf(TPoint)); end; *) end.
unit ChromeLikeTabSetRes; interface uses SysUtils, Classes, vgComponent, vgCustomResources, vg_scene, ChromeLikeTabSetTypes, ImgList, vtPngImgList; type TChromeLikeTabSetResources = class(TDataModule) vgResources: TvgResources; CloseButtonImages: TvtNonFixedPngImageList; private function pm_GetCloseButtonImage( aState: TChromeLikeTabSetElementState): TImageIndex; public property CloseButtonImage[aState: TChromeLikeTabSetElementState]: TImageIndex read pm_GetCloseButtonImage; end; const cChromeLikeTabStyleName = 'ChromeLikeTabItemStyle'; cChromeLikeTabCloseButtonStyleName = 'ChromeLikeTabCloseButtonStyle'; cChromeLikeTabCloseButtonLayoutName = 'TabCloseButtonLayout'; // - название ресурса layout'a, в котором лежит кнопка закрытия вкладки cChromeLikeTabTextObjectResourceName = 'text'; // - название ресурса объекта текста на вкладке cChromeLikeTabCenterRectResourceName = 'Background';//'TabItemCenterRect'; // - название ресурса центрального прямоугольника вкладки cChromeLikeTabRightPathResourceName = 'RightEdgePart';//'TabItemRightPath'; // - название ресурса объекта TvgPath правого края вкладки cChromeLikeTabLeftPathResourceName = 'LeftEdgePart';//'TabItemLeftPath'; // - название ресурса объекта TvgPath левого края вкладки cChromeLikeTabTopLineResourceName = 'TopEdgeLine'; // - название ресурса объекта TvgLine верхней границы вкладки cChromeLikeTabBottomLineResourceName = 'BottomEdgeLine'; // - название ресурса объекта TvgLine нижней границы вкладки cChromeLikeTabCloseButtonInactiveBitmap = 'TabCloseButtonInactiveBitmap'; // - картинка для неактивного креста закрытия вкладки cChromeLikeTabCloseButtonActiveBitmap = 'TabCloseButtonActiveBitmap'; // - картинка для активного креста закрытия вкладки cChromeLikeTabIconImageName = 'TabIconImage'; // - название ресурса иконки таба cCloseButtonImages: array[TChromeLikeTabSetElementState] of TImageIndex = (0, -1, 1); // - картинки для крестика закрытия вкладки function ChromeLikeTabSetResources: TChromeLikeTabSetResources; implementation uses l3Base ; {$R *.dfm} var StdChromeLikeTabSetRes: TChromeLikeTabSetResources = nil; procedure Fini; begin FreeAndNil(StdChromeLikeTabSetRes); end; function ChromeLikeTabSetResources: TChromeLikeTabSetResources; begin Assert(not l3SystemDown); if (StdChromeLikeTabSetRes = nil) then begin StdChromeLikeTabSetRes := TChromeLikeTabSetResources.Create(nil); l3System.AddExitProc(Fini); end;//StdChromeLikeTabSetRes = nil Result := StdChromeLikeTabSetRes; end; { TChromeLikeTabSetResources } function TChromeLikeTabSetResources.pm_GetCloseButtonImage( aState: TChromeLikeTabSetElementState): TImageIndex; begin Result := cCloseButtonImages[aState]; end; end.
unit cSpecobj; interface uses contnrs; type TSpecObj = class(TObject) private _ID : Byte; _X1 : SmallInt; _Y1 : SmallInt; _X2 : SmallInt; _Y2 : SmallInt; _Width : SmallInt; _Height : SmallInt; public property ID : Byte read _ID write _ID; property X1 : SmallInt read _X1 write _X1; property Y1 : SmallInt read _Y1 write _Y1; property X2 : SmallInt read _X2 write _X2; property Y2 : SmallInt read _Y2 write _Y2; property Width : SmallInt read _width write _width; property Height : SmallInt read _Height write _height; end; TSpecObjList = class(TObjectList) protected function GetSpecObj(Index: Integer) : TSpecObj; procedure SetSpecObj(Index: Integer; const Value: TSpecObj); public function Add(AObject: TSpecObj) : Integer; property Items[Index: Integer] : TSpecObj read GetSpecObj write SetSpecObj;default; function Last : TSpecObj; end; implementation { TEnemyList } function TSpecObjList.Add(AObject: TSpecObj): Integer; begin Result := inherited Add(AObject); end; function TSpecObjList.GetSpecObj(Index: Integer): TSpecObj; begin Result := TSpecObj(inherited Items[Index]); end; procedure TSpecObjList.SetSpecObj(Index: Integer; const Value: TSpecObj); begin inherited Items[Index] := Value; end; function TSpecObjList.Last : TSpecObj; begin result := TSpecObj(inherited Last); end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, Data.FMTBcd, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Data.DB, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Comp.Client, FireDAC.Comp.DataSet, FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FMX.Controls.Presentation,uDM; type TFireDAC_SQLiteForm = class(TForm) ToolBar1: TToolBar; ListBox1: TListBox; btnAdd: TButton; Title: TLabel; btnDelete: TButton; procedure btnAddClick(Sender: TObject); procedure TaskListBeforeConnect(Sender: TObject); procedure TaskListAfterConnect(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure OnIdle(Sender: TObject; var FDone: Boolean); { Private declarations } public { Public declarations } end; var FireDAC_SQLiteForm: TFireDAC_SQLiteForm; implementation uses IOUtils; {$R *.fmx} procedure TFireDAC_SQLiteForm.btnAddClick(Sender: TObject); var LDefaultValue, LPrompt, TaskName: string; begin try LPrompt := 'Task'; LDefaultValue := ''; InputQuery('Enter New Task', LPrompt, LDefaultValue, procedure(const AResult: TModalResult; const AValues: array of string) begin if AResult = mrOk then TaskName := AValues[0] else TaskName := ''; if not (TaskName.Trim = '') then begin with DM do begin FDQueryInsert.ParamByName('TaskName').AsString := TaskName; FDQueryInsert.ExecSQL(); FDTableTask.Refresh; LinkFillControlToField1.BindList.FillList; end; end; end); except on e: Exception do begin SHowMessage(e.Message); end; end; end; procedure TFireDAC_SQLiteForm.btnDeleteClick(Sender: TObject); var TaskName: string; LIndex: Integer; begin TaskName := ListBox1.Selected.Text; try with DM do begin FDQueryDelete.ParamByName('TaskName').AsString := TaskName; FDQueryDelete.ExecSQL(); FDTableTask.Refresh; LinkFillControlToField1.BindList.FillList; if (ListBox1.Selected = nil) and (ListBox1.Count > 0) then // Select last item ListBox1.ItemIndex := ListBox1.Count - 1; end; except on e: Exception do begin SHowMessage(e.Message); end; end; end; procedure TFireDAC_SQLiteForm.FormCreate(Sender: TObject); begin try // For unidirectional dataset, don't refill automatically when dataset is activated // because dataset is reactivated everytime use DataSet.First. with DM do begin LinkFillControlToField1.AutoActivate := False; LinkFillControlToField1.AutoFill := False; Application.OnIdle := OnIdle; FireTaskList.Connected := True; FDTableTask.Active := True; LinkFillControlToField1.BindList.FillList; end; except on e: Exception do begin SHowMessage(e.Message); end; end; end; procedure TFireDAC_SQLiteForm.OnIdle(Sender: TObject; var FDone: Boolean); begin btnDelete.Visible := ListBox1.Selected <> nil; end; procedure TFireDAC_SQLiteForm.TaskListAfterConnect(Sender: TObject); begin dm.FireTaskList.ExecSQL ('CREATE TABLE IF NOT EXISTS Task (TaskName TEXT NOT NULL)'); end; procedure TFireDAC_SQLiteForm.TaskListBeforeConnect(Sender: TObject); begin with DM do begin {$IF DEFINED(IOS) or DEFINED(ANDROID)} FireTaskList.Params.Values['Database'] := TPath.GetDocumentsPath + PathDelim + 'tasks.s3db'; // was: GetHomePath + PathDelim + // 'Documents' + PathDelim + 'tasks.s3db'; {$ELSEIF defined(MSWINDOWS)} FireTaskList.Params.Values['Database'] := TPath.GetDocumentsPath + PathDelim + 'tasks.s3db'; {$ELSEIF defined(MACOS)} {$ELSEIF defined(POSIX)} {$ENDIF} end; end; // better use: end.
Unit MazeGen; interface uses MazeMain; Procedure GenMazeHuntAKill(var MazeToCreate: TMaze; StartPoint: TPos); Procedure GenMazeBackTrack(var MazeToCreate: TMaze; Cell: TPos); Procedure GenMazePrim(var MazeToCreate: TMaze; StartPoint: TPos); implementation type TCource = (Up, Down, Right, Left); //Shuffle array with sides Procedure ShuffleArr(var ArrToShuffle: array of TCource); //Swap two elements Procedure Swap(var SwapArr: array of TCource; Ind1, Ind2: Integer); Var Temp: TCource; Begin Temp := SwapArr[Ind1]; SwapArr[Ind1] := SwapArr[Ind2]; SwapArr[Ind2] := Temp; End; Var I: Integer; Begin For I := 0 to High(ArrToShuffle)*2 do Swap(ArrToShuffle, Random(Length(ArrToShuffle)), Random(Length(ArrToShuffle))); End; //Check the direction of travel so that no loops are formed Function CheckCell(const MazeToCheck: TMaze; CellPos: TPos; Side: TCource): Boolean; //Return Y-1 pos, check for the Maze size Function GetYMinPos(const Arr: TMaze; YPos: Integer): Integer; begin if YPos = Low(Arr) then Result := YPos else Result := YPos - 1; end; //Resurn Y+1 pos, check for the Maze size Function GetYMaxPos(const Arr: TMaze; YPos: Integer): Integer; begin if YPos = High(Arr) then Result := YPos else Result := YPos + 1; end; //Resurn X-1 pos, check for the Maze size Function GetXMinPos(const Arr: TMaze; XPos: Integer): Integer; begin if XPos = Low(Arr[0]) then Result := XPos else Result := XPos - 1; end; //Resurn X+1 pos, check for the Maze size Function GetXMaxPos(const Arr: TMaze; XPos: Integer): Integer; begin if XPos = High(Arr[0]) then Result := XPos else Result := XPos + 1; end; //Return amount of passes around the cell with cell Function GetAmountOfPass(const ArrToCheck: TMaze; Point: TPos): Integer; var I, J: Integer; begin Result := 0; //Check maze from Cell.Y + 1 to Cell.Y - 1 and X +- 1 //Check for the borders for I := GetYMinPos(ArrToCheck, Point.PosY) to GetYMaxPos(ArrToCheck, Point.PosY) do for J := GetXMinPos(ArrToCheck, Point.PosX) to GetXMaxPos(ArrToCheck, Point.PosX) do if ArrToCheck[I, J] = Pass then Inc(Result); end; //Return amount of passes behind the direction of movement of the cell Function GetOppositePass(const ArrToCheck: TMaze; Point: TPos; SideNow: TCource): Integer; //If dir Right or Left Function CheckLineX(Const ArrLine: TMaze; Ind1, Ind2, Line: Integer): Integer; var I: Integer; begin Result := 0; for I := Ind1 to Ind2 do if ArrLine[I, Line] = Pass then Inc(Result); end; //If dir Up or Down Function CheckLineY(Const ArrLine: TMaze; Ind1, Ind2, Line: Integer): Integer; var I: Integer; begin Result := 0; for I := Ind1 to Ind2 do if ArrLine[Line, I] = Pass then Inc(Result); end; Begin Case SideNow of Up: Result := CheckLineY(ArrToCheck, GetXMinPos(ArrToCheck, Point.PosX), GetXMaxPos(ArrToCheck, Point.PosX), GetYMaxPos(ArrToCheck, Point.PosY)); Down: Result := CheckLineY(ArrToCheck, GetXMinPos(ArrToCheck, Point.PosX), GetXMaxPos(ArrToCheck, Point.PosX), GetYMinPos(ArrToCheck, Point.PosY)); Right: Result := CheckLineX(ArrToCheck, GetYMinPos(ArrToCheck, Point.PosY), GetYMaxPos(ArrToCheck, Point.PosY), GetXMinPos(ArrToCheck, Point.PosX)); Left: Result := CheckLineX(ArrToCheck, GetYMinPos(ArrToCheck, Point.PosY), GetYMaxPos(ArrToCheck, Point.PosY), GetXMaxPos(ArrToCheck, Point.PosX)); End; End; Const ModifX: array [0 .. 3] of Integer = (0, 0, 1, -1); ModifY: array [0 .. 3] of Integer = (-1, 1, 0, 0); Begin Inc(CellPos.PosX, ModifX[Ord(Side)]); Inc(CellPos.PosY, ModifY[Ord(Side)]); {1. Check for the maze sizes 2. Check front side for wall 3. Sub The number of passes around the cell and the cell itself - Behind the direction of travel} If (CellPos.PosX < 0) or (CellPos.PosY < 0) or (CellPos.PosX > High(MazeToCheck[0])) or (CellPos.PosY > High(MazeToCheck)) then Result := False Else If (MazeToCheck[CellPos.PosY, CellPos.PosX] = Pass) then Result := False Else If GetAmountOfPass(MazeToCheck, CellPos) - GetOppositePass(MazeToCheck, CellPos, Side) = 0 then Result := True else Result := False; End; //Algorithm Hunt-and-Kill Procedure GenMazeHuntAKill(var MazeToCreate: TMaze; StartPoint: TPos); const isMazeGenerated = -3; //Breaking the path until there's nowhere to go Procedure Walk(var MazeToGen: TMaze; const StartP: TPos); Const ModifX: array [0 .. 3] of Integer = (0, 0, 1, -1); ModifY: array [0 .. 3] of Integer = (-1, 1, 0, 0); Var Cell: TPos; CourceNow: TCource; NumberOfCheckSides: Integer; DirFound: Boolean; Dir: array of TCource; Begin Dir := [Up, Down, Right, Left]; Cell := StartP; MazeToGen[Cell.PosY, Cell.PosX] := Pass; //Repeats until it runs into a hopeless situation Repeat DirFound := False; NumberOfCheckSides := 0; ShuffleArr(Dir); //Checking each direction of travel While (NumberOfCheckSides < 4) and not DirFound do Begin CourceNow := Dir[NumberOfCheckSides]; If CheckCell(MazeToGen, Cell, CourceNow) then Begin Inc(Cell.PosX, ModifX[Ord(CourceNow)]); Inc(Cell.PosY, ModifY[Ord(CourceNow)]); MazeToGen[Cell.PosY, Cell.PosX] := Pass; DirFound := True; End else Inc(NumberOfCheckSides); End; Until (NumberOfCheckSides >= 4) or not DirFound; End; //Finding the first free cell to continue the path Function Hunt(const MazeToGen: TMaze): TPos; //Find available cells near cell Function CheckNeighbors(const MazeWithCell: TMaze; CellToCheck: TPos): Boolean; Const Dir: array [0..3] of TCource = (Up, Down, Right, Left); Var CourceNow: TCource; Begin Result := False; For CourceNow in Dir do If CheckCell(MazeWithCell, CellToCheck, CourceNow) then Result := True; End; Var PointFound: Boolean; Cell: TPos; Begin Result.PosX := isMazeGenerated; PointFound := False; //Check all cells of maze Cell.PosY := 0; While (Cell.PosY <= High(MazeToGen)) and not PointFound do Begin Cell.PosX := 0; While (Cell.PosX <= High(MazeToGen[Cell.PosY])) and not PointFound do Begin //If Pass and there are available direcrion, return Cell If (MazeToGen[Cell.PosY, Cell.PosX] = Pass) and CheckNeighbors(MazeToGen, Cell) then Begin Result := Cell; PointFound := True; End; Inc(Cell.PosX); End; Inc(Cell.PosY); End; End; Var Position: TPos; Begin Position := StartPoint; While Position.PosX <> isMazeGenerated do Begin Walk(MazeToCreate, Position); Position := Hunt(MazeToCreate); End; End; //Algorithm BackTracker Procedure GenMazeBackTrack(var MazeToCreate: TMaze; Cell: TPos); Var Dir: array of TCource; CourceNow: TCource; NewCell: TPos; Begin Dir := [Up, Down, Right, Left]; MazeToCreate[Cell.PosY, Cell.PosX] := Pass; ShuffleArr(Dir); //Check each direction for a cell For CourceNow in Dir do Begin //If direction available, break wall If CheckCell(MazeToCreate, Cell, CourceNow) then Begin NewCell := Cell; Case CourceNow of Up: Dec(NewCell.PosY); Down: Inc(NewCell.PosY); Right: Inc(NewCell.PosX); Left: Dec(NewCell.PosX); End; GenMazeBackTrack(MazeToCreate, NewCell); End End; End; //Algorithm Prims Procedure GenMazePrim(var MazeToCreate: TMaze; StartPoint: TPos); Type TFront = array of TPos; //Add Neighbors for a cell to Array Procedure AddNeighbors(const MazeToCmp: TMaze; var SetOfPoints: TFront; PosToCheck: TPos); //Add Neighbors Procedure AddPointToFront(var ArrWithPoints: TFront; Pos: TPos; Direction: TCource); const ModifX: array [0..3] of Integer = (0, 0, 1, -1); ModifY: array [0..3] of Integer = (-1, 1, 0, 0); Var NewPos: TPos; Begin NewPos.PosX := Pos.PosX + ModifX[Ord(Direction)]; NewPos.PosY := Pos.PosY + ModifY[Ord(Direction)]; SetLength(SetOfPoints, Length(SetOfPoints)+1); SetOfPoints[High(SetOfPoints)] := NewPos; End; //Get array with broken walls and wtih cells which located in Queue Function GetShadowMaze(MazeToModif: TMaze; const Points: TFront): TMaze; Var I: Integer; Begin For I := 0 to High(Points) do MazeToModif[Points[I].PosY, Points[I].PosX] := Pass; Result := MazeToModif; End; Const Dir: array of TCource = [Up, Down, Right, Left]; Var CourceNow: TCource; Begin //Check each direction for cell, and add Neighbors For CourceNow in Dir do If CheckCell(GetShadowMaze(MazeToCmp, SetOfPoints), PosToCheck, CourceNow) then AddPointToFront(SetOfPoints, PosToCheck, CourceNow); End; //Get random sell from array with neighbors Function GetRandomCell(var SetOfPoints: TFront): TPos; Var I: Integer; Begin I := Random(Length(SetOfPoints)); Result := SetOfPoints[I]; SetOfPoints[I] := SetOfPoints[High(SetOfPoints)]; SetOfPoints[High(SetOfPoints)] := Result; SetLength(SetOfPoints, High(SetOfPoints)); end; Var Frontier: TFront; Cell: TPos; Begin SetLength(Frontier, 1); Frontier[0] := StartPoint; While Length(Frontier) <> 0 do Begin Cell := GetRandomCell(Frontier); MazeToCreate[Cell.PosY, Cell.PosX] := Pass; AddNeighbors(MazeToCreate, Frontier, Cell); End; End; end.
unit msmModelElementDir; {* Список содержимого элемента в виде директории } // Модуль: "w:\common\components\gui\Garant\msm\msmModelElementDir.pas" // Стереотип: "SimpleClass" // Элемент модели: "TmsmModelElementDir" MUID: (57B1674A02B6) {$Include w:\common\components\msm.inc} interface uses l3IntfUses , msmViewOfModelElement , msmElementViews , msmModelElements , l3Interfaces ; type TmsmModelElementDir = class(TmsmViewOfModelElement, ImsmModelElementStringList) {* Список содержимого элемента в виде директории } private f_List: ImsmModelElementList; f_Parent: ImsmModelElement; protected function IsDir: Boolean; virtual; function Get_Item(anIndex: Integer): ImsmModelElement; function Get_Count: Integer; function Get_Owner: ImsmModelElement; function Get_Strings(anIndex: Integer): Il3CString; function Get_StringsToFind(anIndex: Integer): Il3CString; procedure Cleanup; override; {* Функция очистки полей объекта. } {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure ClearFields; override; public constructor Create(const anElement: TmsmModelElementView); reintroduce; class function Make(const anElement: TmsmModelElementView): ImsmModelElementStringList; reintroduce; function IndexOfElementView(const anElement: ImsmModelElement): Integer; end;//TmsmModelElementDir implementation uses l3ImplUses , tfwCStringFactory //#UC START# *57B1674A02B6impl_uses* , StrUtils , l3String , l3Base //#UC END# *57B1674A02B6impl_uses* ; constructor TmsmModelElementDir.Create(const anElement: TmsmModelElementView); //#UC START# *57B1682902FF_57B1674A02B6_var* //#UC END# *57B1682902FF_57B1674A02B6_var* begin //#UC START# *57B1682902FF_57B1674A02B6_impl* if (anElement.rElement = nil) then f_Parent := nil else f_Parent := anElement.rElement.Parent; if (anElement.rElement = nil) then f_List := nil else f_List := anElement.rElement.MEList[anElement.rListName]; inherited Create(anElement); //#UC END# *57B1682902FF_57B1674A02B6_impl* end;//TmsmModelElementDir.Create class function TmsmModelElementDir.Make(const anElement: TmsmModelElementView): ImsmModelElementStringList; var l_Inst : TmsmModelElementDir; begin l_Inst := Create(anElement); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TmsmModelElementDir.Make function TmsmModelElementDir.IsDir: Boolean; //#UC START# *57B57DE500CF_57B1674A02B6_var* //#UC END# *57B57DE500CF_57B1674A02B6_var* begin //#UC START# *57B57DE500CF_57B1674A02B6_impl* Result := true; //#UC END# *57B57DE500CF_57B1674A02B6_impl* end;//TmsmModelElementDir.IsDir function TmsmModelElementDir.Get_Item(anIndex: Integer): ImsmModelElement; //#UC START# *57AAD86403AD_57B1674A02B6get_var* //#UC END# *57AAD86403AD_57B1674A02B6get_var* begin //#UC START# *57AAD86403AD_57B1674A02B6get_impl* if (anIndex < 0) then Result := nil else begin if IsDir then if (f_Parent <> nil) then begin if (anIndex = 0) then begin Result := f_Parent; Exit; end;//anIndex = 0 Dec(anIndex); end;//f_Parent <> nil Result := f_List[anIndex]; end;//anIndex < 0 //#UC END# *57AAD86403AD_57B1674A02B6get_impl* end;//TmsmModelElementDir.Get_Item function TmsmModelElementDir.Get_Count: Integer; //#UC START# *57AAD89C0277_57B1674A02B6get_var* //#UC END# *57AAD89C0277_57B1674A02B6get_var* begin //#UC START# *57AAD89C0277_57B1674A02B6get_impl* Result := f_List.Count; if IsDir then if (f_Parent <> nil) then Inc(Result); //#UC END# *57AAD89C0277_57B1674A02B6get_impl* end;//TmsmModelElementDir.Get_Count function TmsmModelElementDir.Get_Owner: ImsmModelElement; //#UC START# *57AE2E140297_57B1674A02B6get_var* //#UC END# *57AE2E140297_57B1674A02B6get_var* begin //#UC START# *57AE2E140297_57B1674A02B6get_impl* Result := Element.rElement; //#UC END# *57AE2E140297_57B1674A02B6get_impl* end;//TmsmModelElementDir.Get_Owner function TmsmModelElementDir.Get_Strings(anIndex: Integer): Il3CString; //#UC START# *57AEBED1018D_57B1674A02B6get_var* //#UC END# *57AEBED1018D_57B1674A02B6get_var* begin //#UC START# *57AEBED1018D_57B1674A02B6get_impl* Result := Get_Item(anIndex).StringProp[Element.rTextName]; if IsDir then if (anIndex = 0) AND (f_Parent <> nil) then begin if IsDir then Result := TtfwCStringFactory.Cat(TtfwCStringFactory.C('.. '), Result); end;//(anIndex = 0) AND (f_Parent <> nil) //#UC END# *57AEBED1018D_57B1674A02B6get_impl* end;//TmsmModelElementDir.Get_Strings function TmsmModelElementDir.Get_StringsToFind(anIndex: Integer): Il3CString; //#UC START# *57B6C7D40215_57B1674A02B6get_var* //#UC END# *57B6C7D40215_57B1674A02B6get_var* begin //#UC START# *57B6C7D40215_57B1674A02B6get_impl* Result := Get_Item(anIndex).StringProp['DefaultSearchText']; //#UC END# *57B6C7D40215_57B1674A02B6get_impl* end;//TmsmModelElementDir.Get_StringsToFind function TmsmModelElementDir.IndexOfElementView(const anElement: ImsmModelElement): Integer; //#UC START# *57D1327900BC_57B1674A02B6_var* //#UC END# *57D1327900BC_57B1674A02B6_var* begin //#UC START# *57D1327900BC_57B1674A02B6_impl* if IsDir then if (f_Parent <> nil) then if f_Parent.IsSameElementView(anElement) then begin Result := 0; Exit; end;//f_Parent.IsSameElement(anElement) Result := f_List.IndexOfElementView(anElement); if (Result >= 0) then if IsDir then if (f_Parent <> nil) then Inc(Result); //#UC END# *57D1327900BC_57B1674A02B6_impl* end;//TmsmModelElementDir.IndexOfElementView procedure TmsmModelElementDir.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57B1674A02B6_var* //#UC END# *479731C50290_57B1674A02B6_var* begin //#UC START# *479731C50290_57B1674A02B6_impl* f_List := nil; f_Parent := nil; inherited; //#UC END# *479731C50290_57B1674A02B6_impl* end;//TmsmModelElementDir.Cleanup {$If NOT Defined(DesignTimeLibrary)} class function TmsmModelElementDir.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_57B1674A02B6_var* //#UC END# *47A6FEE600FC_57B1674A02B6_var* begin //#UC START# *47A6FEE600FC_57B1674A02B6_impl* Result := true; //#UC END# *47A6FEE600FC_57B1674A02B6_impl* end;//TmsmModelElementDir.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure TmsmModelElementDir.ClearFields; begin f_List := nil; f_Parent := nil; inherited; end;//TmsmModelElementDir.ClearFields end.
unit SensorMonitorsU; interface uses System.Bluetooth.Components, System.Bluetooth,System.SysUtils, FMX.Edit; type // Update Event Heart Monitor TEventHeartMonitorUpdateData = procedure(const AMeasurement : string; const ASensorLocation : String) of object; // Heart monitor THeartMonitor = class private FBluetoothLE : TBluetoothLE; FBLEDevice: TBluetoothLEDevice; FRateMeasurementData: string; FSensorLocationData: string; FHRGattService: TBluetoothGattService; FHRMeasurementGattCharact: TBluetoothGattCharacteristic; FBodySensorLocationGattCharact: TBluetoothGattCharacteristic; FOnUpdateData: TEventHeartMonitorUpdateData; procedure ManageCharacteristicData(const ACharacteristic: TBluetoothGattCharacteristic); function GetMeasurementData(Data: TBytes): String; function GetSensorLocationData(Index: Byte): String; protected procedure OnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure OnEndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure UpdateData(const ADataMea : String; const ADataSensor : String); public constructor Create; procedure Connect; procedure Disconnect; destructor Destroy; override; public property RateMeasurementData : string read FRateMeasurementData; property SensorLocationData : string read FSensorLocationData; property OnUpdateData : TEventHeartMonitorUpdateData read FOnUpdateData write FOnUpdateData; end; // Update Event Heart Monitor TEventWeightMonitorUpdateData = procedure(const AWeight : double) of object; // Weight Monitor TWeightMonitor = class private FBluetoothLE : TBluetoothLE; FBLEDevice: TBluetoothLEDevice; FOnUpdateData: TEventWeightMonitorUpdateData; FWeightGattService: TBluetoothGattService; FWeightMeasurementGattCharacteristic: TBluetoothGattCharacteristic; protected procedure OnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure OnEndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure UpdateData(const AWeight : double); public constructor Create; procedure Connect; procedure Disconnect; destructor Destroy; override; public property OnUpdateData : TEventWeightMonitorUpdateData read FOnUpdateData write FOnUpdateData; end; implementation uses System.Classes, FMX.Dialogs; type TSensorContactStatus = (NonSupported, NonDetected, Detected); THRMFlags = record HRValue16bits: boolean; SensorContactStatus: TSensorContactStatus; EnergyExpended: boolean; RRInterval: boolean; end; const HEART_HRSERVICE: TBluetoothUUID = '{0000180D-0000-1000-8000-00805F9B34FB}'; HEART_HRMEASUREMENT_CHARACTERISTIC: TBluetoothUUID = '{00002A37-0000-1000-8000-00805F9B34FB}'; HEART_BODY_SENSOR_LOCATION_CHARACTERISTIC: TBluetoothUUID = '{00002A38-0000-1000-8000-00805F9B34FB}'; BodySensorLocations : array[0..6] of string = ('Other', 'Chest', 'Wrist', 'Finger', 'Hand', 'Ear Lobe', 'Foot'); HEART_HR_VALUE_FORMAT_MASK = $1; HEART_SENSOR_CONTACT_STATUS_MASK = $6; HEART_ENERGY_EXPANDED_STATUS_MASK = $8; HEART_RR_INTERVAL_MASK = $10; WEIGHT_DEVICE: TBluetoothUUID = '{00001901-0000-1000-8000-00805F9B34FB}'; WEIGHT_SERVICE: TBluetoothUUID = '{00001901-0000-1000-8000-00805F9B34FB}'; WEIGHT_CHARACTERISTIC : TBluetoothUUID = '{00002B01-0000-1000-8000-00805F9B34FB}'; { TWeightMonitor } procedure THeartMonitor.Connect; begin FBluetoothLE.Enabled := True; FBluetoothLE.DiscoverDevices(2500, [HEART_HRSERVICE]); end; constructor THeartMonitor.Create; begin inherited; FBluetoothLE := TBluetoothLE.Create(nil); FBluetoothLE.OnCharacteristicRead := OnCharacteristicRead; FBluetoothLE.OnEndDiscoverDevices := OnEndDiscoverDevices; end; destructor THeartMonitor.Destroy; begin Disconnect(); FreeAndNil(FBluetoothLE); inherited; end; procedure THeartMonitor.Disconnect; begin try if FHRMeasurementGattCharact <> nil then begin if FBluetoothLE.Enabled then begin FBluetoothLE.UnSubscribeToCharacteristic(FBLEDevice, FHRMeasurementGattCharact); FBluetoothLE.UnSubscribeToCharacteristic(FBLEDevice, FBodySensorLocationGattCharact); FBLEDevice.Disconnect(); end end; FBluetoothLE.Enabled := False; except FBluetoothLE.Enabled := False; end; end; function GetFlags(Data: Byte): THRMFlags; var LValue: Byte; begin Result.HRValue16bits := (Data and HEART_HR_VALUE_FORMAT_MASK) = 1; LValue := (Data and HEART_SENSOR_CONTACT_STATUS_MASK) shr 1; case LValue of 2: Result.SensorContactStatus := NonDetected; 3: Result.SensorContactStatus := Detected; else Result.SensorContactStatus := NonSupported; end; Result.EnergyExpended := ((Data and HEART_ENERGY_EXPANDED_STATUS_MASK) shr 3) = 1; Result.RRInterval := ((Data and HEART_RR_INTERVAL_MASK) shr 4) = 1; end; function THeartMonitor.GetMeasurementData(Data: TBytes): String; var Flags: THRMFlags; LBPM: Integer; begin Flags := GetFlags(Data[0]); if Flags.HRValue16bits then LBPM := Data[1] + (Data[2] * 16) else LBPM := Data[1]; begin Result := LBPM.ToString + ' bpm'; end; end; function THeartMonitor.GetSensorLocationData(Index: Byte): String; begin if Index > 6 then Result := '' else Result := BodySensorLocations[Index]; end; procedure THeartMonitor.ManageCharacteristicData(const ACharacteristic: TBluetoothGattCharacteristic); begin if ACharacteristic.UUID = HEART_HRMEASUREMENT_CHARACTERISTIC then begin FRateMeasurementData := GetMeasurementData(ACharacteristic.Value); end; if ACharacteristic.UUID = HEART_BODY_SENSOR_LOCATION_CHARACTERISTIC then begin FSensorLocationData := GetSensorLocationData(ACharacteristic.Value[0]); end; UpdateData(FRateMeasurementData, FSensorLocationData); end; function BytesToString(const B: TBytes): string; var I: Integer; begin if Length(B) > 0 then begin Result := Format('%0.2X', [B[0]]); for I := 1 to High(B) do Result := Result + Format(' %0.2X', [B[I]]); end else Result := ''; end; procedure THeartMonitor.OnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var LSValue: string; begin if AGattStatus = TBluetoothGattStatus.Success then begin LSValue := BytesToString(ACharacteristic.Value); ManageCharacteristicData(ACharacteristic); end; end; procedure THeartMonitor.OnEndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin try if(ADeviceList.Count > 0)then begin if FBluetoothLE.DiscoveredDevices.Count > 0 then begin FBLEDevice := FBluetoothLE.DiscoveredDevices.First(); if FBluetoothLE.GetServices(FBLEDevice).Count > 0 then begin FHRGattService := nil; FHRMeasurementGattCharact := nil; FBodySensorLocationGattCharact := nil; FHRGattService := FBluetoothLE.GetService(FBLEDevice, HEART_HRSERVICE); if FHRGattService <> nil then begin FBluetoothLE.GetCharacteristics(FHRGattService); FHRMeasurementGattCharact := FBluetoothLE.GetCharacteristic (FHRGattService, HEART_HRMEASUREMENT_CHARACTERISTIC); FBodySensorLocationGattCharact := FBluetoothLE.GetCharacteristic (FHRGattService, HEART_BODY_SENSOR_LOCATION_CHARACTERISTIC); end; if FHRMeasurementGattCharact <> nil then begin if FBluetoothLE.Enabled then begin FBluetoothLE.SubscribeToCharacteristic(FBLEDevice, FHRMeasurementGattCharact); end end; end; end end else begin Disconnect(); ShowMessage('Device not found!'); end; except Disconnect(); ShowMessage('Device not found!'); end; end; procedure THeartMonitor.UpdateData(const ADataMea, ADataSensor: String); begin if Assigned(FOnUpdateData) then OnUpdateData(ADataMea, ADataSensor); end; { TWeightMonitor } procedure TWeightMonitor.Connect; begin FBluetoothLE.Enabled := True; FBluetoothLE.DiscoverDevices(3500, [WEIGHT_DEVICE]); end; constructor TWeightMonitor.Create; begin inherited; FBluetoothLE := TBluetoothLE.Create(nil); FBluetoothLE.OnCharacteristicRead := OnCharacteristicRead; FBluetoothLE.OnEndDiscoverDevices := OnEndDiscoverDevices; end; destructor TWeightMonitor.Destroy; begin Disconnect(); FreeAndNil(FBluetoothLE); inherited; end; procedure TWeightMonitor.Disconnect; begin try if FWeightMeasurementGattCharacteristic <> nil then begin if FBluetoothLE.Enabled then begin FBluetoothLE.UnSubscribeToCharacteristic(FBLEDevice, FWeightMeasurementGattCharacteristic); FBLEDevice.Disconnect(); end end; FBluetoothLE.Enabled := False; except FBluetoothLE.Enabled := False; end; end; procedure TWeightMonitor.OnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var WeightPounds : double; begin if AGattStatus = TBluetoothGattStatus.Success then begin // calculate weight - characteristic is in hectograms // ignore last two bytes, take first 6 bytes - that is hectograms WeightPounds := (ACharacteristic.GetValueAsInteger shr 8) * 0.2205; UpdateData(WeightPounds); end; end; procedure TWeightMonitor.OnEndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin try if(ADeviceList.Count > 0) then begin if FBluetoothLE.DiscoveredDevices.Count > 0 then begin FBLEDevice := FBluetoothLE.DiscoveredDevices.First(); if FBluetoothLE.GetServices(FBLEDevice).Count > 0 then begin FWeightGattService := nil; FWeightMeasurementGattCharacteristic := nil; FWeightGattService := FBluetoothLE.GetService(FBLEDevice, WEIGHT_SERVICE); if FWeightGattService <> nil then begin FBluetoothLE.GetCharacteristics(FWeightGattService); FWeightMeasurementGattCharacteristic := FBluetoothLE.GetCharacteristic (FWeightGattService, WEIGHT_CHARACTERISTIC); end; if FWeightMeasurementGattCharacteristic <> nil then begin if FBluetoothLE.Enabled then begin FBluetoothLE.SubscribeToCharacteristic(FBLEDevice, FWeightMeasurementGattCharacteristic); end end; end; end end else begin Disconnect(); ShowMessage('Device not found!'); end; except Disconnect(); ShowMessage('Device not found!'); end; end; procedure TWeightMonitor.UpdateData(const AWeight: double); begin if Assigned(FOnUpdateData) then OnUpdateData(AWeight); end; end.
program calendar(input, output); type month = (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec); var days : array [month] of 28 .. 31; mon, this : month; year : integer; function isLeapYear(y : integer) : boolean; begin isLeapYear := (y mod 400 = 0) or ((y mod 4 = 0) and (y mod 100 <> 0)) end; function dayOfWeek(d, m, y : real) : 1 .. 7; begin dayOfWeek := (d + m + y + (y div 4) + end; procedure populateDays(); begin for this := jan to dec do begin case this of jan, mar, may, jul, aug, oct, dec: days[this] := 31; apr, jun, sep, nov: days[this] := 30; feb: begin if isLeapYear(year) then days[this] := 29 else days[this] := 28 end; end; end; end; begin read(mon, year); populateDays(); for this := jan to dec do writeln(this, ' ', days[this]) end.
unit StockDataApp; interface uses define_stockapp, define_dealItem, define_StockDataApp, windef_msg, UtilsHttp, win.process, BaseApp, Forms, BaseForm, BaseStockApp, StockDataDownloaderApp, StockDataConsoleApp; type TStockDataAppData = record RunMode: TStockDataAppRunMode; AppAgent: TBaseAppAgent; ConsoleAppData: TConsoleAppData; DownloaderAppData: TDownloaderAppData; end; TStockDataApp = class(TBaseStockApp) protected fStockDataAppData: TStockDataAppData; function CreateAppCommandWindow: Boolean; procedure RunStart; procedure RunStart_Console(AConsoleApp: PConsoleAppData); procedure RunStart_Downloader; function Console_GetNextDownloadDealItem(AConsoleApp: PConsoleAppData): PRT_DealItem; procedure Console_NotifyDownloadData(AConsoleApp: PConsoleAppData; ADealItem: PRT_DealItem); overload; procedure Console_NotifyDownloadData(AConsoleApp: PConsoleAppData); overload; procedure Console_Notify_DownloadOK(AStockCode: integer); function Console_CheckDownloaderProcess(AConsoleApp: PConsoleAppData): Boolean; procedure Downloader_Download(ADownloaderApp: PDownloaderAppData; AStockCode: integer); overload; procedure Downloader_Download(AStockCode: integer); overload; function Downloader_CheckConsoleProcess(ADownloaderApp: PDownloaderAppData): Boolean; public constructor Create(AppClassId: AnsiString); override; procedure Run; override; function Initialize: Boolean; override; procedure Finalize; override; end; implementation uses Windows, Sysutils, Classes, SDConsoleForm, Define_Price, db_dealitem, Define_DataSrc, StockDayData_Get_163, win.iobuffer, UtilsLog, StockDayDataAccess, StockDayData_Load, StockDayData_Save, define_stock_quotes, DB_dealItem_Load, DB_dealItem_Save; { TStockDataApp } constructor TStockDataApp.Create(AppClassId: AnsiString); begin inherited; FillChar(fStockDataAppData, SizeOf(fStockDataAppData), 0); end; function TStockDataApp.Initialize: Boolean; begin Result := inherited Initialize; if Result then begin Result := CheckSingleInstance(AppMutexName_StockDataDownloader_Console); if Result then begin fStockDataAppData.RunMode := runMode_Console; Result := CreateAppCommandWindow; if not Result then exit; InitializeDBStockItem; Result := 0 < Self.StockItemDB.RecordCount; if Result then begin fStockDataAppData.AppAgent := TStockDataConsoleApp.Create(Self); fStockDataAppData.AppAgent.Initialize; end; end else begin Result := CheckSingleInstance(AppMutexName_StockDataDownloader); if Result then begin UtilsLog.CloseLogFiles; UtilsLog.G_LogFile.FileName := ChangeFileExt(ParamStr(0), '.down.log'); UtilsLog.SDLog('StockDataApp.pas', 'init mode downloader'); fStockDataAppData.RunMode := runMode_DataDownloader; Result := CreateAppCommandWindow; if not Result then exit; InitializeDBStockItem; Result := 0 < Self.StockItemDB.RecordCount; end; end; end; end; procedure TStockDataApp.Finalize; begin end; function AppCommandWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := 0; case AMsg of WM_AppStart: begin if nil <> GlobalBaseStockApp then begin TStockDataApp(GlobalBaseStockApp).RunStart; end; exit; end; WM_AppRequestEnd: begin TStockDataApp(GlobalBaseStockApp).Terminate; end; WM_Downloader2Console_Command_DownloadOK: begin TStockDataApp(GlobalBaseStockApp).Console_Notify_DownloadOK(wParam); end; WM_Console2Downloader_Command_Download: begin PostMessage(AWnd, WM_Downloader_Command_Download, wParam, 0) end; WM_Downloader_Command_Download: begin TStockDataApp(GlobalBaseStockApp).Downloader_Download(wParam); end; end; Result := DefWindowProcA(AWnd, AMsg, wParam, lParam); end; function TStockDataApp.CreateAppCommandWindow: Boolean; var tmpRegWinClass: TWndClassA; tmpGetWinClass: TWndClassA; tmpIsReged: Boolean; begin Result := false; if runMode_Undefine = fStockDataAppData.RunMode then exit; FillChar(tmpRegWinClass, SizeOf(tmpRegWinClass), 0); tmpRegWinClass.hInstance := HInstance; tmpRegWinClass.lpfnWndProc := @AppCommandWndProcA; if runMode_Console = fStockDataAppData.RunMode then begin tmpRegWinClass.lpszClassName := AppCmdWndClassName_StockDataDownloader_Console; end; if runMode_DataDownloader = fStockDataAppData.RunMode then begin tmpRegWinClass.lpszClassName := AppCmdWndClassName_StockDataDownloader; end; tmpIsReged := GetClassInfoA(HInstance, tmpRegWinClass.lpszClassName, tmpGetWinClass); if tmpIsReged then begin if (tmpGetWinClass.lpfnWndProc <> tmpRegWinClass.lpfnWndProc) then begin UnregisterClassA(tmpRegWinClass.lpszClassName, HInstance); tmpIsReged := false; end; end; if not tmpIsReged then begin if 0 = RegisterClassA(tmpRegWinClass) then exit; end; fBaseWinAppData.AppCmdWnd := CreateWindowExA( WS_EX_TOOLWINDOW //or WS_EX_APPWINDOW //or WS_EX_TOPMOST , tmpRegWinClass.lpszClassName, '', WS_POPUP {+ 0}, 0, 0, 0, 0, HWND_MESSAGE, 0, HInstance, nil); Result := Windows.IsWindow(fBaseWinAppData.AppCmdWnd); end; procedure TStockDataApp.Console_NotifyDownloadData(AConsoleApp: PConsoleAppData; ADealItem: PRT_DealItem); begin if nil = ADealItem then begin PostMessage(AConsoleApp.Downloader_Process.Core.AppCmdWnd, WM_AppRequestEnd, 0, 0); exit; end; if Console_CheckDownloaderProcess(AConsoleApp) then begin PostMessage(AConsoleApp.Downloader_Process.Core.AppCmdWnd, WM_Console2Downloader_Command_Download, ADealItem.iCode, 0); end; end; function TStockDataApp.Console_GetNextDownloadDealItem(AConsoleApp: PConsoleAppData): PRT_DealItem; var tmpDealItem: PRT_DealItem; begin Result := nil; if 1 > Self.StockItemDB.RecordCount then exit; if 0 > fStockDataAppData.ConsoleAppData.Download_DealItemIndex then fStockDataAppData.ConsoleAppData.Download_DealItemIndex := 0; if Self.StockItemDB.RecordCount <= fStockDataAppData.ConsoleAppData.Download_DealItemIndex then exit; if 0 = fStockDataAppData.ConsoleAppData.Download_DealItemCode then begin Result := Self.StockItemDB.Items[fStockDataAppData.ConsoleAppData.Download_DealItemIndex]; end else begin tmpDealItem := Self.StockItemDB.Items[fStockDataAppData.ConsoleAppData.Download_DealItemIndex]; if fStockDataAppData.ConsoleAppData.Download_DealItemCode = tmpDealItem.iCode then begin while nil = Result do begin Inc(fStockDataAppData.ConsoleAppData.Download_DealItemIndex); if Self.StockItemDB.RecordCount > fStockDataAppData.ConsoleAppData.Download_DealItemIndex then begin tmpDealItem := Self.StockItemDB.Items[fStockDataAppData.ConsoleAppData.Download_DealItemIndex]; if 0 = tmpDealItem.EndDealDate then begin Result := tmpDealItem; end; end else begin tmpDealItem := nil; Break; end; end; end; end; if nil <> Result then begin fStockDataAppData.ConsoleAppData.Download_DealItemCode := Result.iCode; end; end; procedure TStockDataApp.Console_NotifyDownloadData(AConsoleApp: PConsoleAppData); begin Console_NotifyDownloadData(AConsoleApp, Console_GetNextDownloadDealItem(AConsoleApp)); end; procedure TStockDataApp.Console_Notify_DownloadOK(AStockCode: integer); var tmpConsoleApp: PConsoleAppData; begin tmpConsoleApp := @fStockDataAppData.ConsoleAppData; Console_NotifyDownloadData(tmpConsoleApp, Console_GetNextDownloadDealItem(tmpConsoleApp)); end; function TStockDataApp.Console_CheckDownloaderProcess(AConsoleApp: PConsoleAppData): Boolean; var i: integer; tmpRetCode: DWORD; begin Result := IsWindow(AConsoleApp.Downloader_Process.Core.AppCmdWnd); if not Result then begin if 0 <> AConsoleApp.Downloader_Process.Core.ProcessHandle then begin if Windows.GetExitCodeProcess(AConsoleApp.Downloader_Process.Core.ProcessHandle, tmpRetCode) then begin if Windows.STILL_ACTIVE <> tmpRetCode then AConsoleApp.Downloader_Process.Core.ProcessId := 0; end; end else begin AConsoleApp.Downloader_Process.Core.ProcessId := 0; end; if 0 = AConsoleApp.Downloader_Process.Core.ProcessId then RunProcessA(@AConsoleApp.Downloader_Process, ParamStr(0)); if (0 = AConsoleApp.Downloader_Process.Core.ProcessHandle) or (INVALID_HANDLE_VALUE = AConsoleApp.Downloader_Process.Core.ProcessHandle) then exit; for i := 0 to 100 do begin if IsWindow(AConsoleApp.Downloader_Process.Core.AppCmdWnd) then Break; AConsoleApp.Downloader_Process.Core.AppCmdWnd := Windows.FindWindowA(AppCmdWndClassName_StockDataDownloader, nil); Sleep(10); end; end; Result := IsWindow(AConsoleApp.Downloader_Process.Core.AppCmdWnd); end; procedure TStockDataApp.RunStart_Console(AConsoleApp: PConsoleAppData); begin // run downloader process if Console_CheckDownloaderProcess(AConsoleApp) then begin AConsoleApp.Download_DealItemIndex := 0; Console_NotifyDownloadData(AConsoleApp); end; end; procedure TStockDataApp.Downloader_Download(ADownloaderApp: PDownloaderAppData; AStockCode: integer); var tmpStockItem: PRT_DealItem; begin tmpStockItem := Self.StockItemDB.FindItem(IntToStr(AStockCode)); if nil <> tmpStockItem then begin GetStockDataDay_163(Self, tmpStockItem, False, @ADownloaderApp.HttpClientSession); SDLog('', 'Downloader_Download:' + IntToStr(AStockCode)); if Downloader_CheckConsoleProcess(ADownloaderApp) then begin SDLog('', 'Downloader_Downloaded:' + IntToStr(AStockCode)); PostMessage(ADownloaderApp.Console_Process.Core.AppCmdWnd, WM_Downloader2Console_Command_DownloadOK, AStockCode, 0); end; end else begin SDLog('', 'Downloader_Download can not find stock:' + IntToStr(AStockCode)); end; end; function TStockDataApp.Downloader_CheckConsoleProcess(ADownloaderApp: PDownloaderAppData): Boolean; begin Result := IsWindow(ADownloaderApp.Console_Process.Core.AppCmdWnd); if not Result then begin ADownloaderApp.Console_Process.Core.AppCmdWnd := Windows.FindWindowA(AppCmdWndClassName_StockDataDownloader_Console, nil); Result := IsWindow(ADownloaderApp.Console_Process.Core.AppCmdWnd); end; end; procedure TStockDataApp.Downloader_Download(AStockCode: integer); begin Downloader_Download(@fStockDataAppData.DownloaderAppData, AStockCode); end; procedure TStockDataApp.RunStart_Downloader; begin end; (*// if 0 = tmpDealItem.FirstDealDate then begin tmpIsNeedSaveStockItemDB := true; end; tmpDealItem.IsDataChange := 0; if GetStockDataDay_163(Self, tmpDealItem, false, @tmpHttpClientSession) then begin Sleep(2000); end; if 0 <> tmpDealItem.IsDataChange then begin tmpIsNeedSaveStockItemDB := true; end; end; end; if tmpIsNeedSaveStockItemDB then begin SaveDBStockItem(Self, Self.StockItemDB); end; //*) procedure TStockDataApp.RunStart; begin case fStockDataAppData.RunMode of runMode_Console: RunStart_Console(@fStockDataAppData.ConsoleAppData); runMode_DataDownloader: RunStart_Downloader; end; end; procedure TStockDataApp.Run; begin if runMode_Console = fStockDataAppData.RunMode then begin Application.CreateForm(TfrmSDConsole, fStockDataAppData.ConsoleAppData.ConsoleForm); Application.Run; end; if runMode_DataDownloader = fStockDataAppData.RunMode then begin PostMessage(fBaseWinAppData.AppCmdWnd, WM_AppStart, 0, 0); RunAppMsgLoop; end; end; end.
unit vcmInternalInterfaces; { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmInternalInterfaces - } { Начат: 23.06.2003 18:04 } { $Id: vcmInternalInterfaces.pas,v 1.9 2015/03/18 11:14:07 lulin Exp $ } // $Log: vcmInternalInterfaces.pas,v $ // Revision 1.9 2015/03/18 11:14:07 lulin // - упорядочиваем генерацию зависимостей. // // Revision 1.8 2012/04/13 14:37:25 lulin // {RequestLink:237994598} // // Revision 1.7 2008/03/19 14:23:42 lulin // - cleanup. // // Revision 1.6 2008/02/01 15:14:33 lulin // - избавляемся от излишней универсальности списков. // // Revision 1.5 2007/04/04 09:10:28 lulin // - bug fix: не заполнялся контейнер в параметрах операции (CQ OIT5-24865). // // Revision 1.4 2004/06/02 10:20:38 law // - удален конструктор Tl3VList.MakeIUnknown - пользуйтесь _Tl3InterfaceList.Make. // // Revision 1.3 2003/09/26 15:23:58 law // - new behavior: начал делать слитие строковых ресурсов. // // Revision 1.2 2003/06/23 15:03:21 law // - change: свойство _IvcmContainer.GUID переехало в IvcmEntityForm.GUID - теперь каждая форма имеет свой идентификатор. // - remove interface: IvcmGUIDSetter. // - new param: конструктор _TvcmEntityForm.Make имее еще один параметр - aGUID - для восстановления идентификатора формы при операциях Back/Forward. // // Revision 1.1 2003/06/23 14:27:04 law // - new behavior: теперь контейнер восстанавливает свой GUID при операциях Back/Forward. // {$Include vcmDefine.inc } interface uses vcmInterfaces, vcmBase ; type IvcmForms = interface(IUnknown) ['{627B46F8-E5F3-41C3-9A17-808CE33C2598}'] // public methods procedure GetEntityForms(aList : TvcmClassList); {-} end;//IvcmForms implementation end.
unit drillformulas; {$mode objfpc}{$H+} interface uses Classes, SysUtils; // Диаметр скважины (Диаметр долота; Коэффициент кавернозности), м (мм) function DiameterWell(DiameterBit: real; K_kavern: real):real; // Площадь круга (Диаметре,м^2 (мм^2)), м^2 (мм^2) function PloshadKruga (Diameter: real):real; //Площадь кольцевого пространства (Диаметре1,м^2 (мм^2), Диаметре2,м^2 (мм^2)), м^2 (мм^2) function PloshadAnnular (Diameter1, Diameter2:real):real; //ГИДРАВЛИКА-------------------------------------------------------------------- //Динамическое напряжение сдвига промывочной жидкости (Плотность, кг/м3), Па function DinamNaprSdivga (Plotnost: real):real; //Пластическая вязкость промывочной жидкости (Плотность, кг/м3), Па*с function PlastVayzkost (Plotnost: real):real; //Число Хендсрема (He) function He (Plotnost, DinamNaprSdviga, Diameter, PlastVayzkost: real): real; //Кретическое число Рейнольдса (CRe) function CRe (He:real):real; //Число Рейнольдса (Re) function Re (Plotnost,SrednScorostGidkost,Diameter,PlastVayzkost:real):real; //Коэффициент гидравлических потерь (Лямбда). delta для труб 0,1; для кольцевого //пространства 0,107. K для труб 0,0003; для кольцевого пространства 0,003. function Lambda (delta, Diameter, Re, He, K :double):double; //Скорость потока, м/с (Расход, м^3/c; Площадь, м^2) function SrednScorostGidkost (Raschod, Ploshad:real):real; //Число Сенванана для случая ламинарного течения (Se) function Se (DinamNaprSdviga,Diameter,PlastVayzkost,SredScorostGidkost:real):real; //Перепад давления при ламинарном течении, Па function deltaPLamin (Sen,DinamNaprSdivga, L, Diameter:real):real; //Перепад давления при турбулентном режиме, Па (Лябда, Плотность, кг/м3; //Средняя скорость жидксти, м/с; Диаметер, м) function deltaPTurb (Lambda, Plotnost, SredScorostGidkost , Diameter,L:real):real; // Перепад давления на долоте, МПа (МЮ; Расход, м3; Площадь насадок, м2; Плотность, кг/м3) function deltaPdoloto (mu,Raschod, Ploshad, Plotnost: real):real; //------------------------------------------------------------------------------ implementation // Диаметр скважины (Диаметр долота; Коэффициент кавернозности), м (мм) function DiameterWell(DiameterBit: real; K_kavern: real):real; begin Result:= DiameterBit*sqrt(K_kavern); end; // Площадь круга (Диаметре,м^2 (мм^2)), м^2 (мм^2) function PloshadKruga (Diameter: real):real; begin Result:=Pi*exp(2*ln(Diameter))/4; end; //Площадь кольцевого пространства (Диаметре1,м^2 (мм^2), Диаметре2,м^2 (мм^2)), м^2 (мм^2) function PloshadAnnular (Diameter1, Diameter2:real):real; begin Result:=Pi*(exp(2*ln(Diameter1))-exp(2*ln(Diameter2)))/4 end; //ГИДРАВЛИКА //Динамическое напряжение сдвига промывочной жидкости (Плотность, кг/м3), Па function DinamNaprSdivga (Plotnost: real):real; begin Result:=8.5*Plotnost*0.001-7; end; //Пластическая вязкость промывочной жидкости (Плотность, кг/м3), Па*с function PlastVayzkost (Plotnost: real):real; begin Result:=33*Plotnost*0.001-22; end; //Число Хендсрема (He)(Плотность, Динамическое напряжение сдвига, Пластическая вязкость) function He (Plotnost, DinamNaprSdviga, Diameter, PlastVayzkost: real): real; begin Result:=(Plotnost*DinamNaprSdviga*exp(2*ln(Diameter)))/exp(2*ln(PlastVayzkost)); end; //Кретическое число Рейнольдса (CRe)(Число Хендсрема) function CRe (He:real):real; begin Result:=2100+7.3*exp(0.58*ln(He)); end; //Число Рейнольдса (Re)(Плтность, кг/м3; Средняя скорость жидкости, м/с; //Диаметер, м; Пластическая вязкость,Па*с) function Re (Plotnost,SrednScorostGidkost,Diameter,PlastVayzkost:real):real; begin Result:=Plotnost*SrednScorostGidkost*Diameter/PlastVayzkost; end; //Коэффициент гидравлических потерь (Лямбда). delta для труб 0,1; для кольцевого //пространства 0,107. K для труб 0,0003; для кольцевого пространства 0,003. // (дельта; диаметер, м; Re; He; K) function Lambda (delta, Diameter, Re, He, K :Double):double; begin Result:= delta * exp(0.25*ln(1.46*K/Diameter+100/Re+6.72*He/exp(4*ln(Re)))); end; //Скорость потока, м/с (Расход, м^3/c; Площадь, м^2); function SrednScorostGidkost (Raschod, Ploshad:real):real; begin Result:=Raschod/Ploshad; end; //Перепад давления при турбулентном режиме, Па (Лябда, Плотность, кг/м3; //Средняя скорость жидксти, м/с; Диаметер, м) function deltaPTurb (Lambda, Plotnost, SredScorostGidkost , Diameter,L:real):real; begin Result:= Lambda*Plotnost*exp(2*ln(SredScorostGidkost))*L/(2*Diameter); end; //Число Сенванана для случая ламинарного течения (Se) function Se (DinamNaprSdviga,Diameter,PlastVayzkost,SredScorostGidkost:real):real; begin Result:=(DinamNaprSdviga*Diameter)/(PlastVayzkost*SredScorostGidkost); end; //Перепад давления при ламинарном течении, Па function deltaPLamin (Sen,DinamNaprSdivga, L, Diameter:real):real; var beta:real; begin if Sen >= 10 then beta:= 1-(4*(sqrt(1.2+0.5*Sen)-1))/Sen else beta:=Sen/(12+1.3*Sen); Result:=4*DinamNaprSdivga*L/(beta*Diameter); end; // Перепад давления на долоте, МПа (МЮ; Расход, м3; Площадь насадок, м2; Плотность, кг/м3) function deltaPdoloto (mu,Raschod, Ploshad, Plotnost: real):real; var alfa: real; begin alfa:=1/(2*exp(2*ln(mu))*exp(2*ln(Ploshad))); Result:= alfa* exp(2*ln(Raschod))*Plotnost; end; end.
{!DOCTOPIC}{ PointTools } {!DOCREF} { @method: function se.ScalePoint(const Center, Pt:TPoint; Radius:Integer): TPoint; @desc: Scales the point based on the angle between `Center` and `Pt`. Radius = the amount to move the point: EG: [code=pascal] >> se.ScalePoint([0,0], [10,1], 100) point(X = 100, Y = 10) [/code] } function SimbaExt.ScalePoint(const Center, Pt:TPoint; Radius:Integer): TPoint; begin Result := exp_ScalePoint(Center, Pt, Radius); end; {!DOCREF} { @method: procedure se.SumTPA(TPA: TPointArray): TPoint; @desc: Sums the TPA and returns a TPoint with the sum of X, and Y } function SimbaExt.SumTPA(TPA: TPointArray): TPoint; begin Result := exp_SumTPA(TPA); end; {!DOCREF} { @method: procedure se.TPASplitAxis(TPA: TPointArray; var X:TIntArray; var Y:TIntArray); @desc: Separates the axis in the TPA, returning two TIntArrays, one for each axis } procedure SimbaExt.TPASplitAxis(TPA: TPointArray; var X:TIntArray; var Y:TIntArray); begin exp_TPASplitAxis(TPA, X,Y); end; {!DOCREF} { @method: procedure se.TPAJoinAxis(X:TIntArray; const Y:TIntArray; var TPA:TPointArray); @desc: Joins two axis to create a TPA, takes two TIntArrays, one for each axis } procedure SimbaExt.TPAJoinAxis(X:TIntArray; const Y:TIntArray; var TPA:TPointArray); begin exp_TPAJoinAxis(X,Y, TPA); end; {!DOCREF} { @method: procedure se.TPAFilter(var TPA: TPointArray; const Shape:TPointArray; const TopLeft:TPoint); @desc: Removes every point in `TPA` that is not in `Shape`. `TopLeft` is used to align to the arrays. } procedure SimbaExt.TPAFilter(var TPA: TPointArray; const Shape:TPointArray; const TopLeft:TPoint); begin exp_TPAFilter(TPA, Shape, TopLeft); end; {!DOCREF} { @method: procedure se.TPAFilterBounds(var TPA: TPointArray; x1,y1,x2,y2:Integer); @desc: Removes every point that is in the TPA that is NOT within the given bounds `x1,y1`, `x2,y2` [code=pascal] var TPA:TPointArray; begin TPA := [[0,0], [5,7], [10,10], [-5,-5], [15,15], [13,0]]; se.TPAFilterBounds(TPA,0,0,10,10); WriteLn( TPA ); end. [/code] Outputs: `>> [[0,0], [5,7], [10,10]]` } procedure SimbaExt.TPAFilterBounds(var TPA: TPointArray; x1,y1,x2,y2:Integer); begin exp_TPAFilterBounds(TPA, x1,y1,x2,y2); end; {!DOCREF} { @method: procedure se.ATPAFilter(var ATPA: T2DPointArray; MinLength, MinW, MinH, MaxW, MaxH: Integer; Align:Boolean=False); @desc: Filters the ATPA by going through each TPA, and checking if that TPA fits the given parameters. Align=True will align the TPA by the longest axis, making sure the width of the TPA is always the longest side, it givs you much more controll. } procedure SimbaExt.ATPAFilter(var ATPA: T2DPointArray; MinLength, MinW, MinH, MaxW, MaxH: Integer; Align:Boolean=False); begin exp_ATPAFilter(ATPA, MinLength, MinW, MinH, MaxW, MaxH, Align); end; {!DOCREF} { @method: function se.TPAExtremes(TPA:TPointArray): TPointArray; @desc: Returns the actuall points picked up when calling simbas GetTPABounds } function SimbaExt.TPAExtremes(TPA:TPointArray): TPointArray; begin Result := exp_TPAExtremes(TPA); end; {!DOCREF} { @method: function se.TPABBox(TPA:TPointArray): TPointArray; @desc: Returns the minimum bounding rectangle that can fit around the given TPA. Rectangle is represented by four TPoints. } function SimbaExt.TPABBox(TPA:TPointArray): TPointArray; begin Result := exp_TPABBox(TPA); end; {!DOCREF} { @method: function se.TPABoundingBox(TPA:TPointArray): TPointArray; @desc: Same as se.TPABBox } function SimbaExt.TPABoundingBox(TPA:TPointArray): TPointArray; begin Result := exp_TPABBox(TPA); end; {!DOCREF} { @method: function se.TPACenter(TPA: TPointArray; method: TCenterAlgo; Inside:Boolean): TPoint; @desc: returns the center of the TPA, the center if defined by the given `method` which is defined by TCenterAlgo. } function SimbaExt.TPACenter(TPA: TPointArray; method: TCenterAlgo; Inside:Boolean): TPoint; begin Result := exp_TPACenter(TPA, method, Inside); end; {!DOCREF} { @method: function se.GetAdjacent(var adj:TPointArray; n:TPoint; EightWay:Boolean); @desc: Returns the surronding 4, or 8 points around the given point `n` } procedure SimbaExt.GetAdjacent(var adj:TPointArray; n:TPoint; EightWay:Boolean); begin exp_GetAdjacent(adj, n, EightWay); end; {!DOCREF} { @method: function se.TPACircularity(TPA: TPointArray): Extended; @desc: Returns the circularity ratio '0.0 - 1.0' of the given TPA } function SimbaExt.TPACircularity(TPA: TPointArray): Extended; begin Result := exp_TPACircularity(TPA); end; {!DOCREF} { @method: function se.TPAConvexity(TPA: TPointArray): Extended; @desc: Returns the convexity ratio '0.0 - 1.0' of the given TPA } function SimbaExt.TPAConvexity(TPA: TPointArray): Extended; begin Result := exp_TPAConvexity(TPA); end; {!DOCREF} { @method: procedure se.ReverseTPA(var TPA: TPointArray); @desc: Reverses the TPA } procedure SimbaExt.ReverseTPA(var TPA: TPointArray); begin exp_ReverseTPA(TPA); end; {!DOCREF} { @method: procedure se.TPARemoveDupes(var TPA: TPointArray); @desc: Removes all the duplicates in the TPA } procedure SimbaExt.TPARemoveDupes(var TPA: TPointArray); begin exp_TPARemoveDupes(TPA); end; {!DOCREF} { @method: procedure se.LongestPolyVector(Poly:TPointArray; var A,B:TPoint); @desc: Returns the points of the longest side in the Polygon } procedure SimbaExt.LongestPolyVector(Poly:TPointArray; var A,B:TPoint); begin exp_LongestPolyVector(Poly, A,B); end; {!DOCREF} { @method: function se.InvertTPA(TPA:TPointArray): TPointArray; @desc: Inverts the TPA, meaning that all points within the bounds of the TPA that is NOT in the TPA will be returned } function SimbaExt.InvertTPA(TPA:TPointArray): TPointArray; begin Result := exp_InvertTPA(TPA); end; {!DOCREF} { @method: function se.RotateTPA(TPA: TPointArray; Radians: Extended): TPointArray; @desc: Rotates the TPA } function SimbaExt.RotateTPA(TPA: TPointArray; Radians: Extended): TPointArray; begin Result := exp_RotateTPA(TPA, Radians); end; {!DOCREF} { @method: function se.TPAPartition(TPA:TPointArray; BoxWidth, BoxHeight:Integer): T2DPointArray; @desc: Split the points in to partitions of BoxWidth, and BoxHeight. } function SimbaExt.TPAPartition(TPA:TPointArray; BoxWidth, BoxHeight:Integer): T2DPointArray; begin Result := exp_TPAPartition(TPA, BoxWidth, BoxHeight); end; {!DOCREF} { @method: function se.AlignTPA(TPA:TPointArray; method: TAlignAlgo; var Angle:Extended): TPointArray; @desc: Tries to align the TPA horizontally so that the longest side is faced downwards. } function SimbaExt.AlignTPA(TPA:TPointArray; method: TAlignAlgo; var Angle:Extended): TPointArray; begin Result := exp_AlignTPA(TPA, method, Angle); end; {!DOCREF} { @method: function se.CleanSortTPA(TPA: TPointArray): TPointArray; @desc: Sorts the TPA by row and at the same time removes all the duplicates. } function SimbaExt.CleanSortTPA(TPA: TPointArray): TPointArray; begin Result := exp_CleanSortTPA(TPA); end; {!DOCREF} { @method: function se.UniteTPA(TPA1, TPA2: TPointArray; RemoveDupes:Boolean): TPointArray; @desc: Combines two TPAs, if RemoveDups is 'True' then it will also remove all the duplicates } function SimbaExt.UniteTPA(TPA1, TPA2: TPointArray; RemoveDupes:Boolean): TPointArray; begin Result := exp_UniteTPA(TPA1, TPA2, RemoveDupes); end; {!DOCREF} { @method: procedure se.TPALine(var TPA:TPointArray; const P1:TPoint; const P2: TPoint); @desc: Fills `TPA` with a line between `P1`, and `P2`. } procedure SimbaExt.TPALine(var TPA:TPointArray; const P1:TPoint; const P2: TPoint); begin exp_TPALine(TPA, P1,P2); end; {!DOCREF} { @method: function se.TPACross(const center:TPoint; Radius:Int32): TPointArray; @desc: Returns a `TPA` filled with a cross of the radius `Radius`, so the diameter will be `radius*radius` } function SimbaExt.TPACross(const center:TPoint; Radius:Int32): TPointArray; var P1,P2:TPoint; begin P1 := Point(center.x-Radius, center.y); P2 := Point(center.x+Radius, center.y); exp_TPALine(Result, P1,P2); P1 := Point(center.x, center.y-Radius); P2 := Point(center.x, center.y+Radius); exp_TPALine(Result, P1,P2); end; {!DOCREF} { @method: function se.ConnectTPA(TPA:TPointArray): TPointArray; @desc: Given a polygon, or a ordered `TPA`, this function will draw a line between each point, and return that line. } function SimbaExt.ConnectTPA(TPA:TPointArray): TPointArray; begin Result := exp_ConnectTPA(TPA); end; {!DOCREF} { @method: function se.ConnectTPAEx(TPA:TPointArray; Tension:Extended): TPointArray; @desc: *might be bugged*, but it's supposed to connect/draw a line between each point in the TPA using splines, so it will be more "round". } function SimbaExt.ConnectTPAEx(TPA:TPointArray; Tension:Extended): TPointArray; begin Result := exp_ConnectTPAEx(TPA, Tension); end; {!DOCREF} { @method: function se.XagonPoints(const Center:TPoint; Sides:Integer; const Dir:TPoint): TPointArray; @desc: Returns the points which defines the corners of a polygon, it's defined by the params: `Sides`, and `Dir` (direction) } function SimbaExt.XagonPoints(const Center:TPoint; Sides:Integer; const Dir:TPoint): TPointArray; begin Result := exp_XagonPoints(Center, Sides, Dir); end; {!DOCREF} { @method: function se.TPAEllipse(const Center: TPoint; RadX,RadY:Integer; Filled:Boolean=False): TPointArray; @desc: Returns an ellipse wihch can be filled or not. } function SimbaExt.TPAEllipse(const Center: TPoint; RadX,RadY:Integer; Filled:Boolean=False): TPointArray; begin Result := exp_TPAEllipse(Center,RadX,RadY,Filled); end; {!DOCREF} { @method: function se.TPACircle(const Center: TPoint; Radius:Integer; Filled:Boolean=False): TPointArray; @desc: Returns a circle wihch can be filled or not. } function SimbaExt.TPACircle(const Center: TPoint; Radius:Integer; Filled:Boolean=False): TPointArray; begin Result := exp_TPACircle(Center,Radius,Filled); end; {!DOCREF} { @method: function se.TPASimplePoly(const Center:TPoint; Sides:Integer; const Dir:TPoint): TPointArray; @desc: Returns the outer lines of a polygon, it's defined by the params: `Sides`, and `Dir` (direction) } function SimbaExt.TPASimplePoly(const Center:TPoint; Sides:Integer; const Dir:TPoint): TPointArray; begin Result := exp_TPASimplePoly(Center, Sides, Dir); end; {!DOCREF} { @method: function se.ConvexHull(TPA:TPointArray): TPointArray; @desc: Returns the Convex Hull of the TPA [url]http://en.wikipedia.org/wiki/Convex_hull[/url] } function SimbaExt.ConvexHull(TPA:TPointArray): TPointArray; begin Result := exp_ConvexHull(TPA); end; {!DOCREF} { @method: function se.FloodFillTPAEx(TPA:TPointArray; const Start:TPoint; EightWay, KeepEdges:Boolean): TPointArray; @desc: Floodfills the TPA, allows you to keep the outer edges or not. } function SimbaExt.FloodFillTPAEx(TPA:TPointArray; const Start:TPoint; EightWay, KeepEdges:Boolean): TPointArray; begin Result := exp_FloodFillTPAEx(TPA, Start, EightWay, KeepEdges); end; {!DOCREF} { @method: function se.FloodFillTPA(TPA:TPointArray; const Start:TPoint; EightWay:Boolean): TPointArray; @desc: Floodfills the TPA. } function SimbaExt.FloodFillTPA(TPA:TPointArray; const Start:TPoint; EightWay:Boolean): TPointArray; begin Result := exp_FloodFillTPA(TPA,Start,EightWay); end; {!DOCREF} { @method: function se.TPAOutline(TPA:TPointArray): TPointArray; @desc: Returns the outline of the TPA, meaning all the points on the outer edge of the TPA } function SimbaExt.TPAOutline(TPA:TPointArray): TPointArray; begin Result := exp_TPAOutline(TPA); end; {!DOCREF} { @method: function se.TPABorder(TPA:TPointArray): TPointArray; @desc: Returns the border of the TPA, meaning all the points just outside the edge of the TPA } function SimbaExt.TPABorder(TPA:TPointArray): TPointArray; begin Result := exp_TPABorder(TPA); end; {!DOCREF} { @method: function se.FloodFillPolygon(Poly:TPointArray; EightWay:Boolean): TPointArray; @desc: Given a polygon, this function will fill all the points in that polygon and return them } function SimbaExt.FloodFillPolygon(Poly:TPointArray; EightWay:Boolean): TPointArray; begin Result := exp_FloodFillPolygon(Poly, EightWay); end; {!DOCREF} { @method: function se.ClusterTPAEx(TPA: TPointArray; Distx,Disty: Integer; EightWay:Boolean): T2DPointArray; @desc: This function is very similar to 'SplitTPAEx' and 'ClusterTPAEx' in Simba, only differance is the order of the result.[br] It groups the TPA in to many clusters by the given `DistX`, and `DistY` which represents the max distance (chebyshev) from each point to it's neighbor for the to create a group. But in almost all cases this function is faster then the "equal" simba functions. } function SimbaExt.ClusterTPAEx(TPA: TPointArray; Distx,Disty: Integer; EightWay:Boolean): T2DPointArray; begin if Length(TPA) > 0 then Result := exp_ClusterTPAEx(TPA,DistX,DistY, Eightway); end; {!DOCREF} { @method: function se.ClusterTPA(TPA: TPointArray; Distance: Integer; EightWay:Boolean): T2DPointArray; @desc: This function is very similar to 'SplitTPAEx' and 'ClusterTPAEx' in Simba, only differance is the order of the result, and that it onlytakse a single param.[br] It groups the TPA in to many clusters by the given `Distance` which represents the max distance (chebyshev) from each point to it's neighbor for the to create a group. But in almost all cases this function is faster then the "equal" simba functions.[br] [note]Do not mix this with simbas 'SplitTPA', this function clusters by using Chebyshev distance, and not Euclidean distance[/note] } function SimbaExt.ClusterTPA(TPA: TPointArray; Distance: Integer; EightWay:Boolean): T2DPointArray; begin if Length(TPA) > 0 then Result := exp_ClusterTPA(TPA,Distance, Eightway); end; {!DOCREF} { @method: function se.TPAEdges(TPA: TPointArray): TPointArray; @desc: Returns the edges of the TPA } function SimbaExt.TPAEdges(TPA: TPointArray): TPointArray; begin Result := exp_TPAEdges(TPA); end; {*=========================================================================================| | Spline.pas | |=========================================================================================*} {!DOCREF} { @method: function se.Spline(TPA:TPointArray; Tension:Extended; Connect:Boolean=False): TPointArray; @desc: [warning]Not working, yet[/warning] } function SimbaExt.Spline(TPA:TPointArray; Tension:Extended; Connect:Boolean=False): TPointArray; begin Result := exp_Spline(TPA, Tension, Connect); end; {*=========================================================================================| | Morphology.pas | |=========================================================================================*} {!DOCREF} { @method: function se.TPASkeleton(TPA:TPointArray; FMin,FMax:Integer): TPointArray; @desc: Returns the skeleton of the TPA, best FMin, and FMax is usually 2 and 6 } function SimbaExt.TPASkeleton(TPA:TPointArray; FMin,FMax:Integer): TPointArray; begin Result := exp_TPASkeleton(TPA,FMin,FMax); end; {!DOCREF} { @method: function se.TPAReduce(TPA:TPointArray; FMin,FMax, Iterations:Integer): TPointArray; @desc: Same as se.TPASkeleton but it allows you to decide ow much you want to reduce it by } function SimbaExt.TPAReduce(TPA:TPointArray; FMin,FMax, Iterations:Integer): TPointArray; begin Result := exp_TPAReduce(TPA,FMin,FMax,Iterations); end; {!DOCREF} { @method: function se.TPAExpand(TPA:TPointArray; Iterations:Integer): TPointArray; @desc: Expands the TPA by adding new layers out side the TPA } function SimbaExt.TPAExpand(TPA:TPointArray; Iterations:Integer): TPointArray; begin Result := exp_TPAExpand(TPA,Iterations); end;
unit FmItemsEditor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, GsDocument, Vcl.Menus, Vcl.StdActns, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.ComCtrls, Vcl.StdStyleActnCtrls, System.ImageList, Vcl.ImgList, StrUtils; type TItemsEditorForm = class(TForm) pnlMain: TPanel; btnOK: TButton; btnCancel: TButton; cbAttribute: TComboBox; Label1: TLabel; cbValue: TCheckBox; edtCommonValue: TEdit; cbDeleteAttrib: TCheckBox; pmValues: TPopupMenu; lblElementsCountText: TLabel; lblCount: TLabel; Panel1: TPanel; ActionToolBar1: TActionToolBar; ActionManager1: TActionManager; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; EditSelectAll1: TEditSelectAll; EditUndo1: TEditUndo; EditDelete1: TEditDelete; Label2: TLabel; lblCountMemo: TLabel; ImageList1: TImageList; Button1: TButton; cbAddText: TCheckBox; edtText: TEdit; rgAddTextMode: TRadioGroup; cbReplaceText: TCheckBox; edtOldValue: TLabeledEdit; edtNewValue: TLabeledEdit; cbShowValues: TCheckBox; cbMoveValue: TCheckBox; cbOtherAttrib: TComboBox; rgMoveValuesMode: TRadioGroup; cbLeftTrim: TCheckBox; edtLeftTrim: TEdit; cbRightTrim: TCheckBox; edtRightTrim: TEdit; memValues: TMemo; cbFirstPos: TCheckBox; procedure btnCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbAttributeChange(Sender: TObject); procedure memValuesChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure cbShowValuesClick(Sender: TObject); private FChapter: TGsAbstractContainer; procedure SetChapter(AChapter: TGsAbstractContainer); procedure UpdateView; procedure UpdateAttribValues; procedure WriteAttribs(DoUpdate: Boolean); function CheckMemoValue(Value: string): Boolean; procedure CommonSetValue(Value: string); procedure MoveValues; public FClass: TGsAbstractItemClass; property Chapter: TGsAbstractContainer read FChapter write SetChapter; end; const // TGsPriceElementAttributes = ( // paCode = 0, //код элемента // paCaption, //наименование // paUnits, //ед. измерения // paMass, //масса // paCargo, //класс груза // paPriceCE, //тек. сметная цена // paPriceCT, //тек. оптовая цена // paPriceBE, //баз. сметная цена // paPriceBT, //баз. оптовая цена // paWorkClass, //разряд рабочего // paComment, //примечание // paPriceCurrComment, //обоснование тек. цены // paPriceBaseComment, //обоснование баз. цены // paOKP //код ОКП // ); PriceAttributesNames: array [TGsPriceElementAttributes] of string = ('Код', 'Наименование', 'Измеритель', 'Масса', 'Класс груза', 'Текущая сметная цена', 'Текущая оптовая цена', 'Базисная сметная цена', 'Базисная оптовая цена', 'Разряд рабочего', 'Примечание', 'Обоснование текущей цены', 'Обоснование базисной цены', 'Код ОКП'); PriceFloatAttribs: set of TGsPriceElementAttributes = [paMass, paCargo, paPriceCE, paPriceBE, paPriceBT, paWorkClass]; IndexFloatAttribs: set of TGsIndexElementAttributes = [iaSMR, iaOZ, iaEM, iaZM, iaMT]; RowFloatAttribs: set of TGsBaseElementAttributes = [eaID, eaCargoClass, eaWorkCode]; // TGsIndexElementAttributes = ( // iaCode = 0, //код индекса // iaCaption, //наименование // iaSMR, //Индекс к СМР // iaOZ, //Индекс к ОЗП // iaEM, //Индекс к ЭМ // iaZM, //Индекс к ЗМ // iaMT, //Индекс к МАТ // iaSeparEm //Галочка - включать ли ЗМ в ЕМ // ); IndexAttributesNames: array [TGsIndexElementAttributes] of string = ('Код', 'Наименование', 'СМР', 'ОЗ', 'ЕМ', 'ЗМ', 'МТ', 'Разделять ЕМ'); // TGsBaseElementAttributes = ( // eaNumber, //Номер // eaCaption, //Наименование // eaUnits, //ед. изм // eaID, // eaComment, //Комментарий // eaCarGoClass, //Класс груза // eaWorkCode, //Код вида работ // eaOKP, //Код окп // eaWorkClass //Разряд рабочего // ); RowAttributesNames: array [TGsBaseElementAttributes] of string = ('Код', 'Наименование', 'Измеритель', 'Идентификатор', 'Комментарий', 'Класс груза', 'Код вида работ', 'Код ОКП', 'Разряд работ', 'Код 2001', 'Код ОКПД2'); var ItemsEditorForm: TItemsEditorForm; implementation {$R *.dfm} procedure TItemsEditorForm.btnCancelClick(Sender: TObject); begin Close; end; procedure TItemsEditorForm.btnOKClick(Sender: TObject); begin WriteAttribs(False); Close; end; procedure TItemsEditorForm.Button1Click(Sender: TObject); var I: Integer; begin WriteAttribs(True); for I := 0 to Self.ComponentCount - 1 do begin if (Components[I] is TCheckBox) and (Components[I] <> cbShowValues) then TCheckBox(Components[I]).Checked := False else end; end; procedure TItemsEditorForm.cbAttributeChange(Sender: TObject); begin UpdateAttribValues; end; procedure TItemsEditorForm.cbShowValuesClick(Sender: TObject); begin if not cbShowValues.Checked then UpdateAttribValues else memValues.Clear; end; function TItemsEditorForm.CheckMemoValue(Value: string): Boolean; begin Result := True; Value := Trim(Value); Value := StringReplace(Value, '.', ',', []); if (FClass = TGsIndexElement) and ((TGsIndexElementAttributes(cbAttribute.ItemIndex) in IndexFloatAttribs)) then Result := (StrToFloatDef(Value, -66666) <> -66666) else if (FClass = TGsPriceElement) and (TGsPriceElementAttributes(cbAttribute.ItemIndex) in PriceFloatAttribs) then Result := (StrToFloatDef(Value, -66666) <> -66666) else if (FClass = TGsRow) and (TGsBaseElementAttributes(cbAttribute.ItemIndex) in RowFloatAttribs) then Result := (StrToFloatDef(Value, -66666) <> -66666) else end; procedure TItemsEditorForm.CommonSetValue(Value: string); var L: TList; I: Integer; begin L := TList.Create; try FChapter.EnumItems(L, FClass, True); for I := 0 to L.Count - 1 do begin if (Value <> Unassigned) and not CheckMemoValue(VarToStr(Value)) then raise Exception.CreateFmt ('Значение %s для атрибута %s может быть только числом!', [Value, cbAttribute.Items[cbAttribute.ItemIndex]]); TGsAbstractItem(L[I]).Attributes[cbAttribute.ItemIndex] := VarToStr(Value); end; finally L.Free; end; end; procedure TItemsEditorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TItemsEditorForm.memValuesChange(Sender: TObject); begin lblCountMemo.Caption := IntToStr(memValues.Lines.Count); end; procedure TItemsEditorForm.MoveValues; var Item: TGsAbstractItem; begin if cbAttribute.ItemIndex = cbOtherAttrib.ItemIndex then Exit; for Item in FChapter do begin if Item is FClass then begin Item.Attributes[cbOtherAttrib.ItemIndex] := Item.Attributes[cbAttribute.ItemIndex]; if rgMoveValuesMode.ItemIndex = 1 then Item.Attributes[cbAttribute.ItemIndex] := Unassigned; end; end; end; procedure TItemsEditorForm.SetChapter(AChapter: TGsAbstractContainer); begin if FChapter <> AChapter then begin FChapter := AChapter; UpdateView; end; end; procedure TItemsEditorForm.UpdateAttribValues; var S: TStringList; L: TList; I: Integer; begin if cbShowValues.Checked then Exit; if cbAttribute.ItemIndex <> -1 then begin memValues.Clear; if FClass = nil then raise Exception.Create ('Критическая ошибка. Обратитесь к разработчику. Класс элемента не определен.'); S := TStringList.Create; try L := TList.Create; try FChapter.EnumItems(L, FClass, True); for I := 0 to L.Count - 1 do S.Add(VarToStr(TGsAbstractItem(L[I]).Attributes [cbAttribute.ItemIndex])); memValues.Lines.Assign(S); lblCount.Caption := IntToStr(L.Count); finally L.Free; end; finally S.Free; end; end; end; procedure TItemsEditorForm.UpdateView; var PriceAttrib: TGsPriceElementAttributes; IndexAttrib: TGsIndexElementAttributes; RowAttrib: TGsBaseElementAttributes; begin if FChapter = nil then Exit; memValues.Clear; cbAttribute.Clear; edtCommonValue.Text := ''; cbValue.Checked := False; FClass := nil; case FChapter.Document.DocumentType of dtPrice: begin FClass := TGsPriceElement; for PriceAttrib := Low(TGsPriceElementAttributes) to High(TGsPriceElementAttributes) do cbAttribute.Items.Add(PriceAttributesNames[PriceAttrib]); end; dtIndex: begin FClass := TGsIndexElement; for IndexAttrib := Low(TGsIndexElementAttributes) to High(TGsIndexElementAttributes) do cbAttribute.Items.Add(IndexAttributesNames[IndexAttrib]); end; dtBaseData: begin FClass := TGsRow; for RowAttrib := Low(TGsBaseElementAttributes) to High(TGsBaseElementAttributes) do cbAttribute.Items.Add(RowAttributesNames[RowAttrib]); end; end; if cbAttribute.Items.Count > 0 then begin cbAttribute.ItemIndex := 0; cbOtherAttrib.Items.Assign(cbAttribute.Items); cbOtherAttrib.ItemIndex := 0; UpdateAttribValues; end; end; procedure TItemsEditorForm.WriteAttribs(DoUpdate: Boolean); var I: Integer; L: TList; NewValue: string; Count: Integer; begin if cbMoveValue.Checked then begin MoveValues; if (rgMoveValuesMode.ItemIndex = 1) and (not cbShowValues.Checked) then memValues.Clear; Exit; end; if cbDeleteAttrib.Checked then begin CommonSetValue(Unassigned); memValues.Clear; cbDeleteAttrib.Checked := False; Exit; end; if cbValue.Checked then begin CommonSetValue(Trim(edtCommonValue.Text)); if DoUpdate then UpdateAttribValues; Exit; end; if lblCount.Caption <> lblCountMemo.Caption then raise Exception.Create ('Несоответсвие количества значений в поле количеству элементов в разделе.'); L := TList.Create; try FChapter.EnumItems(L, FClass, True); if cbShowValues.Checked then Count := L.Count else Count := memValues.Lines.Count; for I := 0 to Count - 1 do begin if cbShowValues.Checked then NewValue := TGsAbstractItem(L[I]).Attributes[cbAttribute.ItemIndex] else begin NewValue := Trim(memValues.Lines[I]); if cbLeftTrim.Checked then NewValue := RightStr(NewValue, Length(NewValue)-StrToInt(edtLeftTrim.Text)); if cbRightTrim.Checked then NewValue := LeftStr(NewValue, Length(NewValue)-StrToInt(edtRightTrim.Text)); end; if cbAddText.Checked then begin case rgAddTextMode.ItemIndex of 0: NewValue := edtText.Text + NewValue; 1: NewValue := NewValue + edtText.Text; end; end; if cbReplaceText.Checked then begin if cbFirstPos.Checked then NewValue := StringReplace(NewValue, edtOldValue.Text, edtNewValue.Text, []) else NewValue := StringReplace(NewValue, edtOldValue.Text, edtNewValue.Text, [rfReplaceAll]); end; if CheckMemoValue(NewValue) then TGsAbstractItem(L[I]).Attributes[cbAttribute.ItemIndex] := NewValue else raise Exception.CreateFmt ('Значение %s для атрибута %s может быть только числом!', [NewValue, cbAttribute.Items[cbAttribute.ItemIndex]]); end; finally L.Free; end; if DoUpdate then UpdateAttribValues; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type BinaryTest = public class (Test) private Data: Binary; DataBytes: array of Byte := [72, 101, 108, 108, 111]; //method AreEquals(Expected, Actual: array of Byte); public method Setup; override; method TestAssign; method TestClear; method TestReadRangeOfBytes; method TestReadBytes; method TestSubdata; method TestWriteBytes; method TestWriteData; method TestToByteArray; method TestLength; method TestFromArray; method TestFromBinary; method &Empty; end; implementation method BinaryTest.Setup; begin Data := new Binary(DataBytes); end; {method BinaryTest.AreEquals(Expected: array of Byte; Actual: array of Byte); begin Assert.CheckInt(length(Expected), length(Actual)); for i: Int32 := 0 to length(Expected) - 1 do Assert.CheckInt(Expected[i], Actual[i]); end;} method BinaryTest.TestAssign; begin var Value := new Binary; Value.Assign(Data); Assert.AreEqual(Value.Length, Data.Length); Value.Assign(nil); Assert.AreEqual(Value.Length, 0); end; method BinaryTest.TestClear; begin Data.Clear; Assert.AreEqual(Data.Length, 0); end; method BinaryTest.TestReadRangeOfBytes; begin var Expected: array of Byte := [101, 108, 108]; Assert.AreEqual(Data.Read(Range.MakeRange(1, 3)), Expected); Assert.AreEqual(Data.Read(Range.MakeRange(0, 5)), DataBytes); Assert.AreEqual(Data.Read(Range.MakeRange(5555, 0)), []); //empty //out of range Assert.Throws(->Data.Read(Range.MakeRange(32, 1))); Assert.Throws(->Data.Read(Range.MakeRange(0, 32))); end; method BinaryTest.TestReadBytes; begin var Expected: array of Byte := [72, 101, 108]; Assert.AreEqual(Data.Read(3), Expected); Assert.AreEqual(Data.Read(0), []); Assert.AreEqual(Data.Read(88888), DataBytes); //number of bytes copied is the Min(length, Data.Length) end; method BinaryTest.TestSubdata; begin var Expected: array of Byte := [101, 108, 108]; var Value := Data.Subdata(Range.MakeRange(1, 3)); Assert.IsNotNil(Value); Assert.AreEqual(Value.Length, 3); Assert.AreEqual(Value.ToArray, Expected); Assert.AreEqual(Data.Subdata(Range.MakeRange(0, Data.Length)).ToArray, DataBytes); Assert.AreEqual(Data.Subdata(Range.MakeRange(0,0)).ToArray, []); Assert.Throws(->Data.Subdata(Range.MakeRange(0, 50))); end; method BinaryTest.TestWriteBytes; begin Data.Write([], 0); //empty write Assert.AreEqual(Data.Length, 5); var BytesToWrite: array of Byte := [1, 2, 3]; Data.Write(BytesToWrite, 3); Assert.AreEqual(Data.Length, 8); Assert.AreEqual(Data.Read(Range.MakeRange(5, 3)), BytesToWrite); Assert.Throws(->Data.Write(nil, 0)); //null Assert.Throws(->Data.Write(BytesToWrite, 4)); //out of range end; method BinaryTest.TestWriteData; begin var Expected: Binary := new Binary([1,2,3]); Data.Write(Expected); Assert.AreEqual(Data.Length, 8); Assert.AreEqual(Data.Read(Range.MakeRange(5, 3)), Expected.ToArray); Expected := nil; Assert.Throws(->Data.Write(Expected)); Data.Write(new Binary([])); Assert.AreEqual(Data.Length, 8); end; method BinaryTest.TestToByteArray; begin Assert.AreEqual(Data.ToArray, DataBytes); Assert.AreEqual(new Binary([]).ToArray, []); end; method BinaryTest.TestLength; begin Assert.AreEqual(Data.Length, 5); Data.Clear; Assert.AreEqual(Data.Length, 0); Assert.AreEqual(new Binary([]).Length, 0); end; method BinaryTest.TestFromArray; begin var Value := new Binary(DataBytes); Assert.IsNotNil(Value); Assert.AreEqual(Value.Length, 5); Assert.AreEqual(Value.ToArray, DataBytes); //Assert.Throws(->new Binary(nil)); Assert.AreEqual(new Binary([]).Length, 0); end; method BinaryTest.TestFromBinary; begin var Value := new Binary(Data); Assert.IsNotNil(Value); Assert.AreEqual(Value.Length, 5); Assert.AreEqual(Value.ToArray, DataBytes); end; method BinaryTest.&Empty; begin var Value := new Binary; Assert.IsNotNil(Value); Assert.AreEqual(Value.Length, 0); end; end.
unit GX_ProofreaderAutoCorrectEntry; interface uses Classes, Controls, Forms, StdCtrls, GX_ProofreaderUtils, GX_BaseForm; type TfmProofreaderAutoCorrectEntry = class(TfmBaseForm) lblReplaceWhat: TLabel; edtReplaceWhat: TEdit; btnOK: TButton; btnCancel: TButton; lblLocation: TLabel; lblReplaceWith: TLabel; edtReplaceWith: TEdit; cbxLocation: TComboBox; procedure EditBoxChange(Sender: TObject); private procedure UpdateButtons; public class function Execute(var TypedString: string; var ReplaceWhere: TGXWhereReplace; var ReplaceWithString: string; Add: Boolean): Boolean; constructor Create(AOwner: TComponent); override; end; implementation uses SysUtils; {$R *.dfm} { TfmProofreaderDictionaryEntry } class function TfmProofreaderAutoCorrectEntry.Execute(var TypedString: string; var ReplaceWhere: TGXWhereReplace; var ReplaceWithString: string; Add: Boolean): Boolean; resourcestring SDlgCaptionAdd = 'Add AutoCorrect Entry'; SDlgCaptionEdit = 'Edit AutoCorrect Entry'; var Dialog: TfmProofreaderAutoCorrectEntry; begin Dialog := TfmProofreaderAutoCorrectEntry.Create(nil); try if Add then begin Dialog.Caption := SDlgCaptionAdd; Dialog.edtReplaceWhat.Text := ''; Dialog.cbxLocation.ItemIndex := Ord(wrAnywhere); Dialog.edtReplaceWith.Text := ''; end else begin Dialog.Caption := SDlgCaptionEdit; Dialog.edtReplaceWhat.Text := TypedString; Dialog.cbxLocation.ItemIndex := Ord(ReplaceWhere); Dialog.edtReplaceWith.Text := ReplaceWithString; end; Dialog.UpdateButtons; Result := Dialog.ShowModal = mrOk; if Result then begin Result := Trim(Dialog.edtReplaceWhat.Text) <> ''; if Result then begin TypedString := Dialog.edtReplaceWhat.Text; ReplaceWhere := TGXWhereReplace(Dialog.cbxLocation.ItemIndex); ReplaceWithString := Dialog.edtReplaceWith.Text; end; end; finally FreeAndNil(Dialog); end; end; constructor TfmProofreaderAutoCorrectEntry.Create(AOwner: TComponent); var WhereReplace: TGXWhereReplace; begin inherited Create(AOwner); for WhereReplace := Low(TGXWhereReplace) to High(TGXWhereReplace) do cbxLocation.Items.Add(GXWhereReplaceStrings[WhereReplace]); end; procedure TfmProofreaderAutoCorrectEntry.UpdateButtons; begin btnOK.Enabled := Trim(edtReplaceWhat.Text) <> ''; // Allow replacing with nothing end; procedure TfmProofreaderAutoCorrectEntry.EditBoxChange(Sender: TObject); begin UpdateButtons; end; end.
unit View.FrmPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Menus, FMX.Layouts; type TViewFrmPrincipal = class(TForm) RectBotao: TRectangle; BtnConfiguracao: TRectangle; Label1: TLabel; BtnProdutos: TRectangle; Label2: TLabel; Label3: TLabel; ToolBar: TToolBar; Label4: TLabel; LblUsuario: TLabel; RectClient: TRectangle; Image1: TImage; Image2: TImage; Image3: TImage; Layout1: TLayout; LytFrame: TLayout; StatusBar1: TStatusBar; procedure BtnConfiguracaoClick(Sender: TObject); procedure BtnProdutosClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure RectBotaoClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FUsuario: String; const cVersao: String = '3.0.0'; procedure FinalizaFrames; public { Public declarations } property Usuario: String read FUsuario write FUsuario; end; var ViewFrmPrincipal: TViewFrmPrincipal; implementation {$R *.fmx} uses View.CadProdutos, View.Configuracao, View.CadTVs, uDm; procedure TViewFrmPrincipal.BtnConfiguracaoClick(Sender: TObject); begin FinalizaFrames; if not Assigned(FrameConfiguracao) then FrameConfiguracao := TFrameConfiguracao.Create(Nil); FrameConfiguracao.Parent := LytFrame; FrameConfiguracao.BringToFront; end; procedure TViewFrmPrincipal.BtnProdutosClick(Sender: TObject); begin FinalizaFrames; if not Assigned(FrameCadProdutos) then FrameCadProdutos := TFrameCadProdutos.Create(Nil); FrameCadProdutos.Parent := LytFrame; FrameCadProdutos.BringToFront; end; procedure TViewFrmPrincipal.FinalizaFrames; begin if Assigned(FrameCadProdutos) then FrameCadProdutos.CloseCadProduto; if Assigned(FrameConfiguracao) then FrameConfiguracao.CloseConfiguracao; if Assigned(FrameCadTVs) then FrameCadTVs.CloseCadTVs; end; procedure TViewFrmPrincipal.FormDestroy(Sender: TObject); begin FinalizaFrames; Dm.DisposeOf; end; procedure TViewFrmPrincipal.FormShow(Sender: TObject); begin try Dm := TDm.Create(self); except Application.Terminate; end; LblUsuario.Text := 'Versão: ' + cVersao; end; procedure TViewFrmPrincipal.RectBotaoClick(Sender: TObject); begin FinalizaFrames; if not Assigned(FrameCadTVs) then FrameCadTVs := TFrameCadTVs.Create(Nil); FrameCadTVs.Parent := LytFrame; FrameCadTVs.BringToFront; end; end.
//////////////////////////////////////////////////////////////////////////////// // LibraryEvents.pas // MTB communication library // Library event definition // (c) Jan Horacek (jan.horacek@kmz-brno.cz), //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2015-2019 Jan Horacek Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } { DESCRIPTION: This file defines library callback events. Class TLibEvents holds library events. } unit LibraryEvents; interface type TStdNotifyEvent = procedure (Sender: TObject; data:Pointer); stdcall; TStdLogEvent = procedure (Sender: TObject; data:Pointer; logLevel:Integer; msg:PChar); stdcall; TStdErrorEvent = procedure (Sender: TObject; data:Pointer; errValue: word; errAddr: Cardinal; errMsg:PChar); stdcall; TStdModuleChangeEvent = procedure (Sender: TObject; data:Pointer; module: Cardinal); stdcall; TMyErrorEvent = record event: TStdErrorEvent; data: Pointer; end; TMyNotifyEvent = record event: TStdNotifyEvent; data: Pointer; end; TMyModuleChangeEvent = record event: TStdModuleChangeEvent; data:Pointer end; TMyLogEvent = record event: TStdLogEvent; data: Pointer; end; TLibEvents = record BeforeOpen:TMyNotifyEvent; AfterOpen:TMyNotifyEvent; BeforeClose:TMyNotifyEvent; AfterClose:TMyNotifyEvent; BeforeStart:TMyNotifyEvent; AfterStart:TMyNotifyEvent; BeforeStop:TMyNotifyEvent; AfterStop:TMyNotifyEvent; OnScanned:TMyNotifyEvent; OnError:TMyErrorEvent; OnLog:TMyLogEvent; OnInputChanged:TMyModuleChangeEvent; OnOutputChanged:TMyModuleChangeEvent; end; var LibEvents:TLibEvents; implementation end.
unit OXmlLng; { Author: Ondrej Pokorny, http://www.kluug.net All Rights Reserved. License: CPAL 1.0 or commercial Please see the /license.txt file for more information. } { OXmlLng.pas Language definitions for OXml library. } {$I OXml.inc} {$IFDEF O_DELPHI_XE4_UP} {$ZEROBASEDSTRINGS OFF} {$ENDIF} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$BOOLEVAL OFF} interface {$IFDEF O_DELPHI_5_DOWN} uses OWideSupp; {$ENDIF} var OXmlLng_InvalidCData: String = '"%s" is not a valid CData text.'; OXmlLng_InvalidText: String = '"%s" is not a valid text.'; OXmlLng_InvalidComment: String = '"%s" is not a valid comment text.'; OXmlLng_InvalidPITarget: String = '"%s" is not a valid processing instruction target.'; OXmlLng_InvalidPIContent: String = '"%s" is not a valid processing instruction content.'; OXmlLng_InvalidAttributeName: String = '"%s" is not a valid attribute name.'; OXmlLng_InvalidElementName: String = '"%s" is not a valid element name.'; OXmlLng_InvalidCharacterInText: String = 'The character "%s" cannot occur in text.'; OXmlLng_InvalidCharacterInAttribute: String = 'The character "%s" cannot occur in attribute.'; OXmlLng_InvalidStringInText: String = 'The string "%s" cannot occur in text.'; OXmlLng_InvalidCharacterInElement: String = 'The character "%s" cannot occur in element header.'; OXmlLng_InvalidAttributeStartChar: String = 'An attribute cannot start with the character "%s".'; OXmlLng_EqualSignMustFollowAttribute: String = 'Equal sign must follow the attribute "%s".'; OXmlLng_AttributeValueMustBeEnclosed: String = '"%s" attribute value must be enclosed in quotes.'; OXmlLng_DTDEntityValueMustBeEnclosed: String = '"%s" entity value must be enclosed in quotes.'; OXmlLng_TooManyElementsClosed: String = 'Too many elements closed.'; OXmlLng_UnclosedElementsInTheEnd: String = 'There are unclosed elements in the document end.'; OXmlLng_WrongElementClosed: String = 'Trying to close wrong element. Close="%s", open element="%s".'; OXmlLng_InvalidEntity: String = '"%s" is not a valid entity.'; OXmlLng_EntityNameNotFound: String = 'The entity name "%s" was not found.'; OXmlLng_ReadingAt: String = 'Reading at:'+sLineBreak+ 'Line: %d'+sLineBreak+ 'Char: %d'+sLineBreak+ 'XML token line: %d'+sLineBreak+ 'XML token char: %d'+sLineBreak+ 'Position in source stub: %d'+sLineBreak+ 'Source stub:'+sLineBreak+ '%s'; OXmlLng_XPathPredicateNotSupported: String = 'XPath predicate "%s" is not supported.'+sLineBreak+'XPath: %s'; OXmlLng_XPathPredicateNotValid: String = 'XPath predicate "%s" is not valid.'+sLineBreak+'XPath: %s'; OXmlLng_XPathNotSupported: String = 'XPath is not supported.'+sLineBreak+'XPath: %s'; OXmlLng_AppendFromDifferentDocument: String = 'You can''t append a node from a different XML document.'; OXmlLng_InsertFromDifferentDocument: String = 'You can''t insert a node from a different XML document.'; OXmlLng_ExchangeFromDifferentDocument: String = 'You can''t exchange nodes from different XML documents.'; OXmlLng_InsertEqualNodes: String = 'Node to insert and reference node can''t be equal.'; OXmlLng_ParentNodeCantBeNil: String = 'Parent node can''t be nil.'; OXmlLng_ParentNodeMustBeNil: String = 'Parent node must be nil.'; OXmlLng_NodeToDeleteNotAChild: String = 'You can''t delete a node that is not a child of current node.'; OXmlLng_NodeToInsertNotAChild: String = 'You can''t insert node before a node that is not a child of current node.'; OXmlLng_NodeMustBeDOMDocumentOrElement: String = 'Node must be a DOMDocument or an element.'; OXmlLng_CannotSetText: String = 'You can''t set the text property of this node. Use NodeValue instead.'; OXmlLng_ChildNotFound: String = 'Child not found.'; OXmlLng_NodeNotFound: String = 'Node not found.'; OXmlLng_ListIndexOutOfRange: String = 'List index out of range.'; OXmlLng_FeatureNotSupported: String = 'This feature is not supported.'; OXmlLng_CannotWriteAttributesWhenFinished: String = 'You can''t add an attribute %s="%s" when the element header ("%s") has been finished.'; OXmlLng_CannotSetIndentLevelAfterWrite: String = 'You can''t set the IndentLevel after something has been already written to the document.'; OXmlLng_NodeNameCannotBeEmpty: String = 'Node name cannot be empty.'; OXmlLng_XPathCannotBeEmpty: String = 'XPath cannot be empty.'; OXmlLng_PathCannotBeEmpty: String = 'Path cannot be empty.'; OXmlLng_CannotWriteToVirtualMemoryStream: String = 'You cannot write to a TVirtualMemoryStream.'; OXmlLng_CannotChangeRootNodeName: String = 'Cannot change RootNodeName after data has been written.'; OXmlLng_CannotChangeUseRootDataWritten: String = 'Cannot change UseRoot after data has been written.'; OXmlLng_CannotChangeUseRootDataRead: String = 'Cannot change UseRoot after data has been read.'; OXmlLng_WrongDeserializerSequence: String = 'TXMLDeserializer: wrong ReadObjectInfo/ReadObject call sequence.'; OXmlLng_RTTIInternalError: String = 'RTTI Internal Error'; OXmlLng_DeserializerNotSupportedListItemType: String = 'TXMLRTTIDeserializer: the type %s is not supported for TList<T> or array enumeration.'; OXmlLng_DeserializerRegisterClass: String = 'TXMLRTTIDeserializer: you have to register the class %s with the RegisterClass method.'; implementation end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. For more information, please refer to <http://unlicense.org>} { Source: https://forum.lazarus.freepascal.org/index.php?topic=20274.0 -i --install: register the daemon. This has no effect under unix. -u --uninstall: unregister the daemon. This has no effect under unix. -r --run: start the daemon on Unix. Windows does this normally itself. How to use on Windows: 1 Install the service from command line (run as admin): httpserver -i The service will auto start when Windows boots. 2 Start the service: With Services.msc: 'start' menu inside the windows services manager Or CMD as Admin : net start httpserver 3 Stop the service: With Services.msc: 'stop' menu inside the windows services manager Or CMD as Admin : net stop httpserver 4 Uninstall the service from command line (run as admin): httpserver -u Close services.msc before issuing pause/continue/stop commands above If service won't stop then: >sc.exe queryex <SERVICE_NAME> (note the PID number) >taskkill /f /pid <SERVICE_PID> >DemoDaemon -u For Internet access, open a port for the service on the router and firewall. } program httpserver; {$mode objfpc}{$H+} {$apptype console} {$define usecthreads} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Classes, SysUtils, EventLog, DaemonApp, httpserverunit; type { TDemoDaemon } TDemoDaemon = class(TCustomDaemon) private FThread: TServerThread; public function Install: boolean; override; function Start : Boolean; override; function UnInstall: boolean; override; procedure WriteLog(const ET: TEventType; const msg: string); end; { TDemoDaemon } function TDemoDaemon.Install: boolean; begin Result := inherited Install; WriteLog(etInfo, 'Daemon.Install: ' + BoolToStr(Result, True)); end; function TDemoDaemon.Start: Boolean; begin Result:=inherited Start; {init server params, then start server thread} WriteLog(etInfo, 'Daemon.Start: ' + BoolToStr(result,true)); FThread:=TServerThread.Create(True); with FThread do begin FLogFile:=ChangeFileExt(ParamStr(0), '.log'); FIP:='127.0.0.1'; FPort:=80; FHome:=ExtractFilePath(Application.ExeName)+'HOME\'; FreeOnTerminate:=true; Start; end; end; function TDemoDaemon.UnInstall: boolean; begin Result := inherited UnInstall; WriteLog(etInfo, 'Daemon.Uninstall: ' + BoolToStr(Result, True)); end; procedure TDemoDaemon.WriteLog(const ET: TEventType; const msg: string); var Log: TEventLog; begin {open, write, then close the log file to unlock it} Log:=TEventLog.Create(nil); try with Log do begin LogType := ltFile; DefaultEventType := etDebug; AppendContent := True; FileName := ChangeFileExt(ParamStr(0), '.log'); Active:=true; end; Log.Log(ET, msg); Log.Active:=False; //close log file to unlock it finally FreeAndNil(Log); end; end; { TDemoDaemonMapper } type TDemoDaemonMapper = class(TCustomDaemonMapper) constructor Create(AOwner: TComponent); override; end; constructor TDemoDaemonMapper.Create(AOwner: TComponent); begin inherited Create(AOwner); with DaemonDefs.Add as TDaemonDef do begin DaemonClassName := 'TDemoDaemon'; Name := 'HTTPServer'; DisplayName := 'HTTP Server Demo'; WinBindings.ServiceType := stWin32; WinBindings.StartType := stAuto; end; end; {$R *.res} begin RegisterDaemonClass(TDemoDaemon); RegisterDaemonMapper(TDemoDaemonMapper); with Application do begin Title := 'HTTP Server Demo'; Initialize; Run; end; end.
unit ScreenPrint; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Printers; type TScreenPrint = class(TComponent) private { Private declarations } protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } procedure Execute(Control: TControl); end; procedure Register; implementation constructor TScreenPrint.Create(AOwner: TComponent); begin inherited Create(AOwner); end;//end of contructor... destructor TScreenPrint.Destroy; begin inherited Destroy; end; procedure TScreenPrint.Execute(Control: TControl); var dc: HDC; isDcPalDevice : BOOL; MemDc :hdc; MemBitmap : hBitmap; OldMemBitmap : hBitmap; hDibHeader : Thandle; pDibHeader : pointer; hBits : Thandle; pBits : pointer; ScaleX : Double; ScaleY : Double; ppal : PLOGPALETTE; pal : hPalette; Oldpal : hPalette; i : integer; begin {Get the screen dc} dc := GetDc(0); {Create a compatible dc} MemDc := CreateCompatibleDc(dc); {create a bitmap} MemBitmap := CreateCompatibleBitmap(Dc, Control.width, Control.height); {select the bitmap into the dc} OldMemBitmap := SelectObject(MemDc, MemBitmap); {Lets prepare to try a fixup for broken video drivers} isDcPalDevice := false; if GetDeviceCaps(dc, RASTERCAPS) and RC_PALETTE = RC_PALETTE then begin GetMem(pPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY))); FillChar(pPal^, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)), #0); pPal^.palVersion := $300; pPal^.palNumEntries := GetSystemPaletteEntries(dc, 0, 256, pPal^.palPalEntry); if pPal^.PalNumEntries <> 0 then begin pal := CreatePalette(pPal^); oldPal := SelectPalette(MemDc, Pal, false); isDcPalDevice := true end else FreeMem(pPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY))); end; {copy from the screen to the memdc/bitmap} BitBlt(MemDc, 0, 0, control.width, control.height, Dc, control.left, control.top, SrcCopy); if isDcPalDevice = true then begin SelectPalette(MemDc, OldPal, false); DeleteObject(Pal); end; {unselect the bitmap} SelectObject(MemDc, OldMemBitmap); {delete the memory dc} DeleteDc(MemDc); {Allocate memory for a DIB structure} hDibHeader := GlobalAlloc(GHND, sizeof(TBITMAPINFO) + (sizeof(TRGBQUAD) * 256)); {get a pointer to the alloced memory} pDibHeader := GlobalLock(hDibHeader); {fill in the dib structure with info on the way we want the DIB} FillChar(pDibHeader^, sizeof(TBITMAPINFO) + (sizeof(TRGBQUAD) * 256), #0); PBITMAPINFOHEADER(pDibHeader)^.biSize := sizeof(TBITMAPINFOHEADER); PBITMAPINFOHEADER(pDibHeader)^.biPlanes := 1; PBITMAPINFOHEADER(pDibHeader)^.biBitCount := 8; PBITMAPINFOHEADER(pDibHeader)^.biWidth := control.width; PBITMAPINFOHEADER(pDibHeader)^.biHeight := control.height; PBITMAPINFOHEADER(pDibHeader)^.biCompression := BI_RGB; {find out how much memory for the bits} GetDIBits(dc, MemBitmap, 0, control.height, nil, TBitmapInfo(pDibHeader^), DIB_RGB_COLORS); {Alloc memory for the bits} hBits := GlobalAlloc(GHND, PBitmapInfoHeader(pDibHeader)^.BiSizeImage); {Get a pointer to the bits} pBits := GlobalLock(hBits); {Call fn again, but this time give us the bits!} GetDIBits(dc, MemBitmap, 0, control.height, pBits, PBitmapInfo(pDibHeader)^, DIB_RGB_COLORS); {Lets try a fixup for broken video drivers} if isDcPalDevice = true then begin for i := 0 to (pPal^.PalNumEntries - 1) do begin PBitmapInfo(pDibHeader)^.bmiColors[i].rgbRed := pPal^.palPalEntry[i].peRed; PBitmapInfo(pDibHeader)^.bmiColors[i].rgbGreen := pPal^.palPalEntry[i].peGreen; PBitmapInfo(pDibHeader)^.bmiColors[i].rgbBlue := pPal^.palPalEntry[i].peBlue; end; FreeMem(pPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY))); end; {Release the screen dc} ReleaseDc(0, dc); {Delete the bitmap} DeleteObject(MemBitmap); {Start print job} Printer.BeginDoc; {Scale print size} if Printer.PageWidth < Printer.PageHeight then begin ScaleX := Printer.PageWidth; ScaleY := Control.Height * (Printer.PageWidth / Control.Width); end else begin ScaleX := Control.Width * (Printer.PageHeight / Control.Height); ScaleY := Printer.PageHeight; end; {Just incase the printer drver is a palette device} isDcPalDevice := false; if GetDeviceCaps(Printer.Canvas.Handle, RASTERCAPS) and RC_PALETTE = RC_PALETTE then begin {Create palette from dib} GetMem(pPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY))); FillChar(pPal^, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)), #0); pPal^.palVersion := $300; pPal^.palNumEntries := 256; for i := 0 to (pPal^.PalNumEntries - 1) do begin pPal^.palPalEntry[i].peRed := PBitmapInfo(pDibHeader)^.bmiColors[i].rgbRed; pPal^.palPalEntry[i].peGreen := PBitmapInfo(pDibHeader)^.bmiColors[i].rgbGreen; pPal^.palPalEntry[i].peBlue := PBitmapInfo(pDibHeader)^.bmiColors[i].rgbBlue; end; pal := CreatePalette(pPal^); FreeMem(pPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY))); oldPal := SelectPalette(Printer.Canvas.Handle, Pal, false); isDcPalDevice := true end; {send the bits to the printer} StretchDiBits(Printer.Canvas.Handle, 0, 0, Round(scaleX), Round(scaleY), 0, 0, Control.Width, Control.Height, pBits, PBitmapInfo(pDibHeader)^, DIB_RGB_COLORS, SRCCOPY); {Just incase you printer drver is a palette device} if isDcPalDevice = true then begin SelectPalette(Printer.Canvas.Handle, oldPal, false); DeleteObject(Pal); end; {Clean up allocated memory} GlobalUnlock(hBits); GlobalFree(hBits); GlobalUnlock(hDibHeader); GlobalFree(hDibHeader); {End the print job} Printer.EndDoc; end; procedure Register; begin RegisterComponents('FFS Common', [TScreenPrint]); end; end.
unit qcndate; interface { 本单元算法数据使用自早期 UCDOS 的农历数据,本来想使用寿星万年历的数据,但太复杂 所以暂时舍弃。 本单元Delphi接口由swish设计实现,版权归swish所有。 更新日志 2015.2.26 ========== * 修正了在2007下的编译警告(感谢麦子仲肥) } uses System.Classes, System.SysUtils; type {$HPPEMIT '#pragma link "qcndate"'} TCnDate = record case Integer of 1: (Year: Word; Month: Shortint; Day: Byte); // 16位年,8位月,8位日 2: (Value: Integer); // 32位的整数值 end; const CnDayNames: array [1 .. 30] of String = ('初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'); CnMonthNames: array [1 .. 12] of String = ('正月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '冬月', '腊月'); CnSkyNames: array [1 .. 10] of String = ('甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'); CnEarthNames: array [1 .. 12] of String = ('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'); CnAnimals: array [1 .. 12] of String = ('鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'); CnSolarTerms: array [0 .. 24] of String = ('', '小寒', '大寒', '立春', '雨水', '惊蛰', '春分', '清明', '谷雨', '立夏', '小满', '芒种', '夏至', '小暑', '大暑', '立秋', '处暑', '白露', '秋分', '寒露', '霜降', '立冬', '小雪', '大雪', '冬至'); CnWeekNames: array [1 .. 7] of String = ('一', '二', '三', '四', '五', '六', '日'); /// <summary> /// 将指定的农历年月日编码为一个TCnDate变量 /// </summary> /// <params> /// <param name="Y">农历年份,取值范围为1901-2050 </param> /// <param name="M">农历月份,负数代表是闰月</param> /// <param name="D">农历日数,取值范围为1-30</param> /// </params> /// <returns>返回编码后日期</returns> function CnDate(Y: Word; M, D: Shortint): TCnDate; inline; /// <summary>将指定的日期转换为农历日期</summary> /// <params> /// <param name=“ADate">阳历日期</param> /// </params> /// <returns>返回转换后的日期</returns> function ToCnDate(ADate: TDateTime): TCnDate; overload; /// <summary>将指定的日期转换为农历日期</summary> /// <params> /// <param name=“yyyy">阳历年份</param> /// <param name="mm">阳历月份</param> /// <param name="dd">阳历日</param> /// </params> /// <returns>返回转换后的日期</returns> function ToCnDate(yyyy, mm, dd: Word): TCnDate; overload; /// <summary>将指定农历日期转换为阳历日期</summary> /// <params> /// <param name="ADate">阴历日期</param> /// </params> /// <returns>返回转换后的阳历日期</returns> function ToEnDate(ADate: TCnDate): TDateTime; /// <summary>获取指定阳历日期的农历年份</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回指定阳历日期的农历年份</returns> function CnYearOf(ADate: TDateTime): Smallint; overload; /// <summary>获取指定农历日期的年份的天干地支名称</summary> /// <params> /// <param name="ADate">阴历日期</param> /// </params> /// <returns>返回天干地支名称,如"甲午"</reutrns> function CnYearName(ADate: TCnDate): String; overload; /// <summary>获取指定阳历日期对应的农历年份的天干地支名称</summary> /// <params> /// <param name="ADate">阴历日期</param> /// </params> /// <returns>返回天干地支名称,如"甲午"</reutrns> function CnYearName(ADate: TDateTime): String; overload; /// <summary>获取指定阳历日期对应的月份数</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回月份数,取值范围为1-12,-12~-1,负数代表是闰月</returns> function CnMonthOf(ADate: TDateTime): Shortint; overload; /// <summary>获取指定农历日期对应的月份名称</summary> /// <params> /// <param name="ADate">农历日期</param> /// </params> /// <returns>返回农历月份名称,如“腊月”</param> function CnMonthName(ADate: TCnDate): String; overload; /// <summary>获取指定阳历日期对应农历日期对应的月份名称</summary> /// <params> /// <param name="ADate">农历日期</param> /// </params> /// <returns>返回农历月份名称,如“腊月”</param> function CnMonthName(ADate: TDateTime): String; overload; /// <summary>获取指定农历年月的天数</summary> /// <params> /// <param name="Y">农历年份</param> /// <param name="M">农历月份,负数代表闰月</param> /// </params> /// <returns>返回指定农历年月的天数</returns> function CnMonthDays(Y: Word; M: Shortint): Byte; /// <summary>获取指定阳历日期的农历日</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回指定的农历日</returns> function CnDayOf(ADate: TDateTime): Shortint; overload; /// <summary>获取指定农历日期的中文名称</summary> /// <params> /// <param name="ADate">农历日期</param> /// </params> /// <returns>返回指定日期的日的中文名称</returns> function CnDayName(ADate: TCnDate): String; overload; /// <summary>获取指定阳历日期对应农历日期日的中文名称</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回指定日期的日的中文名称</returns> function CnDayName(ADate: TDateTime): String; overload; /// <summary>获取指定小时的时刻名称</summary> /// <params> /// <param name="AHour">小时数,取值范围0-23</param> /// </params> /// <returns>返回中文的小时对应的时刻名称(子、丑等)</returns> function CnHourName(AHour: Byte): String; overload; /// <summary>获取指定的农历日期的属相名称</summary> /// <params> /// <param name="ADate">农历日期</param> /// </params> /// <returns>返回指定的农历年份对应的属相名称</returns> function CnAnimalOf(ADate: TCnDate): String; overload; /// <summary>获取指定的阳历日期的属相名称</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回指定的阳历年份对应的属相名称</returns> function CnAnimalOf(ADate: TDateTime): String; overload; /// <summary>获取指定年份相应节气对应的阳历日期</summary> /// <params> /// <param name="AYear">农历年份</param> /// <param name="AName">节气名称</param> /// </params> /// <returns>返回对应的阳历日期</returns> function DateOfCnSolarTerm(AYear: Smallint; AName: String) : TDateTime; overload; /// <summary>获取指定阳历日期对应的节气序号</summary> /// <params> /// <param name="AYear">阳历年份</param> /// <param name="AMonth">阳历月份</param> /// <param name="ADay">阳历日</param> /// </params> /// <returns>返回节气序列,如果不是任何节气,返回0</returns> function CnSolarTerm(AYear, AMonth, ADay: Word): Shortint; overload; /// <summary>获取指定农历日期对应的节气序号</summary> /// <params> /// <param name="AYear">农历年份</param> /// <param name="AMonth">农历月份</param> /// <param name="ADay">农历日</param> /// </params> /// <returns>返回节气序列,如果不是任何节气,返回0</returns> function CnSolarTerm(ADate: TCnDate): Shortint; overload; /// <summary>获取指定阳历日期对应的节气序号</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回节气序列,如果不是任何节气,返回0</returns> function CnSolarTerm(ADate: TDateTime): Shortint; overload; /// <summary>获取指定农历日期对应的节气名称</summary> /// <params> /// <param name="ADate">农历日期</param> /// </params> /// <returns>返回节气名称,如果不属于任何节气,返回空字符串</returns> function CnSolarTermName(ADate: TCnDate): String; overload; /// <summary>获取指定阳历日期对应的节气名称</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回节气名称,如果不属于任何节气,返回空字符串</returns> function CnSolarTermName(ADate: TDateTime): String; overload; /// <summary>获取指定日期在相应的农历年份中的周次</summary> /// <params> /// <param name="ADate">阳历日期</param> /// </params> /// <returns>返回周次</returns> function CnWeeksInYear(const ADate: TDateTime): Byte; /// <summary>增加指定的农历的年数</summary> /// <params> /// <param name="ADate">当前日期</param> /// <param name="ADelta">增量</param> /// </params> /// <returns>返回增加或减少(负增量)的年数后的农历日期</returns> function CnIncYear(ADate: TCnDate; ADelta: Integer = 1): TCnDate; /// <summary>增加指定的农历的月数</summary> /// <params> /// <param name="ADate">当前日期</param> /// <param name="ADelta">增量</param> /// </params> /// <returns>返回增加或减少(负增量)的月数后的农历日期</returns> function CnIncMonth(ADate: TCnDate; ADelta: Integer = 1): TCnDate; /// <summary>增加指定的农历的天数</summary> /// <params> /// <param name="ADate">当前日期</param> /// <param name="ADelta">增量</param> /// </params> /// <returns>返回增加或减少(负增量)的月数后的农历日期</returns> function CnIncDay(ADate: TCnDate; ADelta: Integer = 1): TCnDate; implementation uses math, dateutils; const // 农历月份数据,每年4字节,从1901年开始,共150年 // 数据来源:UCDOS 6.0 UCT.COM // 分析整理:Copyright (c) 1996-1998, Randolph // 数据解析: // 如果第一字节的bit7为1,则该年1月1日位于农历12月,否则位于11月 // 第一字节去除bit7为该年1月1日的农历日期 // 第二字节 第三字节 // bit: 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 // 农历月份:16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 // 农历月份指的是从该年1月1日的农历月份算起的顺序号 // 农历月份对应的bit为1则该月为30日,否则为29日 // 第四字节为闰月月份 // BaseDate='2000/02/04';//2000立春 BaseAnimalDate = 1972; // 1972年支为子(是鼠年) BaseSkyStemDate = 1974; // 1974年干为甲 START_YEAR = 1901; END_YEAR = 2050; gLunarHolDay: array [0 .. 1799] of Byte = ($96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1901 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, // 1902 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, // 1903 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, // 1904 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1905 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, // 1906 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, // 1907 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1908 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1909 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, // 1910 $96, $A5, $87, $96, $87, $87, $79, $69, $69, $69, $78, $78, // 1911 $86, $A5, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1912 $95, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1913 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, // 1914 $96, $A5, $97, $96, $97, $87, $79, $79, $69, $69, $78, $78, // 1915 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1916 $95, $B4, $96, $A6, $96, $97, $78, $79, $78, $69, $78, $87, // 1917 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $77, // 1918 $96, $A5, $97, $96, $97, $87, $79, $79, $69, $69, $78, $78, // 1919 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1920 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $87, // 1921 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $77, // 1922 $96, $A4, $96, $96, $97, $87, $79, $79, $69, $69, $78, $78, // 1923 $96, $A5, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1924 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $87, // 1925 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1926 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, // 1927 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1928 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1929 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1930 $96, $A4, $96, $96, $97, $87, $79, $79, $79, $69, $78, $78, // 1931 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1932 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1933 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1934 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, // 1935 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1936 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1937 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1938 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, // 1939 $96, $A5, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1940 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1941 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1942 $96, $A4, $96, $96, $97, $97, $79, $79, $79, $69, $78, $78, // 1943 $96, $A5, $96, $A5, $A6, $96, $88, $78, $78, $78, $87, $87, // 1944 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1945 $95, $B4, $96, $A6, $97, $97, $78, $79, $78, $69, $78, $77, // 1946 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, // 1947 $96, $A5, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 1948 $A5, $B4, $96, $A5, $96, $97, $88, $79, $78, $79, $77, $87, // 1949 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $77, // 1950 $96, $B4, $96, $A6, $97, $97, $79, $79, $79, $69, $78, $78, // 1951 $96, $A5, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 1952 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1953 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $68, $78, $87, // 1954 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1955 $96, $A5, $A5, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 1956 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1957 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1958 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1959 $96, $A4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, // 1960 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1961 $96, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1962 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1963 $96, $A4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, // 1964 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1965 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1966 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1967 $96, $A4, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 1968 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1969 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1970 $96, $B4, $96, $A6, $97, $97, $78, $79, $79, $69, $78, $77, // 1971 $96, $A4, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 1972 $A5, $B5, $96, $A5, $A6, $96, $88, $78, $78, $78, $87, $87, // 1973 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1974 $96, $B4, $96, $A6, $97, $97, $78, $79, $78, $69, $78, $77, // 1975 $96, $A4, $A5, $B5, $A6, $A6, $88, $89, $88, $78, $87, $87, // 1976 $A5, $B4, $96, $A5, $96, $96, $88, $88, $78, $78, $87, $87, // 1977 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, // 1978 $96, $B4, $96, $A6, $96, $97, $78, $79, $78, $69, $78, $77, // 1979 $96, $A4, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 1980 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $77, $87, // 1981 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1982 $95, $B4, $96, $A5, $96, $97, $78, $79, $78, $69, $78, $77, // 1983 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, // 1984 $A5, $B4, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 1985 $A5, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 1986 $95, $B4, $96, $A5, $96, $97, $88, $79, $78, $69, $78, $87, // 1987 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 1988 $A5, $B4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, // 1989 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, // 1990 $95, $B4, $96, $A5, $86, $97, $88, $78, $78, $69, $78, $87, // 1991 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 1992 $A5, $B3, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, // 1993 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1994 $95, $B4, $96, $A5, $96, $97, $88, $76, $78, $69, $78, $87, // 1995 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 1996 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 1997 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 1998 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 1999 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2000 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2001 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 2002 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 2003 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2004 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2005 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2006 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $69, $78, $87, // 2007 $96, $B4, $A5, $B5, $A6, $A6, $87, $88, $87, $78, $87, $86, // 2008 $A5, $B3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2009 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2010 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $78, $87, // 2011 $96, $B4, $A5, $B5, $A5, $A6, $87, $88, $87, $78, $87, $86, // 2012 $A5, $B3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, // 2013 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2014 $95, $B4, $96, $A5, $96, $97, $88, $78, $78, $79, $77, $87, // 2015 $95, $B4, $A5, $B4, $A5, $A6, $87, $88, $87, $78, $87, $86, // 2016 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, // 2017 $A5, $B4, $A6, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2018 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, // 2019 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $86, // 2020 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2021 $A5, $B4, $A5, $A5, $A6, $96, $88, $88, $88, $78, $87, $87, // 2022 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $79, $77, $87, // 2023 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, // 2024 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2025 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2026 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 2027 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, // 2028 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2029 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2030 $A5, $B4, $96, $A5, $96, $96, $88, $78, $78, $78, $87, $87, // 2031 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, // 2032 $A5, $C3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $86, // 2033 $A5, $B3, $A5, $A5, $A6, $A6, $88, $78, $88, $78, $87, $87, // 2034 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2035 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, // 2036 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $86, // 2037 $A5, $B3, $A5, $A5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2038 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2039 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $78, $87, $96, // 2040 $A5, $C3, $A5, $B5, $A5, $A6, $87, $88, $87, $78, $87, $86, // 2041 $A5, $B3, $A5, $B5, $A6, $A6, $88, $88, $88, $78, $87, $87, // 2042 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2043 $95, $B4, $A5, $B4, $A5, $A6, $97, $87, $87, $88, $87, $96, // 2044 $A5, $C3, $A5, $B4, $A5, $A6, $87, $88, $87, $78, $87, $86, // 2045 $A5, $B3, $A5, $B5, $A6, $A6, $87, $88, $88, $78, $87, $87, // 2046 $A5, $B4, $96, $A5, $A6, $96, $88, $88, $78, $78, $87, $87, // 2047 $95, $B4, $A5, $B4, $A5, $A5, $97, $87, $87, $88, $86, $96, // 2048 $A4, $C3, $A5, $A5, $A5, $A6, $97, $87, $87, $78, $87, $86, // 2049 $A5, $C3, $A5, $B5, $A6, $A6, $87, $88, $78, $78, $87, $87); // 2050 CnData: array [0 .. 599] of Byte = ($0B, $52, $BA, $00, $16, $A9, $5D, $00, $83, $A9, $37, $05, $0E, $74, $9B, $00, $1A, $B6, $55, $00, $87, $B5, $55, $04, $11, $55, $AA, $00, $1C, $A6, $B5, $00, $8A, $A5, $75, $02, $14, $52, $BA, $00, $81, $52, $6E, $06, $0D, $E9, $37, $00, $18, $74, $97, $00, $86, $EA, $96, $05, $10, $6D, $55, $00, $1A, $35, $AA, $00, $88, $4B, $6A, $02, $13, $A5, $6D, $00, $1E, $D2, $6E, $07, $0B, $D2, $5E, $00, $17, $E9, $2E, $00, $84, $D9, $2D, $05, $0F, $DA, $95, $00, $19, $5B, $52, $00, $87, $56, $D4, $04, $11, $4A, $DA, $00, $1C, $A5, $5D, $00, $89, $A4, $BD, $02, $15, $D2, $5D, $00, $82, $B2, $5B, $06, $0D, $B5, $2B, $00, $18, $BA, $95, $00, $86, $B6, $A5, $05, $10, $56, $B4, $00, $1A, $4A, $DA, $00, $87, $49, $BA, $03, $13, $A4, $BB, $00, $1E, $B2, $5B, $07, $0B, $72, $57, $00, $16, $75, $2B, $00, $84, $6D, $2A, $06, $0F, $AD, $55, $00, $19, $55, $AA, $00, $86, $55, $6C, $04, $12, $C9, $76, $00, $1C, $64, $B7, $00, $8A, $E4, $AE, $02, $15, $EA, $56, $00, $83, $DA, $55, $07, $0D, $5B, $2A, $00, $18, $AD, $55, $00, $85, $AA, $D5, $05, $10, $53, $6A, $00, $1B, $A9, $6D, $00, $88, $A9, $5D, $03, $13, $D4, $AE, $00, $81, $D4, $AB, $08, $0C, $BA, $55, $00, $16, $5A, $AA, $00, $83, $56, $AA, $06, $0F, $AA, $D5, $00, $19, $52, $DA, $00, $86, $52, $BA, $04, $11, $A9, $5D, $00, $1D, $D4, $9B, $00, $8A, $74, $9B, $03, $15, $B6, $55, $00, $82, $AD, $55, $07, $0D, $55, $AA, $00, $18, $A5, $B5, $00, $85, $A5, $75, $05, $0F, $52, $B6, $00, $1B, $69, $37, $00, $89, $E9, $37, $04, $13, $74, $97, $00, $81, $EA, $96, $08, $0C, $6D, $52, $00, $16, $2D, $AA, $00, $83, $4B, $6A, $06, $0E, $A5, $6D, $00, $1A, $D2, $6E, $00, $87, $D2, $5E, $04, $12, $E9, $2E, $00, $1D, $EC, $96, $0A, $0B, $DA, $95, $00, $15, $5B, $52, $00, $82, $56, $D2, $06, $0C, $2A, $DA, $00, $18, $A4, $DD, $00, $85, $A4, $BD, $05, $10, $D2, $5D, $00, $1B, $D9, $2D, $00, $89, $B5, $2B, $03, $14, $BA, $95, $00, $81, $B5, $95, $08, $0B, $56, $B2, $00, $16, $2A, $DA, $00, $83, $49, $B6, $05, $0E, $64, $BB, $00, $19, $B2, $5B, $00, $87, $6A, $57, $04, $12, $75, $2B, $00, $1D, $B6, $95, $00, $8A, $AD, $55, $02, $15, $55, $AA, $00, $82, $55, $6C, $07, $0D, $C9, $76, $00, $17, $64, $B7, $00, $86, $E4, $AE, $05, $11, $EA, $56, $00, $1B, $6D, $2A, $00, $88, $5A, $AA, $04, $14, $AD, $55, $00, $81, $AA, $D5, $09, $0B, $52, $EA, $00, $16, $A9, $6D, $00, $84, $A9, $5D, $06, $0F, $D4, $AE, $00, $1A, $EA, $4D, $00, $87, $BA, $55, $04, $12, $5A, $AA, $00, $1D, $AB, $55, $00, $8A, $A6, $D5, $02, $14, $52, $DA, $00, $82, $52, $BA, $06, $0D, $A9, $3B, $00, $18, $B4, $9B, $00, $85, $74, $9B, $05, $11, $B5, $4D, $00, $1C, $D6, $A9, $00, $88, $35, $AA, $03, $13, $A5, $B5, $00, $81, $A5, $75, $0B, $0B, $52, $B6, $00, $16, $69, $37, $00, $84, $E9, $2F, $06, $10, $F4, $97, $00, $1A, $75, $4B, $00, $87, $6D, $52, $05, $11, $2D, $69, $00, $1D, $95, $B5, $00, $8A, $A5, $6D, $02, $15, $D2, $6E, $00, $82, $D2, $5E, $07, $0E, $E9, $2E, $00, $19, $EA, $96, $00, $86, $DA, $95, $05, $10, $5B, $4A, $00, $1C, $AB, $69, $00, $88, $2A, $D8, $03); function CnDate(Y: Word; M, D: Shortint): TCnDate; begin if (Y < 1901) or (Y > 2050) then raise EConvertError.CreateFmt('农历年份范围无效,只支持 1901-2050 年间的农历范围。', [Y]); if (M > 12) or (M = 0) or (M < -12) then raise EConvertError.CreateFmt('农历月份范围无效,只支持 -12~-1,1-12 之间的有效值。', [M]); if (D < 1) or (D > 30) then raise EConvertError.CreateFmt('农历日值范围无效,只支持 1-30 之间的有效值。', [M]); Result.Year := Y; Result.Day := CnMonthDays(Y, M); if Result.Day = 0 then raise Exception.CreateFmt('指定的年份 %d 不存在 %s 月', [Y, CnMonthName(M)]); Result.Month := M; if Byte(D) > Result.Day then raise Exception.CreateFmt('指定的 %d 年 %s 月 %d 日无效,该月只有 %d 天', [Y, CnMonthName(M), Result.Day]); Result.Day := D; end; // 日期是该年的第几天,1月1日为第一天 function DaysNumberOfDate(yyyy, mm, dd: Word): Integer; overload; var I: Integer; begin Result := 0; for I := 1 to mm - 1 do Inc(Result, MonthDays[IsLeapYear(yyyy), I]); Inc(Result, dd); end; function DaysNumberOfDate(ADate: TDateTime): Integer; overload; var yyyy, mm, dd: Word; begin DecodeDate(ADate, yyyy, mm, dd); Result := DaysNumberOfDate(yyyy, mm, dd); end; function ToCnDate(ADate: TDateTime): TCnDate; var yyyy, mm, dd: Word; begin DecodeDate(ADate, yyyy, mm, dd); Result := ToCnDate(yyyy, mm, dd); end; function CnMonthDays(Y: Word; M: Shortint): Byte; var CnMonth, CnMonthDays: array [0 .. 15] of Integer; Bytes: array [0 .. 3] of Byte; I: Integer; LeapMonth: Integer; CnMonthData: Word; begin Result := 0; if (Y < 1901) or (Y > 2050) then Exit; Bytes[0] := CnData[(Y - 1901) * 4]; Bytes[1] := CnData[(Y - 1901) * 4 + 1]; Bytes[2] := CnData[(Y - 1901) * 4 + 2]; Bytes[3] := CnData[(Y - 1901) * 4 + 3]; if (Bytes[0] and $80) <> 0 then CnMonth[0] := 12 else CnMonth[0] := 11; CnMonthData := Bytes[1]; CnMonthData := CnMonthData shl 8; CnMonthData := CnMonthData or Bytes[2]; LeapMonth := Bytes[3]; for I := 15 downto 0 do begin CnMonthDays[15 - I] := 29; if ((1 shl I) and CnMonthData) <> 0 then Inc(CnMonthDays[15 - I]); if CnMonth[15 - I] = LeapMonth then CnMonth[15 - I + 1] := -LeapMonth else begin if CnMonth[15 - I] < 0 then // 上月为闰月 CnMonth[15 - I + 1] := -CnMonth[15 - I] + 1 else CnMonth[15 - I + 1] := CnMonth[15 - I] + 1; if CnMonth[15 - I + 1] > 12 then CnMonth[15 - I + 1] := 1; end; end; I := 0; while I < 16 do begin if CnMonth[I] = 1 then // 1月 begin while I < 16 do begin if CnMonth[I] = M then begin Result := CnMonthDays[I]; Break; end; Inc(I); end; Break; end; Inc(I); end; end; function ToCnDate(yyyy, mm, dd: Word): TCnDate; var CnMonth, CnMonthDays: array [0 .. 15] of Integer; CnBeginDay, LeapMonth: Integer; Bytes: array [0 .. 3] of Byte; I: Integer; CnMonthData: Word; ACnEnd: TCnDate; DaysCount, CnDaysCount, ResultMonth, ResultDay: Integer; begin if (yyyy < 1901) or (yyyy > 2050) then begin Result.Value := 0; Exit; end; Bytes[0] := CnData[(yyyy - 1901) * 4]; Bytes[1] := CnData[(yyyy - 1901) * 4 + 1]; Bytes[2] := CnData[(yyyy - 1901) * 4 + 2]; Bytes[3] := CnData[(yyyy - 1901) * 4 + 3]; if (Bytes[0] and $80) <> 0 then CnMonth[0] := 12 else CnMonth[0] := 11; CnBeginDay := (Bytes[0] and $7F); CnMonthData := Bytes[1]; CnMonthData := CnMonthData shl 8; CnMonthData := CnMonthData or Bytes[2]; LeapMonth := Bytes[3]; for I := 15 downto 0 do begin CnMonthDays[15 - I] := 29; if ((1 shl I) and CnMonthData) <> 0 then Inc(CnMonthDays[15 - I]); if CnMonth[15 - I] = LeapMonth then CnMonth[15 - I + 1] := -LeapMonth else begin if CnMonth[15 - I] < 0 then // 上月为闰月 CnMonth[15 - I + 1] := -CnMonth[15 - I] + 1 else CnMonth[15 - I + 1] := CnMonth[15 - I] + 1; if CnMonth[15 - I + 1] > 12 then CnMonth[15 - I + 1] := 1; end; end; DaysCount := DaysNumberOfDate(yyyy, mm, dd) - 1; if DaysCount <= (CnMonthDays[0] - CnBeginDay) then begin ACnEnd := ToCnDate(EncodeDate(yyyy - 1, 12, 31)); if (yyyy > 1901) and (ACnEnd.Month < 0) then ResultMonth := -CnMonth[0] else ResultMonth := CnMonth[0]; ResultDay := CnBeginDay + DaysCount; end else begin CnDaysCount := CnMonthDays[0] - CnBeginDay; I := 1; while (CnDaysCount < DaysCount) and (CnDaysCount + CnMonthDays[I] < DaysCount) do begin Inc(CnDaysCount, CnMonthDays[I]); Inc(I); end; ResultMonth := CnMonth[I]; ResultDay := DaysCount - CnDaysCount; end; if (ResultMonth in [11, 12]) and (mm in [1, 2]) then Dec(yyyy); Result.Year := yyyy; Result.Month := ResultMonth; Result.Day := ResultDay; end; function ToEnDate(ADate: TCnDate): TDateTime; var tempDate: TDateTime; ADelta: Integer; ACnTemp: TCnDate; begin if ADate.Month > 11 then tempDate := EncodeDate(ADate.Year - 1, ADate.Month, ADate.Day) else tempDate := EncodeDate(ADate.Year, abs(ADate.Month), ADate.Day); Result := 0; while Result = 0 do begin ACnTemp := ToCnDate(tempDate); if ACnTemp.Value = ADate.Value then begin Result := tempDate; Break; end else begin ADelta := 0; if ADate.Year <> ACnTemp.Year then ADelta := (abs(ADate.Month) + 11 - abs(ACnTemp.Month)) * 29 else if ADate.Month <> ACnTemp.Month then begin if ADate.Month <> -ACnTemp.Month then ADelta := (abs(ADate.Month) - abs(ACnTemp.Month) - 1) * 29; end; if ADelta = 0 then ADelta := 1; tempDate := IncDay(tempDate, ADelta); end; end; end; function CnYearOf(ADate: TDateTime): Smallint; begin Result := ToCnDate(ADate).Year; end; function CnYearName(ADate: TCnDate): String; begin Result := CnSkyNames[(ADate.Year - BaseSkyStemDate) mod 10 + 1] + CnEarthNames [(ADate.Year - BaseAnimalDate) mod 12 + 1]; end; function CnYearName(ADate: TDateTime): String; begin Result := CnYearName(ToCnDate(ADate)); end; function CnMonthOf(ADate: TDateTime): Shortint; begin Result := ToCnDate(ADate).Month; end; function CnMonthName(ADate: TCnDate): String; begin if ADate.Month < 0 then Result := '闰' + CnMonthNames[-ADate.Month] else Result := CnMonthNames[ADate.Month] end; function CnMonthName(ADate: TDateTime): String; begin Result := CnMonthName(ToCnDate(ADate)); end; function CnDayOf(ADate: TDateTime): Shortint; begin Result := ToCnDate(ADate).Day; end; function CnDayName(ADate: TCnDate): String; begin Result := CnDayNames[ADate.Day]; end; function CnDayName(ADate: TDateTime): String; begin Result := CnDayNames[ToCnDate(ADate).Day]; end; function CnHourName(AHour: Byte): String; begin AHour := ((AHour + 1) shr 1) mod 12; // Result := CnEarthNames[AHour + 1]; end; function CnAnimalOf(ADate: TCnDate): String; begin Result := CnEarthNames[(ADate.Year - BaseAnimalDate) mod 12 + 1] + CnAnimals[(ADate.Year - BaseAnimalDate) mod 12 + 1]; end; function CnAnimalOf(ADate: TDateTime): String; begin Result := CnAnimalOf(ToCnDate(ADate)); end; function DateOfCnSolarTerm(AYear: Smallint; AName: String): TDateTime; var AIndex: Integer; AFlags: Byte; ADay: Word; I: Integer; begin AIndex := (AYear - START_YEAR) * 12; Result := 0; for I := 1 to 12 do begin AFlags := gLunarHolDay[AIndex + I - 1]; ADay := 15 - (AFlags shr 4) and $0F; if CnSolarTerms[((I - 1) shl 1) + 1] = AName then begin Result := EncodeDate(AYear, I, ADay); Break; end else begin ADay := 15 + (AFlags and $0F); if CnSolarTerms[I shl 1] = AName then begin Result := EncodeDate(AYear, I, ADay); Break; end end; end; end; function CnSolarTerm(ADate: TCnDate): Shortint; begin Result := CnSolarTerm(ToEnDate(ADate)); end; function CnSolarTerm(ADate: TDateTime): Shortint; var iYear, iMonth, iDay: Word; begin DecodeDate(ADate, iYear, iMonth, iDay); Result := CnSolarTerm(iYear, iMonth, iDay); end; function CnSolarTermName(ADate: TCnDate): String; begin Result := CnSolarTerms[CnSolarTerm(ADate)]; end; function CnSolarTermName(ADate: TDateTime): String; begin Result := CnSolarTerms[CnSolarTerm(ADate)]; end; function CnSolarTerm(AYear, AMonth, ADay: Word): Shortint; var Flag: Byte; Day: Word; AIndex: Integer; begin AIndex := (AYear - START_YEAR) * 12 + AMonth - 1; Flag := gLunarHolDay[AIndex]; if ADay < 15 then Day := 15 - ((Flag shr 4) and $0F) else Day := (Flag and $0F) + 15; if ADay = Day then if ADay > 15 then Result := (AMonth - 1) * 2 + 2 else Result := (AMonth - 1) * 2 + 1 else Result := 0; end; function CalcCnFirstDay(ADate: TDateTime): TDateTime; var ATemp: TCnDate; begin ATemp.Year := CnYearOf(ADate); ATemp.Month := 1; ATemp.Day := 1; Result := ToEnDate(ATemp); end; function CnWeeksInYear(const ADate: TDateTime): Byte; var CnStartYearDate, CnEndYearDate: TDateTime; begin CnStartYearDate := CalcCnFirstDay(ADate); CnEndYearDate := CalcCnFirstDay(IncYear(ADate)); Result := Trunc(CnEndYearDate - CnStartYearDate) div 7; if DayOfTheWeek(CnStartYearDate) <> 1 then Inc(Result, 1); if DayOfTheWeek(CnEndYearDate) <> 7 then Inc(Result, 1); end; function CnIncYear(ADate: TCnDate; ADelta: Integer): TCnDate; var Days: Integer; begin Inc(ADate.Year, ADelta); if (ADate.Year < 1901) or (ADate.Year > 2050) then raise Exception.Create('指定的年份范围越界,农历只支持 1901-2050年范围。'); Result.Year := ADate.Year; if ADate.Month < 0 then Result.Month := -ADate.Month else Result.Month := ADate.Month; Days := CnMonthDays(Result.Year, Result.Month); if ADate.Day <= Days then Result.Day := ADate.Day else raise Exception.CreateFmt('编码日期时出错,无法获取 %d 年 %s 月的天数。', [Result.Year, CnMonthName(Result.Month)]); end; function CnIncDay(ADate: TCnDate; ADelta: Integer): TCnDate; begin end; function CnIncMonth(ADate: TCnDate; ADelta: Integer): TCnDate; var D: Byte; begin Result.Value := ADate.Value; while ADelta > 0 do begin Result.Day := 1; Result := ToCnDate(IncDay(ToEnDate(Result), 31)); D := CnMonthDays(Result.Year, Result.Month); if ADate.Day > D then Result.Day := D else Result.Day := ADate.Day; Dec(ADelta); end; while ADelta < 0 do begin Result.Day := 1; Result := ToCnDate(IncDay(ToEnDate(Result), -2)); D := CnMonthDays(Result.Year, Result.Month); if ADate.Day > D then Result.Day := D else Result.Day := ADate.Day; Inc(ADelta); end; end; end.
{ controller.pas Controller class for the texteditor example. This example project is released under public domain AUTHORS: Felipe Monteiro de Carvalho } unit controller; {$mode delphi}{$STATIC ON} interface uses Classes, SysUtils, foundation, objc, appkit, MacOSAll; type { TMyController } TMyController = class(NSObject) public { Extra binding functions } constructor Create; override; procedure AddMethods; override; { Objective-c Methods } class procedure doClose(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; {$ifndef VER2_2_2}static;{$endif} class procedure doOpenFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; {$ifndef VER2_2_2}static;{$endif} class procedure doSaveFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; {$ifndef VER2_2_2}static;{$endif} class procedure doSaveAsFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; {$ifndef VER2_2_2}static;{$endif} class function applicationShouldTerminateAfterLastWindowClosed(_self: objc.id; _cmd: SEL; theApplication: objc.id): cbool; cdecl; {$ifndef VER2_2_2}static;{$endif} end; const Str_doClose = 'doClose:'; Str_doOpenFile = 'doOpenFile:'; Str_doSaveFile = 'doSaveFile:'; Str_doSaveAsFile = 'doSaveAsFile:'; Str_applicationShouldTerminateAfterLastWindowClosed = 'applicationShouldTerminateAfterLastWindowClosed:'; var myController: TMyController; OpenPanel: NSOpenPanel; SavePanel: NSSavePanel; implementation uses view, model; { TMyController } {@@ Adds methods to the class Details of the parameters string: The first parameter is the result (v = void), followed by self and _cmd (@ = id and : = SEL), and on the end "sender" (@ = id) } procedure TMyController.AddMethods; begin AddMethod(Str_doClose, 'v@:@', Pointer(doClose)); AddMethod(Str_doOpenFile, 'v@:@', Pointer(doOpenFile)); AddMethod(Str_doSaveFile, 'v@:@', Pointer(doSaveFile)); AddMethod(Str_doSaveAsFile, 'v@:@', Pointer(doSaveAsFile)); AddMethod(Str_applicationShouldTerminateAfterLastWindowClosed, 'B@:@', Pointer(applicationShouldTerminateAfterLastWindowClosed)); end; constructor TMyController.Create; begin { The class is registered on the Objective-C runtime before the NSObject constructor is called } if not CreateClassDefinition(ClassName(), Str_NSObject) then WriteLn('Failed to create objc class ' + ClassName()); inherited Create; { Create objects } OpenPanel := NSOpenPanel.openPanel; SavePanel := NSSavePanel.savePanel; end; { Objective-c Methods } class procedure TMyController.doClose(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; begin myView.MainWindow.close; end; class procedure TMyController.doOpenFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; var FileContents: NSString; begin { Show dialog } if OpenPanel.runModal = NSFileHandlingPanelOKButton then begin CFStringGetPascalString(OpenPanel.filename, @myModel.DocumentName, 255, kCFStringEncodingUTF8); { Now move the contents of the edit control to the file } FileContents := NSString.initWithContentsOfFile(OpenPanel.filename); myView.TextField.setStringValue(CFStringRef(FileContents.Handle)); end; end; class procedure TMyController.doSaveFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; var FileContents: NSString; begin if myModel.DocumentName = Str_Untitled then doSaveAsFile(_self, _cmd, sender) else begin { Now move the contents of the file to the edit control } FileContents := NSString.CreateWithHandle(objc.id(myView.TextField.StringValue)); FileContents.writeToFile_atomically(CFStringCreateWithPascalString(nil, myModel.DocumentName, kCFStringEncodingUTF8), False); end; end; class procedure TMyController.doSaveAsFile(_self: objc.id; _cmd: SEL; sender: objc.id); cdecl; var FileContents: NSString; begin { Show dialog } if SavePanel.runModal = NSFileHandlingPanelOKButton then begin CFStringGetPascalString(SavePanel.filename, @myModel.DocumentName, 255, kCFStringEncodingUTF8); { Now move the contents of the file to the edit control } FileContents := NSString.CreateWithHandle(objc.id(myView.TextField.StringValue)); FileContents.writeToFile_atomically(CFStringCreateWithPascalString(nil, myModel.DocumentName, kCFStringEncodingUTF8), False); end; end; class function TMyController.applicationShouldTerminateAfterLastWindowClosed(_self: objc.id; _cmd: SEL; theApplication: objc.id): cbool; cdecl; begin Result := objc.YES; end; end.
namespace Sugar.Crypto; interface {$IFDEF ECHOES}(* uses System.IO, System.IO.Compression, System.Security.Cryptography; type Aes = public class private protected public const AESBlockLength = 16; const AESKeyLength = 32; const AesCipherMode = CipherMode.CBC; const AesPaddingMode = PaddingMode.PKCS7; class method AesFactory(myKey: AESKey := nil; myIV: AESBlock := nil): AesManaged; class method GenerateKeys: tuple of (AESBlock, AESKey); class method encryptStringToBytes(plainText: String; Key: AESKey; IV: AESBlock): array of Byte; class method decryptStringFromBytes(cipherText: array of Byte; Key: AESKey; IV: AESBlock): String; end; AESBlock = array[0 .. AESBlockLength - 1] of Byte; AESKey = array[0 .. AESKeyLength - 1] of Byte; *){$ENDIF} implementation {$IFDEF ECHOES}(* class method Aes.AesFactory(myKey: AESKey; myIV: AESBlock): AesManaged; begin result := new AesManaged( Mode := AesCipherMode, Padding := AesPaddingMode, KeySize := AESKeyLength * 8, FeedbackSize := AESBlockLength * 8, BlockSize := AESBlockLength * 8); if assigned(myKey) and assigned(myIV) then begin result.Key := myKey; result.IV := myIV; end; ensure result.Mode = AesCipherMode; result.Padding = AesPaddingMode; result.KeySize = AESKeyLength * 8; result.FeedbackSize = AESBlockLength * 8; result.BlockSize = AESBlockLength * 8; end; class method Aes.GenerateKeys: tuple of (AESBlock, AESKey); begin using aes := AesFactory do exit(aes.IV, aes.Key); end; class method Aes.encryptStringToBytes(plainText: String; Key: AESKey; IV: AESBlock): array of Byte; require assigned(plainText) : "The method encryptStringToBytes requires the plainText parameter to be defined."; plainText.Length > 0 : "The method encryptStringToBytes requires the plainText parameter to be defined."; assigned(Key) : "The method encryptStringToBytes requires the Key parameter to be defined."; assigned(IV) : "The method encryptStringToBytes requires the IV parameter to be defined."; Key.Length = AESKeyLength : "Invalid Key Length when calling encryptStringToBytes."; IV.Length = AESBlockLength : "Invalid IV Length when calling encryptStringToBytes."; begin // Create an AesManaged object with the specified key and IV. using aesAlg := AesFactory(Key, IV) do // The encrytor to performs the stream transform. using encryptor := aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) do // The memory stream holds the output using output := new MemoryStream() do // The CryptoStream performs the encryption using encStrm := new CryptoStream(output, encryptor, CryptoStreamMode.Write) do // The DeflateStream compresses the input using gzip := new DeflateStream(encStrm, CompressionMode.Compress) do // in .NET 4.5 use CompressionLevel.Fastest // The StreamWriter takes the input using writer := new StreamWriter(gzip) do begin //Write all data to the stream. writer.Write(plainText); // Close writer to prepare output writer.Close(); exit output.ToArray(); end; ensure assigned(result) and (result.Length > 0): "Undefined result from encryptStringToBytes."; end; class method Aes.decryptStringFromBytes(cipherText: array of Byte; Key: AESKey; IV: AESBlock): String; require assigned(cipherText) : "The method decryptStringFromBytes requires the cipherText parameter to be defined."; cipherText.Length > 0 : "The method decryptStringFromBytes requires the cipherText parameter to be defined."; assigned(Key) : "The method encryptStringToBytes requires the Key parameter to be defined."; assigned(IV) : "The method encryptStringToBytes requires the IV parameter to be defined."; Key.Length = AESKeyLength : "Invalid Key Length when calling encryptStringToBytes."; IV.Length = AESBlockLength : "Invalid IV Length when calling encryptStringToBytes."; begin var plaintext: String; // Create an AesManaged object with the specified key and IV. using aesAlg := AesFactory(Key, IV) do // Create a decrytor to perform the stream transform. using decryptor := aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV) do // Create the streams used for decryption. using inStrm := new MemoryStream(cipherText) do using decStrm := new CryptoStream(inStrm, decryptor, CryptoStreamMode.Read) do using gzip := new DeflateStream(decStrm, CompressionMode.Decompress) do using reader := new StreamReader(gzip) do begin // Read the decrypted bytes from the decrypting stream and place them in a string. plaintext := reader.ReadToEnd(); end; exit plaintext; ensure assigned(result) : "Undefined result from decryptStringFromBytes."; result.Length > 0 : "Undefined result from decryptStringFromBytes."; end; *){$ENDIF} end.
unit UDataListViewFrame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.JSON, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView, UDataListView, DBXJSON, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter, REST.Client, FMX.Controls.Presentation; type TDataListViewFrame = class(TFrame) DataListView: TDataListView; TopToolBar: TToolBar; TopToolBarLabel: TLabel; RefreshSpeedButton: TSpeedButton; DeleteSpeedButton: TSpeedButton; DataAniIndicator: TAniIndicator; procedure DeleteSpeedButtonClick(Sender: TObject); procedure RefreshSpeedButtonClick(Sender: TObject); procedure DataListViewDeleteChangeVisible(Sender: TObject; AValue: Boolean); procedure DataListViewDeleteItem(Sender: TObject; AIndex: Integer); procedure DataListViewDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); procedure DataListViewItemClick(const Sender: TObject; const AItem: TListViewItem); private { Private declarations } fDataSet: TDataSet; fRESTRequestList: TRESTRequest; fRESTRequestDelete: TRESTRequest; fRESTResponseDelete: TRESTResponse; fDetailStringlist: TStringList; fDataFieldName: String; procedure initDataListView; procedure startSpinner; procedure stopSpinner; public { Public declarations } procedure init(lDataSet: TDataSet; lRESTRequestList: TRESTRequest; lRESTRequestDelete: TRESTRequest; lRESTResponseDelete: TRESTResponse; lDataFieldName: String; lDetailStringlist: TStringList); end; implementation {$R *.fmx} procedure TDataListViewFrame.init(lDataSet: TDataSet; lRESTRequestList: TRESTRequest; lRESTRequestDelete: TRESTRequest; lRESTResponseDelete: TRESTResponse; lDataFieldName: String; lDetailStringlist: TStringList); begin fDataSet := lDataSet; fRESTRequestList := lRESTRequestList; fRESTRequestDelete := lRESTRequestDelete; fRESTResponseDelete := lRESTResponseDelete; fDataFieldName := lDataFieldName; fDetailStringlist := lDetailStringlist; initDataListView; end; procedure TDataListViewFrame.stopSpinner; begin // spinner off DataAniIndicator.Visible := False; DataAniIndicator.Enabled := False; DataListView.Enabled := True; RefreshSpeedButton.Visible := True; end; procedure TDataListViewFrame.startSpinner; begin // spinner on DataListView.Enabled := False; RefreshSpeedButton.Visible := False; DataAniIndicator.Visible := True; DataAniIndicator.Enabled := True; Application.ProcessMessages; end; procedure TDataListViewFrame.DataListViewDeleteChangeVisible(Sender: TObject; AValue: Boolean); begin if (DataListView.ItemCount = 0) then begin DataListView.EditMode := False; if DeleteSpeedButton.StyleLookup = 'donetoolbutton' then begin DeleteSpeedButton.StyleLookup := 'trashtoolbutton'; end; end; // enable delete button only if more than 1 item in list DeleteSpeedButton.Enabled := (DataListView.ItemCount <> 0); // Stop the spinner stopSpinner; end; procedure TDataListViewFrame.DataListViewDeleteItem(Sender: TObject; AIndex: Integer); begin // il faut réinitialiser la timerlist pour éviter // des désynchronisations entre la listview et le dataset try if AIndex < DataListView.ItemCount then begin initDataListView; end; except end; end; procedure TDataListViewFrame.DataListViewDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); var lJSONObject: TJSONObject; lJSONPair: TJSONPair; begin inherited; try fDataSet.RecNo := DataListView.ItemIndex + 1; except end; // start the spinner startSpinner; // ShowMessage(UTF8ToWideString(fDataSet.FieldByName('serviceref').AsString)); // Exit; // fRESTRequestDelete.Params[0].Value := UTF8EncodeToShortString // (fDataSet.FieldByName('serviceref').AsString); fRESTRequestDelete.Params[0].Value := UTF8EncodeToShortString (fDataSet.FieldByName('serviceref').AsString); if (fRESTRequestDelete.Params.Count = 3) then begin fRESTRequestDelete.Params[1].Value := fDataSet.FieldByName('begin') .AsString; fRESTRequestDelete.Params[2].Value := fDataSet.FieldByName('end').AsString; end; try fRESTRequestDelete.Execute; except // stop the spinner stopSpinner; MessageDlg('Event could not be deleted!' + CHR(13) + 'Please delete on decoder!', System.UITypes.TMsgDlgType.mtError, [System.UITypes.TMsgDlgBtn.mbOK], 0); end; if fRESTResponseDelete.StatusCode = 200 then begin lJSONObject := TJSONObject.ParseJSONValue(fRESTResponseDelete.Content) as TJSONObject; if (lJSONObject.Get(1).JsonValue is TJSONTrue) then begin // stop the spinner stopSpinner; MessageDlg(lJSONObject.Get(0).JsonValue.Value, System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbOK], 0); ACanDelete := True; end else begin // stop the spinner stopSpinner; MessageDlg('Event could not be deleted!', System.UITypes.TMsgDlgType.mtError, [System.UITypes.TMsgDlgBtn.mbOK], 0); ACanDelete := False; end; end else begin // stop the spinner stopSpinner; // MessageDlg('The following error occurred: ' + // fRESTResponseDelete.StatusText, System.UITypes.TMsgDlgType.mtError, // [System.UITypes.TMsgDlgBtn.mbOK], 0); ACanDelete := False; end; end; procedure TDataListViewFrame.DataListViewItemClick(const Sender: TObject; const AItem: TListViewItem); begin fDataSet.RecNo := DataListView.ItemIndex + 1; end; procedure TDataListViewFrame.initDataListView; begin // start the spinner startSpinner; // initialisation des timers try fRESTRequestList.Execute; except Exit; end; DataListView.DataSet := fDataSet; DataListView.DataFieldName := fDataFieldName; try DataListView.init(fDetailStringlist); except FreeAndNil(fDetailStringlist); end; // stop the spinner stopSpinner; // enable delete button only if more than 1 item in list DeleteSpeedButton.Enabled := (DataListView.ItemCount <> 0); end; procedure TDataListViewFrame.RefreshSpeedButtonClick(Sender: TObject); begin inherited; initDataListView; end; procedure TDataListViewFrame.DeleteSpeedButtonClick(Sender: TObject); begin inherited; if DeleteSpeedButton.StyleLookup = 'trashtoolbutton' then begin DeleteSpeedButton.StyleLookup := 'donetoolbutton'; DeleteSpeedButton.Width := 60; end else begin DeleteSpeedButton.StyleLookup := 'trashtoolbutton'; DeleteSpeedButton.Width := 44; end; DataListView.EditMode := not DataListView.EditMode; end; end.
unit GX_BookmarkList; interface uses SysUtils, Classes; type TBookmark = class private FLine: Integer; FNumber: Integer; FCharIdx: Integer; FModule: string; FText: string; public constructor Create(_Number, _Line, _CharIdx: Integer; const _Module: string); overload; constructor Create(_bm: TBookmark); overload; function IsSame(_bm: TBookmark): Boolean; property Number: Integer read FNumber; property Line: Integer read FLine; property CharIdx: Integer read FCharIdx; property Module: string read FModule; property Text: string read FText write FText; end; type TBookmarkList = class private function GetCount: Integer; function GetItems(_Idx: Integer): TBookmark; function CompareBookmarks(_Item: Pointer; _Idx: Integer): Integer; protected FList: TList; public constructor Create; destructor Destroy; override; function Add(_Number, _Line, _CharIdx: Integer; const _Module: string = ''): Boolean; procedure Clear; property Items[_Idx: Integer]: TBookmark read GetItems; default; property Count: Integer read GetCount; end; implementation uses GX_dzQuicksort; { TBookmark } constructor TBookmark.Create(_Number, _Line, _CharIdx: Integer; const _Module: string); begin inherited Create; FNumber := _Number; FLine := _Line; FCharIdx := _CharIdx; FModule := _Module; end; constructor TBookmark.Create(_bm: TBookmark); begin Create(_bm.Number, _bm.Line, _bm.CharIdx, _bm.Module); end; function TBookmark.IsSame(_bm: TBookmark): Boolean; begin Result := (Line = _bm.Line) and (CharIdx = _bm.CharIdx) and (Number = _bm.Number) and (Module = _bm.Module); end; { TBookmarkList } constructor TBookmarkList.Create; begin inherited; FList := TList.Create; end; destructor TBookmarkList.Destroy; var i: Integer; begin if Assigned(FList) then begin for i := 0 to FList.Count - 1 do TBookmark(FList[i]).Free; FList.Free; FList := nil; end; inherited; end; function TBookmarkList.CompareBookmarks(_Item: Pointer; _Idx: Integer): Integer; var Item1: TBookmark; Item2: TBookmark; begin Item1 := _Item; Item2 := Items[_Idx]; Result := CompareText(Item1.FModule, Item2.FModule); if Result = 0 then Result := Item1.FNumber - Item2.FNumber; end; function TBookmarkList.Add(_Number, _Line, _CharIdx: Integer; const _Module: string): Boolean; var bm: TBookmark; idx: Integer; begin bm := TBookmark.Create(_Number, _Line, _CharIdx, _Module); if BinarySearch(0, FList.Count - 1, idx, bm, CompareBookmarks) then begin bm.Free; Result := False; end else begin FList.Insert(idx, bm); Result := True; end; end; function TBookmarkList.GetCount: Integer; begin Result := FList.Count; end; function TBookmarkList.GetItems(_Idx: Integer): TBookmark; begin Result := FList[_Idx]; end; procedure TBookmarkList.Clear; var i: Integer; begin for i := 0 to FList.Count - 1 do TBookmark(FList[i]).Free; FList.Clear; end; end.
{ RegisterRxDB unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit RegisterRxDB; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, LazarusPackageIntf; procedure Register; implementation uses DB, DBPropEdits, rxdbgrid, RxDBSpinEdit, RxDBTimeEdit, RxDBCtrls, rxmemds, ComponentEditors, seldsfrm, PropEdits, RxDBColorBox, dbdateedit, rxdbcomb, rxlookup, dbcurredit; type { TRxDBGridFieldProperty } TRxDBGridFieldProperty = class(TFieldProperty) public procedure FillValues(const Values: TStringList); override; end; { TRxDBGridFieldProperty } procedure TRxDBGridFieldProperty.FillValues(const Values: TStringList); var Column: TRxColumn; Grid: TRxDBGrid; DataSource: TDataSource; begin Column:=TRxColumn(GetComponent(0)); if not (Column is TRxColumn) then exit; Grid:=TRxDBGrid(Column.Grid); if not (Grid is TRxDBGrid) then exit; DataSource := Grid.DataSource; if Assigned(DataSource) and Assigned(DataSource.DataSet) then DataSource.DataSet.GetFieldNames(Values); end; type { TRxDBGridFooterFieldProperty } TRxDBGridFooterFieldProperty = class(TFieldProperty) public procedure FillValues(const Values: TStringList); override; end; { TRxDBGridFieldProperty } procedure TRxDBGridFooterFieldProperty.FillValues(const Values: TStringList); var Footer: TRxColumnFooter; Grid: TRxDBGrid; DataSource: TDataSource; begin Footer:=TRxColumnFooter(GetComponent(0)); Grid:=TRxDBGrid(Footer.Owner.Grid); if not (Grid is TRxDBGrid) then exit; DataSource := Grid.DataSource; if Assigned(DataSource) and Assigned(DataSource.DataSet) then DataSource.DataSet.GetFieldNames(Values); end; procedure RegisterRxDBSpinEdit; begin RegisterComponents('RX DBAware',[TRxDBSpinEdit]); end; procedure RegisterRxDBTimeEdit; begin RegisterComponents('RX DBAware',[TRxDBTimeEdit]); end; procedure RegisterRxDBCtrls; begin RegisterComponents('RX DBAware',[TRxDBProgressBar, TRxDBTrackBar, TRxDBRadioGroup]); end; procedure RegisterRxDbGrid; begin RegisterComponents('RX DBAware',[TRxDBGrid]); end; procedure RegisterRxMemDS; begin RegisterComponents('RX DBAware',[TRxMemoryData]); end; procedure RegisterRxDBColorBox; begin RegisterComponents('RX DBAware',[TRxDBColorBox]); end; procedure RegisterUnitDBDateEdit; begin RegisterComponents('RX DBAware',[TDBDateEdit, TRxDBCalcEdit, TRxDBCurrEdit]); end; procedure RegisterRXLookup; begin RegisterComponents('RX DBAware',[TRXLookupEdit, TRxDBLookupCombo]); end; procedure RegisterRxDBComb; begin RegisterComponents('RX DBAware',[TRxDBComboBox]); end; procedure Register; begin //RX DBAware RegisterUnit('dbdateedit', @RegisterUnitDBDateEdit); RegisterUnit('rxlookup', @RegisterRXLookup); RegisterUnit('rxdbcomb', @RegisterRxDBComb); RegisterUnit('RxDBTimeEdit', @RegisterRxDBTimeEdit); RegisterUnit('RxDBSpinEdit', @RegisterRxDBSpinEdit); RegisterUnit('RxDBCtrls', @RegisterRxDBCtrls); RegisterUnit('rxdbgrid', @RegisterRxDbGrid); RegisterUnit('rxmemds', @RegisterRxMemDS); RegisterUnit('RxDBColorBox', @RegisterRxDBColorBox); //Component Editors RegisterComponentEditor(TRxMemoryData, TMemDataSetEditor); // RegisterPropertyEditor(TypeInfo(string), TRxColumn, 'FieldName', TRxDBGridFieldProperty); RegisterPropertyEditor(TypeInfo(string), TRxColumnFooter, 'FieldName', TRxDBGridFooterFieldProperty); end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type StringTest = public class (Test) private Data: String; public method Setup; override; method LengthProperty; method CharsProperty; method Contactenation; method ImplicistCast; method Format; method CharacterIsWhiteSpace; method IsNullOrEmpty; method IsNullOrWhiteSpace; method FromByteArray; method CompareTo; method CompareToIgnoreCase; method &Equals; method EqualsIngoreCase; method Contains; method IndexOf; method LastIndexOf; method Substring; method Split; method Replace; method LowerUpperCase; method Trim; method StartsWith; method EndsWith; method ToByteArray; method Operators; method FromCharArray; method ToCharArray; method NilComparison; end; implementation method StringTest.Setup; begin Data := "Hello"; end; method StringTest.LengthProperty; begin Assert.AreEqual(Data.Length, 5); Data := "abc"; Assert.AreEqual(Data.Length, 3); Assert.AreEqual(Sugar.String("").Length, 0); end; method StringTest.CharsProperty; begin Assert.AreEqual(Data.Chars[1], 'e'); //chars property Assert.AreEqual(Data[4], 'o');//default property Assert.AreEqual(Data[0], 'H'); Assert.Throws(->Data.Chars[244]);//out of range Assert.Throws(->Data.Chars[5]); Assert.Throws(->Data.Chars[-1]); end; method StringTest.Contactenation; begin //Native string var NativeString := Data + " World"; Assert.AreEqual(NativeString.Length, 11); Assert.AreEqual(NativeString, "Hello World"); //Sugar string var SugarString: Sugar.String := Data + " World"; Assert.AreEqual(SugarString.Length, 11); Assert.AreEqual(SugarString, "Hello World"); end; method StringTest.ImplicistCast; begin var C: Char := 'x'; var SugarString: Sugar.String := C; Assert.AreEqual(SugarString, "x"); end; method StringTest.CharacterIsWhiteSpace; begin Assert.IsFalse(String.CharacterIsWhiteSpace(Data[2])); Assert.IsTrue(String.CharacterIsWhiteSpace(' ')); Assert.IsFalse(String.CharacterIsWhiteSpace('x')); end; method StringTest.Format; begin Assert.AreEqual(String.Format("{0}", "Hello"), "Hello"); Assert.AreEqual(String.Format("First {0} Third", "Second"), "First Second Third"); Assert.AreEqual(String.Format("{0} is so {0}", "white"), "white is so white"); Assert.AreEqual(String.Format("{0} {1} {2}", "First", "Second", "Third"), "First Second Third"); //parameters are converted by using ToString method Assert.AreEqual(String.Format("{0}", 42), "42"); //accepts width Assert.AreEqual(String.Format("{0,7}", "Text"), " Text"); Assert.AreEqual(String.Format("{0,-7}", "Text"), "Text "); //accepts format specifiers but the are ignored Assert.AreEqual(String.Format("{0:X4}", 255), "255"); //all specifiers together Assert.AreEqual(String.Format("{0,-5:X4}", 255), "255 "); //escaping brackets Assert.AreEqual(String.Format("{{{0}}}", 42), "{42}"); Assert.Throws(->String.Format("{0", "")); Assert.Throws(->String.Format("{0)", "")); Assert.Throws(->String.Format("(0}", "")); Assert.Throws(->String.Format("{0", "")); Assert.Throws(->String.Format("{0}", nil)); Assert.Throws(->String.Format(nil, "")); Assert.Throws(->String.Format("{a}", "")); Assert.Throws(->String.Format("{-1}", "")); Assert.Throws(->String.Format("{0", "")); Assert.Throws(->String.Format("{0,z}", "")); Assert.Throws(->String.Format("{0,f}", "")); Assert.Throws(->String.Format("{0,}", "")); end; method StringTest.IsNullOrEmpty; begin Assert.IsFalse(String.IsNullOrEmpty(Data)); Assert.IsTrue(String.IsNullOrEmpty(nil)); Assert.IsTrue(String.IsNullOrEmpty("")); end; method StringTest.IsNullOrWhiteSpace; begin Assert.IsFalse(String.IsNullOrWhiteSpace(Data)); Assert.IsTrue(String.IsNullOrWhiteSpace(nil)); Assert.IsTrue(String.IsNullOrWhiteSpace("")); Assert.IsTrue(String.IsNullOrWhiteSpace(" ")); end; method StringTest.FromByteArray; begin var Encoded: array of Byte := [103, 114, 195, 182, 195, 159, 101, 114, 101, 110]; var Expected: String := "größeren"; var Actual: String := new String(Encoded, Encoding.UTF8); Assert.AreEqual(Actual.Length, 8); Assert.AreEqual(Actual, Expected); Encoded := []; Assert.AreEqual(new String(Encoded, Encoding.UTF8), ""); Encoded := nil; Assert.Throws(-> new String(Encoded, Encoding.UTF8)); end; method StringTest.CompareTo; begin Assert.AreEqual(Data.CompareTo("Hello"), 0); Assert.AreNotEqual(Data.CompareTo("hElLo"), 0);//Case sensitive Assert.AreNotEqual(Data.CompareTo(nil), 0); Assert.AreNotEqual(Data.CompareTo(''), 0); var Sample: String := "A"; Assert.Less(Sample.CompareTo("B"), 0); //A is less than B Assert.Less(Sample.CompareTo("a"), 0); //A is less than a end; method StringTest.CompareToIgnoreCase; begin Assert.AreEqual(Data.CompareToIgnoreCase("Hello"), 0); Assert.AreEqual(Data.CompareToIgnoreCase("hElLo"), 0); var Sample: String := "A"; Assert.Less(Sample.CompareToIgnoreCase("B"), 0); //A is less than B Assert.AreEqual(Sample.CompareToIgnoreCase("a"), 0); //A equals a end; method StringTest.Equals; begin Assert.IsTrue(Data.Equals(Data)); Assert.IsTrue(Data.Equals("Hello")); Assert.IsFalse(Data.Equals("hElLo")); Assert.IsFalse(Data.Equals(nil)); end; method StringTest.EqualsIngoreCase; begin Assert.IsTrue(Data.EqualsIgnoreCase(Data)); Assert.IsTrue(Data.EqualsIgnoreCase("Hello")); Assert.IsTrue(Data.EqualsIgnoreCase("hElLo")); Assert.IsFalse(Data.EqualsIgnoreCase(nil)); end; method StringTest.Contains; begin Assert.IsTrue(Data.Contains("Hello")); Assert.IsTrue(Data.Contains(Data)); Assert.IsFalse(Data.Contains("hElLo")); //case sensitive Assert.IsTrue(Data.Contains('e')); Assert.IsFalse(Data.Contains('E')); Assert.IsTrue(Data.Contains("ll")); Assert.IsFalse(Data.Contains("lL")); Assert.IsTrue(Data.Contains("")); //true when check performed on empty string Assert.Throws(->Data.Contains(nil)); //should throw an exception end; method StringTest.IndexOf; begin Assert.AreEqual(Data.IndexOf("Hello"), 0); Assert.AreEqual(Data.IndexOf(Data), 0); Assert.AreEqual(Data.IndexOf("hElLo"), -1); Assert.AreEqual(Data.IndexOf("e"), 1); Assert.AreEqual(Data.IndexOf("E"), -1); Assert.AreEqual(Data.IndexOf('e'), 1); Assert.AreEqual(Data.IndexOf('E'), -1); Assert.AreEqual(Data.IndexOf("l"), 2); Assert.AreEqual(Data.IndexOf(""), 0); //returns 0 if compared with empty string Assert.Throws(->Data.IndexOf(nil));//should throw an exception end; method StringTest.LastIndexOf; begin Assert.AreEqual(Data.LastIndexOf("Hello"), 0); Assert.AreEqual(Data.LastIndexOf(Data), 0); Assert.AreEqual(Data.LastIndexOf("hElLo"), -1); Assert.AreEqual(Data.LastIndexOf("e"), 1); Assert.AreEqual(Data.LastIndexOf("E"), -1); Assert.AreEqual(Data.LastIndexOf('e'), 1); Assert.AreEqual(Data.LastIndexOf('E'), -1); Assert.AreEqual(Data.LastIndexOf("l"), 3); //last 'l' Assert.AreEqual(Data.LastIndexOf(""), Data.Length - 1); //returns last index position in string if compared with empty string Assert.Throws(->Data.LastIndexOf(nil));//should throw an exception end; method StringTest.Substring; begin Assert.AreEqual(Data.Substring(3), "lo"); Assert.AreEqual(Data.Substring(0), Data); //start index is zero based Assert.AreEqual(Data.Substring(Data.Length), ""); //start index is equal to string length, should return empty string Assert.Throws(->Data.Substring(55)); //out of range Assert.Throws(->Data.Substring(-1)); Assert.AreEqual(Data.Substring(1, 2), "el"); Assert.AreEqual(Data.Substring(Data.Length, 0), ""); //should be empty string if index equals to string length and length is 0 Assert.AreEqual(Data.Substring(1, 0), ""); Assert.Throws(->Data.Substring(55, 1)); Assert.Throws(->Data.Substring(0, 244)); Assert.Throws(->Data.Substring(-1, 1)); Assert.Throws(->Data.Substring(1, -1)); end; method StringTest.Split; begin var Original: String := "x; x; x"; var Actual := Original.Split("; "); Assert.AreEqual(length(Actual), 3); for i: Integer := 0 to length(Actual)-1 do Assert.AreEqual(Actual[i], "x"); Actual := Original.Split(";"); var Expected: array of String := ["x", " x", " x"]; Assert.AreEqual(length(Actual), 3); for i: Integer := 0 to length(Actual)-1 do Assert.AreEqual(Actual[i], Expected[i]); Actual := Original.Split(","); //not exists Assert.AreEqual(length(Actual), 1); Assert.AreEqual(Actual[0], Original); Actual := Original.Split(""); //no changes Assert.AreEqual(length(Actual), 1); Assert.AreEqual(Actual[0], Original); Actual := Original.Split(nil); //no changes Assert.AreEqual(length(Actual), 1); Assert.AreEqual(Actual[0], Original); end; method StringTest.Replace; begin Assert.AreEqual(Data.Replace("ll", "LL"), "HeLLo"); Assert.AreEqual(Data.Replace("x", "y"), Data); //not existing Assert.AreEqual(Data.Replace("E", "x"), Data); //case sensitive Assert.Throws(->Data.Replace("", "x")); Assert.Throws(->Data.Replace(nil, "x")); Assert.AreEqual(Data.Replace("l", nil), "Heo"); //remove Assert.AreEqual(Data.Replace("l", ""), "Heo"); //remove end; method StringTest.LowerUpperCase; begin Assert.AreEqual(Data.ToLower, "hello"); Assert.AreEqual(Data.ToUpper, "HELLO"); end; method StringTest.Trim; begin var Original: Sugar.String := " Data "; Assert.AreEqual(Original.Trim, "Data"); Assert.AreEqual(Sugar.String("").Trim, ""); Assert.AreEqual(Sugar.String(" ").Trim, ""); end; method StringTest.StartsWith; begin Assert.IsTrue(Data.StartsWith("Hell")); Assert.IsFalse(Data.StartsWith("x")); Assert.IsFalse(Data.StartsWith("hell")); Assert.Throws(->Data.StartsWith(nil)); Assert.IsTrue(Data.StartsWith("")); Assert.IsTrue(Data.StartsWith(Data)); end; method StringTest.EndsWith; begin Assert.IsTrue(Data.EndsWith("llo")); Assert.IsFalse(Data.EndsWith("x")); Assert.IsFalse(Data.EndsWith("Llo")); Assert.Throws(->Data.EndsWith(nil)); Assert.IsTrue(Data.EndsWith("")); Assert.IsTrue(Data.EndsWith(Data)); end; method StringTest.ToByteArray; begin var Expected: array of Byte := [103, 114, 195, 182, 195, 159, 101, 114, 101, 110]; var Value: String := "größeren"; var Actual: array of Byte := Value.ToByteArray; Assert.AreEqual(Actual, Expected); end; method StringTest.Operators; begin Data := "A"; var SugarString: String := "B"; var NativeString := "B"; Assert.IsTrue(Data < SugarString); Assert.IsTrue(Data < NativeString); Assert.IsTrue(SugarString > Data); Assert.IsTrue(NativeString > Data); Assert.IsFalse(Data > SugarString); Assert.IsFalse(Data > NativeString); Assert.IsFalse(SugarString < Data); Assert.IsFalse(NativeString < Data); Assert.IsTrue(Data <= SugarString); Assert.IsTrue(Data <= NativeString); Assert.IsTrue(SugarString >= Data); Assert.IsTrue(NativeString >= Data); Assert.IsFalse(Data >= SugarString); Assert.IsFalse(Data >= NativeString); Assert.IsFalse(SugarString <= Data); Assert.IsFalse(NativeString <= Data); Assert.IsFalse(Data = SugarString); Assert.IsFalse(Data = NativeString); Assert.IsFalse(SugarString = Data); Assert.IsFalse(NativeString = Data); end; method StringTest.FromCharArray; begin var Encoded: array of Char := ['H', 'e', 'l', 'l', 'o']; var Expected: String := "Hello"; var Actual: String := new String(Encoded); Assert.AreEqual(Actual.Length, 5); Assert.AreEqual(Actual, Expected); Encoded := []; Assert.AreEqual(new String(Encoded), ""); Encoded := nil; Assert.Throws(-> new String(Encoded)); end; method StringTest.ToCharArray; begin var Expected: array of Char := ['g', 'r', 'ö', 'ß', 'e', 'r', 'e', 'n']; var Value: String := "größeren"; var Actual: array of Char := Value.ToCharArray; Assert.AreEqual(Actual, Expected); Value := ""; Assert.AreEqual(Value.ToCharArray.Length, 0); end; method StringTest.NilComparison; begin Data := nil; var S: Sugar.String := ''; Assert.IsFalse(S = Data); Assert.IsFalse(Data = S); end; end.
program ejercicio2; type lista = ^nodo; persona = record dni: integer; nombre: string; apellido: string; end; nodo = record dato: persona; sig: lista; end; procedure leerPersona(p: persona); // 8* Debería pasarse por referencia begin read(p.dni); if (p.dni <> 0) then begin read(p.nombre); read(p.apellido); end; end; {Agrega unnodo a la lista} procedure agregarAdelante(l:lista; p:persona); // 4* La lista debería pasarse por referencia var aux: lista; begin aux^.dato := p; aux^.sig := l; l:= aux; end {Carga la lista hasta que llega el dni 0} procedure generarLista(var l:lista); var p:nodo; begin leerPersona(p); // 1* Acá le está pasando el nodo, debería pasarle nodo^.dato while (p.dni <> 0) do // 2* Como p es de tipo nodo tampoco tiene el campo dni begin agregarAdelante(l,p); // 3* Debería pasar p.dato // 9* Debería llamarse a leerPersona nuevamente adentro del bucle end; end; procedure imprimirInformacion(var l:lista); // 5* La lista debería pasarse por valor begin while(l <> nil) do begin writeln('DNI: ', l^.dato.dni, 'Nombre:', l^.nombre, 'Apellido:', l^.apellido); // 6 y 7* El nombre y el apellido no se estan accediendo // correctamente, la lista no tiene esos campos // Debería ser l^.dato.nombre y l^.dato.apellido l:= l^.sig; // Acá se perdería la referencia al primer elemento end; end; {Programa principal} var l:lista; begin generarLista(l); imprimirInformacion(l); end.
unit ExportSettingsForma; interface {$I defines.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, MemTableDataEh, Db, GridsEh, DBGridEh, MemTableEh, DBCtrlsEh, Mask, RxToolEdit, ToolWin, DBCtrls, FIBDataSet, pFIBDataSet, Menus, OkCancel_frame, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, System.Actions, Vcl.ActnList; type TExportSettingsForm = class(TForm) pnlGrid: TPanel; pnlData: TPanel; pnl1: TPanel; lbl4: TLabel; lbl7: TLabel; lbl9: TLabel; lbl8: TLabel; edtDirFiles: TDirectoryEdit; edtProfile: TDBEditEh; cbbCodePage: TDBComboBoxEh; cbbFileFormat: TDBComboBoxEh; pgcFileBody: TPageControl; tsTXT: TTabSheet; lbl1: TLabel; lbl3: TLabel; tsDBF: TTabSheet; dbgDBF: TDBGridEh; DBGridEh1: TDBGridEh; tlb1: TToolBar; btn1: TToolButton; btnNew: TToolButton; btn3: TToolButton; btnEdit: TToolButton; btn5: TToolButton; btnDEl: TToolButton; btn7: TToolButton; btnOk: TToolButton; btn8: TToolButton; btnCancel: TToolButton; srcTypes: TDataSource; srcDBF: TDataSource; dsTypes: TpFIBDataSet; dbmmoBody: TDBMemoEh; dbmmoHead: TDBMemoEh; dbmmofooter: TDBMemoEh; pmMemo: TPopupMenu; lbl5: TLabel; okcnclfrm1: TOkCancelFrame; dbnvgrDBF: TDBNavigator; lbl6: TLabel; edt1: TDBEditEh; pmTotal: TPopupMenu; pnl2: TPanel; lbl2: TLabel; lbl10: TLabel; edtSEP: TDBEditEh; memDBF: TMemTableEh; dbmmoNotice: TDBMemoEh; actList: TActionList; actAdd: TAction; actEdit: TAction; actDel: TAction; procedure FormShow(Sender: TObject); procedure miClick(Sender: TObject); procedure srcTypesDataChange(Sender: TObject; Field: TField); procedure srcTypesStateChange(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure dsTypesBeforePost(DataSet: TDataSet); procedure dbgDBFExit(Sender: TObject); procedure okcnclfrm1bbOkClick(Sender: TObject); procedure dsTypesNewRecord(DataSet: TDataSet); procedure cbbFileFormatChange(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDelExecute(Sender: TObject); private { Private declarations } procedure TextToDataset(); function DatasetToTxt():string; public { Public declarations } end; implementation uses MAIN, DM, AtrStrUtils, StrUtils; {$R *.dfm} procedure TExportSettingsForm.actAddExecute(Sender: TObject); begin if dsTypes.State = dsBrowse then begin pnlData.Enabled := True; dsTypes.Insert; edtProfile.SetFocus; actAdd.Enabled := False; actDel.Enabled := False; actEdit.Enabled := False; end; end; procedure TExportSettingsForm.actDelExecute(Sender: TObject); begin if dsTypes.RecordCount = 0 then Exit; If MessageDLG( Format(rsDeleteExportProfile,[dsTypes['NAME']]), mtConfirmation, [mbYes, mbNo], 0, mbNo) <> mrYes then exit; dsTypes.Delete; end; procedure TExportSettingsForm.actEditExecute(Sender: TObject); begin if dsTypes.State = dsBrowse then begin pnlData.Enabled := True; dsTypes.Edit; edtProfile.SetFocus; actAdd.Enabled := False; actDel.Enabled := False; actEdit.Enabled := False; end; end; procedure TExportSettingsForm.btnCancelClick(Sender: TObject); begin dsTypes.Cancel; pnlData.Enabled := False; actAdd.Enabled := true; actDel.Enabled := true; actEdit.Enabled := true; end; procedure TExportSettingsForm.btnOkClick(Sender: TObject); begin if (dmMain.AllowedAction(rght_Dictionary_full)) then dsTypes.Post else dsTypes.Cancel; pnlData.Enabled := False; actAdd.Enabled := true; actDel.Enabled := true; actEdit.Enabled := true; end; procedure TExportSettingsForm.FormShow(Sender: TObject); var i : Integer; val : TStringArray; begin for i :=0 to pgcFileBody.PageCount-1 do pgcFileBody.Pages[i].TabVisible := False; val := Explode(';',export_fields); for I := 0 to Length(val) - 1 do begin pmMemo.Items.Add(NewItem(Val[i],0,False,True,miClick,0,'mi'+IntToStr(i))); end; val := Explode(';',export_fields_total); for I := 0 to Length(val) - 1 do begin pmTotal.Items.Add(NewItem(Val[i],0,False,True,miClick,0,'mi'+IntToStr(i))); end; dsTypes.Open; end; procedure TExportSettingsForm.miClick(Sender: TObject); begin if (Sender is TMenuItem) then (ActiveControl as TDBMemoEh).SelText := (Sender as TMenuItem).Caption; end; procedure TExportSettingsForm.okcnclfrm1bbOkClick(Sender: TObject); begin if dsTypes.State in [dsEdit, dsInsert] then dsTypes.Post; end; procedure TExportSettingsForm.srcTypesDataChange(Sender: TObject; Field: TField); begin if srcTypes.State = dsBrowse then begin if not dsTypes.FieldByName('FILE_FORMAT').IsNull then pgcFileBody.ActivePageIndex := dsTypes.FieldByName('FILE_FORMAT').AsInteger else pgcFileBody.ActivePageIndex := -1; if pgcFileBody.ActivePageIndex = 1 then TextToDataset(); edtDirFiles.Text := dsTypes.FieldByName('FILE_DIR').AsString; end; end; procedure TExportSettingsForm.srcTypesStateChange(Sender: TObject); begin btnOk.Enabled := not ((sender as TDataSource).DataSet.State = dsBrowse); btnCancel.Enabled := btnOk.Enabled; btnNew.Enabled := not btnOk.Enabled; btnEdit.Enabled := not btnOk.Enabled and ((sender as TDataSource).DataSet.RecordCount>0); btnDel.Enabled := not btnOk.Enabled and ((sender as TDataSource).DataSet.RecordCount>0); dbgDBF.Enabled := btnOk.Enabled; dbnvgrDBF.Enabled := btnOk.Enabled; edtDirFiles.ReadOnly := not btnOk.Enabled; end; procedure TExportSettingsForm.TextToDataset(); var i : Integer; val : TStringArray; s : string; begin if memDBF.Active then memDBF.Close; memDBF.Open; memDBF.EmptyTable; if dsTypes.FieldByName('FILE_BODY').IsNull then Exit; for i :=0 to dbmmoBody.Lines.Count-1 do begin s:= dbmmoBody.Lines[i]; val := explode('&',s); if Length(val) >4 then begin s:=Val[0]; // вернем обратно символ & который заменили при сохранении на [~@#~] s:= ReplaceStr(s,'[~@#~]','&'); memDBF.Append; memDBF['FLDDATA'] := s; if val[1]<>'' then memDBF['FLDNAME'] := val[1]; if val[2]<>'' then memDBF['FLDTYPE'] := val[2]; if val[3]<>'' then memDBF['FLDSIZE'] := StrToInt(val[3]); if val[4]<>'' then memDBF['FLDPERC'] := StrToInt(val[4]); memDBF.Post; end; end; end; function TExportSettingsForm.DatasetToTxt():string; var l,s : string; begin Result := ''; if not memDBF.Active then exit; memDBF.First; while not memDBF.EOF do begin l:=''; if memDBF.FieldByName('FLDDATA').IsNull then s:='' else s:= memDBF.FieldByName('FLDDATA').AsString; s := ReplaceStr(s,'&','[~@#~]'); l:=l+s+'&'; if memDBF.FieldByName('FLDNAME').IsNull then s:='' else s:= AnsiUpperCase(memDBF.FieldByName('FLDNAME').AsString); l:=l+s+'&'; if memDBF.FieldByName('FLDTYPE').IsNull then s:='' else s:= AnsiUpperCase(memDBF.FieldByName('FLDTYPE').AsString); l:=l+s+'&'; if memDBF.FieldByName('FLDSIZE').IsNull then s:='' else s:= memDBF.FieldByName('FLDSIZE').AsString; l:=l+s+'&'; if memDBF.FieldByName('FLDPERC').IsNull then s:='' else s:= memDBF.FieldByName('FLDPERC').AsString; l:=l+s+'&'; Result := Result + l + rsEOL; memDBF.Next; end; end; procedure TExportSettingsForm.dbgDBFExit(Sender: TObject); begin if memDBF.State in [dsEdit, dsInsert] then memDBF.POST; end; procedure TExportSettingsForm.dsTypesBeforePost(DataSet: TDataSet); begin dsTypes.FieldByName('FILE_DIR').AsString := edtDirFiles.Text; if cbbFileFormat.Value = 1 then dsTypes['FILE_BODY'] := DatasetToTxt(); end; procedure TExportSettingsForm.dsTypesNewRecord(DataSet: TDataSet); begin dsTypes['FILE_FORMAT'] := 0; dsTypes['FILE_CODEPAGE'] := 1; pgcFileBody.ActivePageIndex := 0; end; procedure TExportSettingsForm.cbbFileFormatChange(Sender: TObject); begin if not (VarIsNull(cbbFileFormat.Value) or (cbbFileFormat.Text = '')) then pgcFileBody.ActivePageIndex := cbbFileFormat.Value else pgcFileBody.ActivePageIndex := -1; end; end.
unit ChangeAllTablesTest; {* Работа со всеми таблицами документа. } // Модуль: "w:\common\components\gui\Garant\Daily\ChangeAllTablesTest.pas" // Стереотип: "TestCase" // Элемент модели: "TChangeAllTablesTest" MUID: (4C3FEB280134) {$Include w:\common\components\gui\sdotDefine.inc} interface {$If Defined(nsTest) AND NOT Defined(NoVCM)} uses l3IntfUses , TextViaEditorProcessor , evCustomEditor , PrimTextLoad_Form ; type TChangeAllTablesTest = {abstract} class(TTextViaEditorProcessor) {* Работа со всеми таблицами документа. } protected procedure ApplyEditorTool(aEditor: TevCustomEditor); virtual; abstract; {* Вызов инструмента из редактора } procedure Process(aForm: TPrimTextLoadForm); override; {* Собственно процесс обработки текста } function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TChangeAllTablesTest {$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) implementation {$If Defined(nsTest) AND NOT Defined(NoVCM)} uses l3ImplUses , evTypes , TestFrameWork , vcmBase , SysUtils {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , l3Base //#UC START# *4C3FEB280134impl_uses* //#UC END# *4C3FEB280134impl_uses* ; procedure TChangeAllTablesTest.Process(aForm: TPrimTextLoadForm); {* Собственно процесс обработки текста } //#UC START# *4BE13147032C_4C3FEB280134_var* //#UC END# *4BE13147032C_4C3FEB280134_var* begin //#UC START# *4BE13147032C_4C3FEB280134_impl* aForm.Text.Select(ev_stDocument); ApplyEditorTool(aForm.Text); //#UC END# *4BE13147032C_4C3FEB280134_impl* end;//TChangeAllTablesTest.Process function TChangeAllTablesTest.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'Everest'; end;//TChangeAllTablesTest.GetFolder function TChangeAllTablesTest.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4C3FEB280134'; end;//TChangeAllTablesTest.GetModelElementGUID {$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) end.
//m4rcelpl@outlook.com unit RITslip; interface uses Registry, Windows, INIFiles; type TeRITslip = class // TForm1 = class(TForm) private { Private declarations } public { Public declarations } procedure SaveIntegerReg(RootKeyName : HKEY; key : string; keyName : string; value : integer); procedure SaveStringReg(RootKeyName : HKEY; key : string; keyName : string; value : String); procedure SaveBoolReg(RootKeyName : HKEY; key : string; keyName : string; value : Boolean); function ReadStringReg (RootKeyName : HKEY; key : string; keyName : string): String; function ReadIntegerReg (RootKeyName : HKEY; key : string; keyName : string): Integer; function ReadBoolReg (RootKeyName : HKEY; key : string; keyName : string): Boolean; procedure SaveStringIni(iniNeme:String; sectionNeme:String; keyName:string; value:string); function ReadStringIniValue(iniNeme:String; sectionNeme:String; keyName:string): string; end; implementation { TeReg } { Example: RITslip.SaveStringReg(HKEY_LOCAL_MACHINE, 'Software\Test32', 'SomeNameString', 'ValueString'); } procedure TeRITslip.SaveBoolReg(RootKeyName: HKEY; key, keyName: string; value: Boolean); var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); Reg.WriteBool(keyName,value); finally Reg.Free; end; end; procedure TeRITslip.SaveIntegerReg(RootKeyName: HKEY; key, keyName: string; value: integer); var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); Reg.WriteInteger(keyName,value); finally Reg.Free; end; end; procedure TeRITslip.SaveStringReg(RootKeyName: HKEY; key, keyName, value: String); var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); Reg.WriteString(keyName,value); finally Reg.Free; end; end; { Example: RITslip.ReadStringReg(HKEY_LOCAL_MACHINE, 'Software\Test32', 'SomeNameString'; } function TeRITslip.ReadBoolReg(RootKeyName: HKEY; key, keyName: string): Boolean; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); ReadBoolReg := Reg.ReadBool(keyName); finally Reg.Free; end; end; function TeRITslip.ReadIntegerReg(RootKeyName: HKEY; key, keyName: string): Integer; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); ReadIntegerReg := Reg.ReadInteger(keyName); finally Reg.Free; end; end; function TeRITslip.ReadStringReg(RootKeyName: HKEY; key, keyName: string): String; var Reg: TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := RootKeyName; Reg.OpenKey(key,True); ReadStringReg := Reg.ReadString(keyName); finally Reg.Free; end; end; { Example: RITslip.SaveStringIni('c:\plik.ini', 'Section', 'key1', 'SomeValue'); } procedure TeRITslip.SaveStringIni(iniNeme, sectionNeme, keyName, value: string); var INI: TINIFile; begin try INI := TINIFile.Create(iniNeme); INI.WriteString(sectionNeme, keyName, value); finally INI.Free; end; end; { Example: RITslip.ReadStringIniValue('c:\plik.ini', 'Section', 'key1') } function TeRITslip.ReadStringIniValue(iniNeme, sectionNeme, keyName: string): string; var INI: TINIFile; begin try INI := TIniFile.Create(iniNeme); ReadStringIniValue := INI.ReadString(sectionNeme, keyName, ''); finally INI.Free; end; end; end.
unit uStatusVO; interface uses System.SysUtils, uTableName, uKeyField, System.Generics.Collections; type [TableName('Status')] TStatusVO = class private FAtivo: Boolean; FCodigo: Integer; FId: Integer; FNome: string; FNotificarSupervisor: Boolean; FNotificarRevenda: Boolean; FNotificarCliente: Boolean; FConceito: string; FPrograma: Integer; FNotificarConsultor: Boolean; procedure SetAtivo(const Value: Boolean); procedure SetCodigo(const Value: Integer); procedure SetId(const Value: Integer); procedure SetNome(const Value: string); procedure SetConceito(const Value: string); procedure SetNotificarCliente(const Value: Boolean); procedure SetNotificarConsultor(const Value: Boolean); procedure SetNotificarRevenda(const Value: Boolean); procedure SetNotificarSupervisor(const Value: Boolean); procedure SetPrograma(const Value: Integer); public [KeyField('Sta_Id')] property Id: Integer read FId write SetId; [FieldName('Sta_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('Sta_Nome')] property Nome: string read FNome write SetNome; [FieldName('Sta_Ativo')] property Ativo: Boolean read FAtivo write SetAtivo; [FieldName('Sta_Programa')] property Programa: Integer read FPrograma write SetPrograma; [FieldName('Sta_NotificarCliente')] property NotificarCliente: Boolean read FNotificarCliente write SetNotificarCliente; [FieldName('Sta_NotificarSupervisor')] property NotificarSupervisor: Boolean read FNotificarSupervisor write SetNotificarSupervisor; [FieldName('Sta_NotificarConsultor')] property NotificarConsultor: Boolean read FNotificarConsultor write SetNotificarConsultor; [FieldName('Sta_NotificarRevenda')] property NotificarRevenda: Boolean read FNotificarRevenda write SetNotificarRevenda; [FieldName('Sta_Conceito')] property Conceito: string read FConceito write SetConceito; end; TListaStatus = TObjectList<TStatusVO>; implementation { TStatusVO } procedure TStatusVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TStatusVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TStatusVO.SetConceito(const Value: string); begin FConceito := Value; end; procedure TStatusVO.SetId(const Value: Integer); begin FId := Value; end; procedure TStatusVO.SetNome(const Value: string); begin FNome := Value; end; procedure TStatusVO.SetNotificarCliente(const Value: Boolean); begin FNotificarCliente := Value; end; procedure TStatusVO.SetNotificarConsultor(const Value: Boolean); begin FNotificarConsultor := Value; end; procedure TStatusVO.SetNotificarRevenda(const Value: Boolean); begin FNotificarRevenda := Value; end; procedure TStatusVO.SetNotificarSupervisor(const Value: Boolean); begin FNotificarSupervisor := Value; end; procedure TStatusVO.SetPrograma(const Value: Integer); begin FPrograma := Value; end; end.
unit K620665614_H11300096; {* [RequestLink:620665614] } // Модуль: "w:\common\components\rtl\Garant\Daily\K620665614_H11300096.pas" // Стереотип: "TestCase" // Элемент модели: "K620665614_H11300096" MUID: (56FA6D120037) // Имя типа: "TK620665614_H11300096" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoBothNSRCWriterTest ; type TK620665614_H11300096 = class(TEVDtoBothNSRCWriterTest) {* [RequestLink:620665614] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK620665614_H11300096 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *56FA6D120037impl_uses* //#UC END# *56FA6D120037impl_uses* ; function TK620665614_H11300096.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'CrossSegments'; end;//TK620665614_H11300096.GetFolder function TK620665614_H11300096.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '56FA6D120037'; end;//TK620665614_H11300096.GetModelElementGUID initialization TestFramework.RegisterTest(TK620665614_H11300096.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit OfficeLike_System_Controls; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "UserInteraction" // Модуль: "w:/common/components/gui/Garant/VCM/UserInteraction/OfficeLike_System_Controls.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMControls::Category>> Shared Delphi Operations::OfficeLike::UserInteraction::System // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses vcmExternalInterfaces {a} ; (* Common = operations ['{67A198CE-85FB-4827-855C-6DC622DED7D4}'] operation OpenNewWindowByUser; operation GetWindowList; query CascadeWindows; query TileWindowsHorizontal; query TileWindowsVertical; operation CloseAllWindows; end;//Common*) const en_Common = 'Common'; en_capCommon = ''; op_OpenNewWindowByUser = 'OpenNewWindowByUser'; op_capOpenNewWindowByUser = ''; op_GetWindowList = 'GetWindowList'; op_capGetWindowList = ''; op_CascadeWindows = 'CascadeWindows'; op_capCascadeWindows = ''; op_TileWindowsHorizontal = 'TileWindowsHorizontal'; op_capTileWindowsHorizontal = ''; op_TileWindowsVertical = 'TileWindowsVertical'; op_capTileWindowsVertical = ''; op_CloseAllWindows = 'CloseAllWindows'; op_capCloseAllWindows = ''; implementation end.
{*********************************************************************** } { File: VTreeData.pas } { } { Purpose: } { source file to demonstrate how to get started with VT (5) } { <-- Basic node data class wrapped in a record allowing for --> } { } { Credits: } { taken + modified from example by Sven H. (h.sven@gmx.at) } { } { Module Record: } { } { Date AP Details } { -------- -- -------------------------------------- } { 05-Nov-2002 TC Created (tomc@gripsystems.com) } {**********************************************************************} unit VTreeData; {$mode delphi} {$H+} interface uses LCLIntf, Messages, SysUtils, Classes, Graphics, VirtualTrees; type // declare common node class TBasicNodeData = class protected FCaption : shortstring; FID : longint; FImageIndex : longint; FHasChanged : boolean; public constructor Create( const sCaption : shortstring; const iID, iIndex: longint); property Caption : shortstring read FCaption write FCaption; property ID : longint read FID write FID; property ImageIndex : longint read FImageIndex write FImageIndex; property HasChanged : boolean read FHasChanged write FHasChanged; end; // declare descendant node class TBasicNodeAddData = class(TBasicNodeData) protected FJobTitle : shortstring; FAdd1 : shortstring; FAdd2 : shortstring; FAdd3 : shortstring; public property Add1 : shortstring read FAdd1 write FAdd1; property Add2 : shortstring read FAdd2 write FAdd2; property Add3 : shortstring read FAdd3 write FAdd3; property JobTitle : shortstring read FJobTitle write FJobTitle; end; (*-------------------------------------------------------------------------------------- This is a very simple record we use to store data in the nodes. Since the application is responsible to manage all data including the node's caption this record can be considered as minimal requirement in all VT applications using this method (as opposed to a pre-defined record). Note that this also means individual nodes can store different descendants from TBasicNodeData --------------------------------------------------------------------------------------*) PBasicNodeRec= ^TBasicNodeRec; TBasicNodeRec = record bnd : TBasicNodeData; end; implementation constructor TBasicNodeData.Create( const sCaption : shortstring; const iID, iIndex: longint); begin inherited Create; FCaption := sCaption; FID := iID; FImageIndex := iIndex; end; end.
unit steXmlPreProcessor; {$mode objfpc}{$H+} (* Preprocessor markup structure: {{#-03 inner-tag-with-params }} ^ ^ ^ ^ ^ | | | | | | | | | +-----> Preprocessor's TagCloseToken | | | +-------------------------> A inner tag, usable by TSTEParser, without enclosing | | +-----------------------------> Any space char(s) | +--------------------------------> LevelIndent, integer (with sign), should be valid for StrToInt() +-----------------------------------> Preprocessor's TagOpenToken LevelIndent is a (signed) number of generations (parents) you need to move tag accros xml tree. Positive inserts tag before (grand...grand) parent node, negative inserts after (closing part of) it. Example: <table> <headers> <cell1></cell1> <cell2></cell2> <cell3></cell3> </headers> <row> <cell1>[[#-2 before row]]</cell1> <cell2>[[#3 after table]]</cell2> <cell3></cell3> </row> </table> When moving through xml-tree, inner-tag-with-params will be enclosed by associated TSTEParser tokens. So pairs of enclosing tokens for TSTEXMLPreProcessor and TSTEParser should differ (at least for TagOpenToken) Multiple preprocesor tags within a single node is not (yet?) supported. Preprocesor tag + regualr template tags is OK. *) interface uses Classes, SysUtils, laz2_DOM, laz2_XMLRead, laz2_XMLWrite, steParser; type TSTEXMLPreProcessor = class private FTagCloseToken : string; FTagOpenToken : string; FTagOpenTokenLen, FTagCloseTokenLen : integer; FDoc : TXMLDocument; procedure SetTagCloseToken(AValue : string); procedure SetTagOpenToken(AValue : string); procedure ProcessNode(ANode : TDOMNode; ALevel : integer); procedure CheckNode(ANode : TDOMNode); function ParseTag(const ANodeSourceText : string; out AInnerTagText, ANodeText : string; out AIndentLevel : integer) : boolean; procedure CreateIndentedNode(ARefNode : TDOMNode; AIndentLevel : integer; const AInnerTagText : string); public // when replaced, tag will be enclosed by these two ParserTagOpenToken, ParserTagCloseToken : string; property TagOpenToken : string read FTagOpenToken write SetTagOpenToken; property TagCloseToken : string read FTagCloseToken write SetTagCloseToken; procedure Process(ASource, AResult : TStream); function Process(ASource : TStream) : string; // Result as string // todo: set title //<office:meta> // <dc:title>Title</dc:title> //</office:meta> constructor Create(const ATagOpenToken : string = '[[#'; const ATagCloseToken : string = ']]'); end; // preprocess & prepare oneliner function PrepareXMLTemplate(ASource : TStream; AParser : TSTEParser = nil) : TSTEParsedTemplateData; implementation uses strutils, math, steCommon{, LazLogger}; //{$define DEBUG_STE_XMLPARSER} function PrepareXMLTemplate(ASource : TStream; AParser : TSTEParser) : TSTEParsedTemplateData; var parser : TSTEParser; {$ifdef DEBUG_STE_XMLPARSER} dumpFS : TFileStream; dump : string; {$endif} begin with TSTEXMLPreProcessor.Create do try if AParser <> nil then parser := TSTEParser.Create else parser := AParser; // use external parser try parser.TagOpenToken := ParserTagOpenToken; parser.TagCloseToken := ParserTagCloseToken; {$ifdef DEBUG_STE_XMLPARSER} dump := Process(ASource); dumpFS := TFileStream.Create('preprocessed.xml', fmCreate); try dumpFS.Write(dump[1], Length(dump)); Result := parser.Prepare( dump ); finally dumpFS.Free; end; {$else} Result := parser.Prepare( Process(ASource) ); {$endif} finally if AParser <> nil then parser.Free; end; finally Free; end; end; procedure TSTEXMLPreProcessor.SetTagCloseToken(AValue : string); begin if FTagCloseToken = AValue then Exit; FTagCloseToken := AValue; FTagCloseTokenLen := Length(FTagCloseToken); end; procedure TSTEXMLPreProcessor.SetTagOpenToken(AValue : string); begin if FTagOpenToken = AValue then Exit; FTagOpenToken := AValue; FTagOpenTokenLen := Length(FTagOpenToken); end; procedure TSTEXMLPreProcessor.ProcessNode(ANode : TDOMNode; ALevel : integer); var i : Integer; begin CheckNode(ANode); with ANode.ChildNodes do try for i := 0 to (Count - 1) do begin ANode := Item[i]; ProcessNode(ANode, ALevel+1); end; finally Free; end; end; procedure TSTEXMLPreProcessor.CheckNode(ANode : TDOMNode); var innerTagText, nodeReplacementText : string; AIndentLevel : integer; begin if ANode.NodeType = TEXT_NODE then begin if ParseTag(ANode.NodeValue, innerTagText, nodeReplacementText, AIndentLevel) then begin if AIndentLevel = 0 then raise ESTEParserError.CreateFmt('%s: Invalid indent token `%s`', [ Self.ClassName, ANode.NodeValue ]); CreateIndentedNode(ANode, AIndentLevel, innerTagText); ANode.NodeValue := nodeReplacementText; // replace text end; end; end; procedure TSTEXMLPreProcessor.CreateIndentedNode(ARefNode : TDOMNode; AIndentLevel : integer; const AInnerTagText : string); var i, absLvl : integer; AIndentNode, ANewNode : TDOMNode; begin absLvl := abs(AIndentLevel); AIndentNode := ARefNode; for i := 1 to absLvl do begin AIndentNode := AIndentNode.ParentNode; if AIndentNode = nil then raise ESTEParserError.CreateFmt('%s: Invalid indent level %d (no parent) of %d in `%s`', [ Self.ClassName, i, AIndentLevel, ARefNode.NodeValue ]); end; ANewNode := FDoc.CreateTextNode( ParserTagOpenToken + AInnerTagText + ParserTagCloseToken); //ANewNode := FDoc.CreateComment( ParserTagOpenToken + AInnerTagText + ParserTagCloseToken); if Sign(AIndentLevel) < 0 then begin // before parent AIndentNode.ParentNode.InsertBefore(ANewNode, AIndentNode); end else if Sign(AIndentLevel) > 0 then begin if AIndentNode.NextSibling <> nil then begin// before next sibling AIndentNode.ParentNode.InsertBefore(ANewNode, AIndentNode.NextSibling); end else // append (last) child AIndentNode.ParentNode.AppendChild(ANewNode); end; end; function TSTEXMLPreProcessor.ParseTag(const ANodeSourceText : string; out AInnerTagText, ANodeText : string; out AIndentLevel : integer) : boolean; var i, openTagPos, closeTagPos : integer; AIndentText, tagText : string; begin Result := false; openTagPos := Pos(TagOpenToken, ANodeSourceText); if openTagPos > 0 then begin i := openTagPos + FTagOpenTokenLen; closeTagPos := PosEx(TagCloseToken, ANodeSourceText, i); if closeTagPos > 0 then begin // Inner tag text tagText := Trim( Copy(ANodeSourceText, i, closeTagPos - i) ); // copy NodeText without TagText ANodeText := Copy(ANodeSourceText, 1, openTagPos-1); i := Length(ANodeSourceText); ANodeText += Copy(ANodeSourceText, closeTagPos + FTagCloseTokenLen, i - (closeTagPos + FTagCloseTokenLen) + 1 ); // Indent AIndentText := ExtractWordPos(1, tagText, steWhiteSpaceChars, i); AIndentLevel := StrToIntDef(AIndentText, 0); i += Length(AIndentText); AInnerTagText := Trim( Copy(tagText, i, Length(tagText)-i+1 ) ); Result := true; end; end; end; procedure TSTEXMLPreProcessor.Process(ASource, AResult : TStream); var ANode : TDOMNode; begin ReadXMLFile(FDoc, ASource); try ANode := FDoc.DocumentElement{.FirstChild}; while Assigned(ANode) do begin ProcessNode(ANode, 0); ANode := ANode.NextSibling; end; // write results WriteXML(FDoc, AResult); finally FreeAndNil(FDoc); end; end; function TSTEXMLPreProcessor.Process(ASource : TStream) : string; var ms : TMemoryStream; begin ms := TMemoryStream.Create; try Process(ASource, ms); ms.Position := 0; SetLength(Result, ms.Size); ms.Read(Result[1], ms.Size); finally ms.Free; end; end; constructor TSTEXMLPreProcessor.Create(const ATagOpenToken : string; const ATagCloseToken : string); begin // set defaults TagOpenToken := ATagOpenToken; TagCloseToken := ATagCloseToken; ParserTagOpenToken := '{{'; ParserTagCloseToken := '}}'; end; end.
unit TrackingHistoryResponseUnit; interface uses REST.Json.Types, System.Generics.Collections, GenericParametersUnit, NullableBasicTypesUnit, JSONNullableAttributeUnit, CommonTypesUnit, TrackingHistoryUnit; type TTrackingHistorySummary = class(TGenericParameters) private [JSONName('total_distance')] [Nullable] FTotalDistance: NullableDouble; [JSONName('matched_time')] [Nullable] FMatchedTime: NullableInteger; [JSONName('matched_distance')] [Nullable] FMatchedDistance: NullableDouble; [JSONName('total_time')] [Nullable] FTotalTime: NullableInteger; [JSONName('trace_time')] [Nullable] FTraceTime: NullableInteger; [JSONName('trace_distance')] [Nullable] FTraceDistance: NullableDouble; public constructor Create; override; property TotalDistance: NullableDouble read FTotalDistance write FTotalDistance; property MatchedTime: NullableInteger read FMatchedTime write FMatchedTime; property MatchedDistance: NullableDouble read FMatchedDistance write FMatchedDistance; property TotalTime: NullableInteger read FTotalTime write FTotalTime; property TraceTime: NullableInteger read FTraceTime write FTraceTime; property TraceDistance: NullableDouble read FTraceDistance write FTraceDistance; end; TMmd = class(TGenericParameters) private [JSONName('status')] [Nullable] FStatus: NullableInteger; [JSONName('summary')] [NullableObject(TTrackingHistorySummary)] FSummary: NullableObject; public constructor Create; override; destructor Destroy; override; property Status: NullableInteger read FStatus write FStatus; property Summary: NullableObject read FSummary write FSummary; end; TTrackingHistoryResponse = class(TGenericParameters) private [JSONName('data')] [NullableArray(TTrackingHistory)] FTrackingHistories: TTrackingHistoryArray; [JSONName('mmd')] [NullableObject(TMmd)] FMmd: NullableObject; function GetMmd: TMmd; public constructor Create; override; destructor Destroy; override; property TrackingHistories: TArray<TTrackingHistory> read FTrackingHistories; property Mmd: TMmd read GetMmd; end; implementation constructor TTrackingHistoryResponse.Create; begin inherited; SetLength(FTrackingHistories, 0); FMmd := NullableObject.Null; end; destructor TTrackingHistoryResponse.Destroy; begin FMmd.Free; inherited; end; function TTrackingHistoryResponse.GetMmd: TMmd; begin if (FMmd.IsNotNull) then Result := FMmd.Value as TMmd else Result := nil; end; { TTrackingHistorySummary } constructor TTrackingHistorySummary.Create; begin inherited; FTotalDistance := NullableDouble.Null; FMatchedTime := NullableInteger.Null; FMatchedDistance := NullableDouble.Null; FTotalTime := NullableInteger.Null; FTraceTime := NullableInteger.Null; FTraceDistance := NullableDouble.Null; end; { TMmd } constructor TMmd.Create; begin inherited; Status := NullableInteger.Null; FSummary := NullableObject.Null; end; destructor TMmd.Destroy; begin FSummary.Free; inherited; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 <http://www.gnu.org/licenses/>. } unit frmDirectoryDetail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, cxMaskEdit, cxButtonEdit, cxLabel, cxMemo, cxRichEdit, cxContainer, cxEdit, cxTextEdit, cxPC, cxControls, StdCtrls, cxButtons, ExtCtrls, OraDirectory, cxGroupBox; type TDirectoryDetailFrm = class(TForm) pc: TcxPageControl; tsDirectory: TcxTabSheet; tsDDL: TcxTabSheet; redtDDL: TcxRichEdit; cxGroupBox1: TcxGroupBox; edtName: TcxTextEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; edtPath: TcxButtonEdit; Bevel1: TBevel; cxGroupBox2: TcxGroupBox; btnExecute: TcxButton; btnCancel: TcxButton; procedure btnCancelClick(Sender: TObject); procedure pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure btnExecuteClick(Sender: TObject); private { Private declarations } FDBDirectory: TDBDirectory; procedure GetDBDirectory; function SetDBDirectory: boolean; public { Public declarations } function Init(ADBDirectory: TDBDirectory): boolean; end; var DirectoryDetailFrm: TDirectoryDetailFrm; implementation {$R *.dfm} uses Util, frmSchemaBrowser, GenelDM, OraStorage, VisualOptions; function TDirectoryDetailFrm.Init(ADBDirectory: TDBDirectory): boolean; begin DirectoryDetailFrm := TDirectoryDetailFrm.Create(Application); Self := DirectoryDetailFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FDBDirectory := TDBDirectory.Create; FDBDirectory := ADBDirectory; GetDBDirectory; pc.ActivePage := tsDirectory; ShowModal; result := ModalResult = mrOk; Free; end; procedure TDirectoryDetailFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TDirectoryDetailFrm.GetDBDirectory; begin if FDBDirectory.DIRECTORY_NAME = '' then Caption := 'Create Database Directory ' else Caption := 'Alter Database Directory '+FDBDirectory.DIRECTORY_NAME; edtName.Text := FDBDirectory.DIRECTORY_NAME; edtPath.Text := FDBDirectory.DIRECTORY_PATH; edtName.Enabled := FDBDirectory.DIRECTORY_NAME = ''; end; //GetDBDirectory; function TDirectoryDetailFrm.SetDBDirectory: boolean; begin result := true; if edtName.Text = '' then begin MessageDlg('Directory Name must be specified', mtWarning, [mbOk], 0); result := false; exit; end; if edtPath.Text = '' then begin MessageDlg('Directory Path must be specified', mtWarning, [mbOk], 0); result := false; exit; end; with FDBDirectory do begin DIRECTORY_NAME := edtName.Text; DIRECTORY_PATH := edtPath.Text; end; //FDBDirectory end; //SetDBDirectory procedure TDirectoryDetailFrm.pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin if NewPage = tsDDL then begin if not SetDBDirectory then AllowChange := false else begin redtDDL.Text := FDBDirectory.GetDDL end; CodeColors(self, 'Default', redtDDL, false); end; end; procedure TDirectoryDetailFrm.btnExecuteClick(Sender: TObject); begin if not SetDBDirectory then exit; redtDDL.Text := FDBDirectory.GetDDL; if FDBDirectory.CreateDBDirectory(redtDDL.Text) then ModalResult := mrOK; end; end.
unit IOUnit; {* пакет интерфейсов ввода-вывода } // Модуль: "w:\shared\tie\Garant\GCI\IOUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "IO" MUID: (4423F94903C8) interface uses l3IntfUses ; type OperationError = class {* Во время выполнения операции copy_to один из потоков, участвовавших в операции перешёл в некорректное состояние. } end;//OperationError NotImplemented = class {* функция не реализована } end;//NotImplemented IString = interface {* Интерфейс для работы со строками. Предпочтительно использовать именно этот тип для работы со всеми строковыми данными. } ['{952E8D0E-1685-49D2-BFDB-D854F4BF0156}'] function GetLength: Cardinal; stdcall; function GetMaximum: Cardinal; stdcall; procedure SetMaximum(aValue: Cardinal); stdcall; function GetData: PAnsiChar; stdcall; function GetCodePage: short; stdcall; procedure SetCodePage(aValue: short); stdcall; procedure Reset(var str: PAnsiChar; maximum: Cardinal); overload; stdcall; {* Захватывает переданную строку. Если аргумент, задающий длину, меньше чем strlen(str) + 1, то длина строки принимается равной длине строки + 1. Память под передаваемый аргумент str ДОЛЖНА БЫТЬ ВЫДЕЛЕНА оператором new[], так как в деструкторе вызывается оператор delete[]. } procedure Reset(str: PAnsiChar); overload; stdcall; {* устанавливает значение строки равное переданному (переданная строка копируеться) } procedure Strdup(out aRet {* IString }); stdcall; {* возвращает бинарную копию строки } function Add(str: PAnsiChar): PAnsiChar; overload; stdcall; {* добавляет к строке переданную подстроку, возвращает указатель на свой буфер } function Add(const str: IString): PAnsiChar; overload; stdcall; {* добавляет к строке переданную подстроку, возвращает указатель на свой буфер } function Join(str: PAnsiChar): PAnsiChar; overload; stdcall; {* возвращает новую строку равную объединению текущей и переданной } function Join(const str: IString): PAnsiChar; overload; stdcall; {* возвращает новую строку равную объединению текущей и переданной } property Length: Cardinal read GetLength; {* длинна текстовой строки } property Maximum: Cardinal read GetMaximum write SetMaximum; {* размер аллоцированого буфера, для хранения текстовой строки } property Data: PAnsiChar read GetData; {* указатель на начало аллоцированного буфера (строки) } property CodePage: short read GetCodePage write SetCodePage; {* кодовая страница } end;//IString TStreamSeekDirection = ( {* точка от которой считается смещение. Константы должны совпадать по значению с MSDN-овскими } SSD_BEGIN {* смещение относительно начала потока } , SSD_CURRENT {* смещение относительнотекущей позиции в потоке } , SSD_END {* смещение относительно конца потока } );//TStreamSeekDirection IStream = interface {* Интерфейс для работы с потоком } ['{D99F458B-CF9F-4286-AD02-59ABA1662465}'] function Read(var buffer: pointer; size: Cardinal): Cardinal; stdcall; { can raise OperationError } {* Прочесть данные из потока, возвращает количество прочитанных байтов. } function Write(buffer: pointer; size: Cardinal): Cardinal; stdcall; {* Записать данные в поток. Возвращает количество записанных байтов. } function Seek(offset: Integer; whence: Cardinal): Cardinal; stdcall; { can raise OperationError, NotImplemented } {* Переместить маркер потока. Возвращает число байт от начала потока. } procedure CopyTo(var dst: IStream; size: Cardinal; out actually_read: unsigned long long; out actually_written: unsigned long long); stdcall; { can raise OperationError } {* Копирует данные из одного потока в другой. } function Eof: ByteBool; stdcall; {* Функция возвращает true если достигнут конец потока. } function Bad: ByteBool; stdcall; {* Если возвращается true, дальнейшая работа с потоком невозможна } procedure Clear; stdcall; {* Чистит флаги потока } end;//IStream TDateTimeBox = record {* для универсальной передачи времени между разными языками, платформами. } day: short; {* день в месяце (1-31) } mounth: short; {* месяц в году (1-12) } year: short; {* год } hour: short; {* час (0-23) } minute: short; {* минута в часе (0-59) } second: short; {* секунда в минуте (0-59) } millisecond: short; {* миллисекунды (0-999) } end;//TDateTimeBox implementation uses l3ImplUses ; end.